An open-source, faster Devin alternative
TypeScript
fork reliability and cleanup
Brian Reardon9fb6c9a6cd18
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.goindex e1fd25a2..06f52a8e 100644--- a/cmd/agent/listen_linux.go+++ b/cmd/agent/listen_linux.go@@ -72,13 +72,6 @@ type virtioSerialListener struct {closed chan struct{}mu sync.Mutexactive bool // true when a connection is being served- // activeConn tracks the conn handed to gRPC so PrepareHibernate can- // force-close it before savevm captures state. Without this, the- // gRPC server's HTTP/2 parser state survives savevm/loadvm and gets- // fed garbage from the next worker's handshake — the post-loadvm- // "agent not ready" race that surfaces ~5% under fork stress and- // indefinitely on prod-style restore.- activeConn *virtioSerialConn}func listenVirtioSerial(path string) (net.Listener, error) {@@ -118,15 +111,13 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {}l.mu.Unlock()- // Clear any read deadline left over from PrepareHibernate's conn- // teardown — without this, poll/Read on this fd would immediately- // return ErrDeadlineExceeded forever.- _ = l.f.SetReadDeadline(time.Time{})-// Drain any stale data from the previous gRPC session.// After a gRPC connection drops, the serial port may have leftover// bytes (GOAWAY frames, partial HTTP/2 frames). If we hand these to// the new gRPC session, it gets a protocol error and closes immediately.+ if instrumentVirtioSerial {+ log.Printf("virtio-serial: Accept iter: active=false, draining stale...")+ }drainStaleData(l.f)// Wait for the host to connect (port becomes readable with fresh data)@@ -140,22 +131,17 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {l.mu.Unlock()continue}- conn := &virtioSerialConn{+ l.active = true+ l.mu.Unlock()+ log.Printf("agent: virtio-serial Accept: port readable, accepting connection")+ return &virtioSerialConn{f: l.f,onClose: func() {l.mu.Lock()l.active = false- if l.activeConn != nil {- l.activeConn = nil- }l.mu.Unlock()},- }- l.active = true- l.activeConn = conn- l.mu.Unlock()- log.Printf("agent: virtio-serial Accept: port readable, accepting connection")- return conn, nil+ }, nil}}@@ -198,41 +184,14 @@ func waitForReadable(f *os.File, timeout time.Duration) bool {return fds[0].Revents&(unix.POLLIN|unix.POLLHUP) != 0}-// PrepareHibernate resets the active flag AND wakes up the gRPC server's-// blocked Read goroutine via a past read deadline, then clears the deadline-// before the next Accept cycle.-//-// Why this matters: without forcing the gRPC server to release the conn, its-// HTTP/2 parser state (in-flight frames, keepalive pings) gets captured by-// savevm. On the next worker's loadvm + reconnect, that captured parser-// tries to interpret fresh HTTP/2 SETTINGS frames as continuation of the-// old stream, consumes bytes but fails at semantics, and stays in the bad-// state past the worker's 30s agent-connect timeout. By setting the read-// deadline in the past, the blocked Read returns ErrDeadlineExceeded, gRPC-// treats it as a conn error and drops the stream cleanly. Now savevm-// captures an idle, drained chardev with no parser in flight.-//-// The deadline reset happens at the top of Accept (see resetReadDeadline)-// so future connections are unaffected.+// PrepareHibernate resets the active flag so that after migration restore,+// the Accept loop will poll for a new host-side connection instead of+// thinking the old connection is still active.func (l *virtioSerialListener) PrepareHibernate() {l.mu.Lock()- conn := l.activeConn- l.activeConn = nill.active = falsel.mu.Unlock()log.Printf("agent: virtio-serial: prepared for hibernate (active=false)")- if conn == nil {- return- }- // Give the PrepareHibernate response time to flush before disrupting- // the conn. 50ms is more than enough on a virtio-serial pipe.- go func() {- time.Sleep(50 * time.Millisecond)- // SetReadDeadline in the past wakes up the blocked Read goroutine- // inside gRPC's HTTP/2 transport with os.ErrDeadlineExceeded.- _ = conn.f.SetReadDeadline(time.Now().Add(-1 * time.Second))- log.Printf("agent: virtio-serial: triggered conn teardown (frees gRPC parser state for clean savevm)")- }()}func (l *virtioSerialListener) Close() error {@@ -258,10 +217,41 @@ type virtioSerialConn struct {once sync.Once}-func (c *virtioSerialConn) Read(b []byte) (int, error) { return c.f.Read(b) }-func (c *virtioSerialConn) Write(b []byte) (int, error) { return c.f.Write(b) }+// instrumentVirtioSerial controls per-Read logging on the conn. Set true via+// OSB_AGENT_TRACE_VIRTIO=1 env var to debug post-loadvm protocol confusion.+// HARDCODED TO TRUE FOR INVESTIGATION BUILD — revert before merging.+var instrumentVirtioSerial = true || os.Getenv("OSB_AGENT_TRACE_VIRTIO") == "1"++func (c *virtioSerialConn) Read(b []byte) (int, error) {+ n, err := c.f.Read(b)+ if instrumentVirtioSerial {+ // Log first 16 bytes (or fewer) so we can spot HTTP/2 prefaces+ // that might be from a NEW gRPC session being fed to the OLD parser.+ // HTTP/2 preface is 24 bytes starting with "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".+ preview := ""+ if n > 0 {+ max := n+ if max > 16 {+ max = 16+ }+ preview = fmt.Sprintf(" first=%q", b[:max])+ }+ log.Printf("virtio-serial: conn.Read n=%d err=%v%s", n, err, preview)+ }+ return n, err+}+func (c *virtioSerialConn) Write(b []byte) (int, error) {+ n, err := c.f.Write(b)+ if instrumentVirtioSerial && err != nil {+ log.Printf("virtio-serial: conn.Write n=%d err=%v", n, err)+ }+ return n, err+}func (c *virtioSerialConn) Close() error {c.once.Do(func() {+ if instrumentVirtioSerial {+ log.Printf("virtio-serial: conn.Close called (gRPC dropped this conn)")+ }if c.onClose != nil {c.onClose()}diff --git a/cmd/agent/reaper_linux.go b/cmd/agent/reaper_linux.goindex 19256aac..073c1b62 100644--- a/cmd/agent/reaper_linux.go+++ b/cmd/agent/reaper_linux.go@@ -8,6 +8,8 @@ import ("os/signal""sync/atomic""syscall"++ "github.com/opensandbox/opensandbox/internal/agent")// startReaper spawns a goroutine that waits on SIGCHLD and reaps any@@ -19,6 +21,17 @@ import (//// Also calls prctl(PR_SET_CHILD_SUBREAPER) defensively so reaping still// works even if some future setup parents us to PID > 1.+//+// Coordination with os/exec: when the agent forks a child via os/exec+// (the Exec/PrepareHibernate paths), os/exec wants to call Wait4 on its+// own child. Without coordination the reaper and os/exec race; whichever+// wait4 lands first gets the exit status and the other gets ECHILD. The+// loser returns "waitid: no child processes" up the stack — visible to+// users as ~30% fork failures with empty stdout when bench-style workloads+// hit the agent right after a fork. We fix this via RegisterManagedPid:+// the reaper checks the registry before recording a reap, and if the pid+// is managed it delivers the exit status via channel instead of letting+// os/exec call wait4 (since the reaper already did).func startReaper() {// Best-effort: PR_SET_CHILD_SUBREAPER (option 36). If running as PID 1// this is a no-op; if not, it makes us inherit orphans of our subtree.@@ -39,6 +52,13 @@ var reapedTotal atomic.Int64// drainZombies repeatedly waits for any child in non-blocking mode until// none are available. Multiple SIGCHLDs that arrive while we're already// reaping coalesce into one delivery, so each notification must drain all.+//+// For each reaped pid, agent.TryDeliverReap is consulted: if the pid is+// in the registry (explicit-wait by Exec/PrepareHibernate/PTY), the status+// is forwarded via channel rather than logged as an orphan reap. The+// caller's cmd.Wait() will see ECHILD (the kernel already gave up the+// status to us) and pull the WaitStatus from the channel. See+// internal/agent/reap_registry.go for the protocol.func drainZombies() {for {var ws syscall.WaitStatus@@ -50,6 +70,11 @@ func drainZombies() {}return}+ // If a caller is explicitly waiting on this pid, hand off the+ // status and skip the orphan-reap logging path.+ if agent.TryDeliverReap(pid, ws) {+ continue+ }n := reapedTotal.Add(1)// Log first few + every 100th so the journal stays readable.if n <= 5 || n%100 == 0 {diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 149bdba6..0bb408a9 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -133,6 +133,12 @@ func main() {qmMgr.CleanupOrphanedProcesses()+ // Start the periodic orphan reaper. Catches qemu processes that+ // survived a destroyVM-path failure (state-inconsistency / panic /+ // hibernate race) so they don't pile up and silently shrink worker+ // capacity. See internal/qemu/orphan_reaper.go.+ qmMgr.StartOrphanReaper(ctx)+// Prepare golden snapshot for fast VM creationif err := qmMgr.PrepareGoldenSnapshot(); err != nil {log.Printf("opensandbox-worker: WARNING: golden snapshot failed, using cold boot: %v", err)diff --git a/internal/agent/exec.go b/internal/agent/exec.goindex 0403c5dc..dce4bf36 100644--- a/internal/agent/exec.go+++ b/internal/agent/exec.go@@ -3,6 +3,7 @@ package agentimport ("bytes""context"+ "errors""fmt""os""os/exec"@@ -108,7 +109,12 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponsif err := cmd.Start(); err != nil {return nil, fmt.Errorf("exec start: %w", err)}- moveToCgroup(cmd.Process.Pid)+ pid := cmd.Process.Pid+ // Register with reaper BEFORE the child can exit. If the SIGCHLD reaper+ // races us and reaps the child first, cmd.Wait() returns ECHILD; we+ // recover the status from this channel. See reap_registry.go.+ exitCh := RegisterReap(pid)+ moveToCgroup(pid)// Wait with cgroup kill on timeout — if the process doesn't exit when the// context deadline fires, kill the entire sandbox cgroup to clean up fork@@ -127,6 +133,7 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons}killCgroup()<-waitDone // wait for cmd.Wait to return after kills+ UnregisterReap(pid)return &pb.ExecResponse{ExitCode: -1,Stdout: stdout.String(),@@ -136,11 +143,22 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponsexitCode := 0if err != nil {- if exitErr, ok := err.(*exec.ExitError); ok {- exitCode = exitErr.ExitCode()- } else {+ switch {+ case isExitError(err):+ exitCode = err.(*exec.ExitError).ExitCode()+ UnregisterReap(pid)+ case errors.Is(err, syscall.ECHILD):+ // Reaper got there first; pull WaitStatus from registry channel.+ // The reaper has already populated it (otherwise wait4 would+ // have returned the status to cmd.Wait, not ECHILD).+ ws := <-exitCh+ exitCode = ws.ExitStatus()+ default:+ UnregisterReap(pid)return nil, fmt.Errorf("exec failed: %w", err)}+ } else {+ UnregisterReap(pid)}return &pb.ExecResponse{@@ -150,6 +168,11 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons}, nil}+func isExitError(err error) bool {+ _, ok := err.(*exec.ExitError)+ return ok+}+// ExecStream runs a command and streams stdout/stderr chunks.func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStreamServer) error {timeout := time.Duration(req.TimeoutSeconds) * time.Seconddiff --git a/internal/agent/reap_registry.go b/internal/agent/reap_registry.gonew file mode 100644index 00000000..7fc562fa--- /dev/null+++ b/internal/agent/reap_registry.go@@ -0,0 +1,58 @@+package agent++import (+ "sync"+ "syscall"+)++// ReapRegistry coordinates the agent's SIGCHLD reaper with explicit-wait+// callers (Exec, PrepareHibernate, PTY). Without coordination the reaper's+// Wait4(-1, ...) races with cmd.Wait() — whichever lands first gets the+// child's exit status, and the other returns ECHILD. The loser's caller+// reports `exec failed: waitid: no child processes`, surfacing to users+// as ~30% fork failures with empty stdout when bench-style workloads hit+// the agent immediately after a fresh fork.+//+// Coordination protocol:+// 1. Caller (Exec handler) calls RegisterReap(pid) BEFORE the child can+// exit (immediately after cmd.Start()).+// 2. Caller calls cmd.Wait() in the usual way.+// 3a. If cmd.Wait() succeeds, child status is in cmd.ProcessState. Caller+// should call UnregisterReap(pid) to drop the dangling registration.+// 3b. If cmd.Wait() returns ECHILD, the reaper got there first; pull+// the WaitStatus from the channel and synthesize the exit code.+//+// The reaper (cmd/agent/reaper_linux.go) calls TryDeliverReap on every+// child it consumes. If the pid is registered, it forwards the status via+// channel; otherwise it logs the orphan reap as before.+var reapRegistry sync.Map // pid (int) → chan syscall.WaitStatus++// RegisterReap claims a pid for explicit-wait. Returns a channel that+// receives the wait status when the reaper picks up the child. Channel is+// closed after the status is delivered.+func RegisterReap(pid int) <-chan syscall.WaitStatus {+ ch := make(chan syscall.WaitStatus, 1)+ reapRegistry.Store(pid, ch)+ return ch+}++// UnregisterReap removes a pid registration without consuming a status.+// Use when cmd.Wait() succeeded and you no longer need the channel.+func UnregisterReap(pid int) {+ reapRegistry.Delete(pid)+}++// TryDeliverReap is called by the SIGCHLD reaper for each child it reaps.+// If the pid is registered, the status is delivered via channel and true+// is returned (so the reaper can skip its orphan-log path). Otherwise+// returns false — caller should log this as an orphan reap.+func TryDeliverReap(pid int, ws syscall.WaitStatus) bool {+ v, ok := reapRegistry.LoadAndDelete(pid)+ if !ok {+ return false+ }+ ch := v.(chan syscall.WaitStatus)+ ch <- ws+ close(ch)+ return true+}diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.goindex 01292c15..9f85e6a0 100644--- a/internal/qemu/agent_client.go+++ b/internal/qemu/agent_client.go@@ -4,14 +4,19 @@ import ("context""fmt""io"+ "log""net"+ "strings"+ "sync""time""golang.org/x/sys/unix""google.golang.org/grpc""google.golang.org/grpc/backoff"+ "google.golang.org/grpc/codes""google.golang.org/grpc/credentials/insecure""google.golang.org/grpc/keepalive"+ "google.golang.org/grpc/status"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -19,51 +24,61 @@ import (const streamChunkSize = 256 * 1024 // 256KB per gRPC chunk// AgentClient is the host-side gRPC client that connects to the-// osb-agent running inside a QEMU VM via AF_VSOCK.+// osb-agent running inside a QEMU VM via AF_VSOCK or virtio-serial.+//+// dialer captures the constructor's dial logic so Redial can rebuild the+// connection without the caller knowing whether this is vsock or virtio-+// serial transport. This is the recovery path for the post-loadvm protocol-+// confusion bug and the prod 10-min-after-restore agent disconnect: when an+// RPC fails with a transport error, the caller invokes Redial and retries.type AgentClient struct {+ mu sync.Mutexconn *grpc.ClientConnclient pb.SandboxAgentClient+ dialer func() (*grpc.ClientConn, error)}// NewAgentClient connects to the agent via AF_VSOCK using the guest CID.// QEMU uses the kernel's vhost-vsock directly — no UDS file needed.// Port 1024 is the agent gRPC server inside the VM.func NewAgentClient(guestCID uint32) (*AgentClient, error) {- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- conn, err := grpc.DialContext(ctx,- "passthrough:///vsock",- grpc.WithTransportCredentials(insecure.NewCredentials()),- grpc.WithBlock(),- grpc.WithConnectParams(grpc.ConnectParams{- Backoff: backoff.Config{- BaseDelay: 10 * time.Millisecond,- Multiplier: 1.6,- Jitter: 0.2,- 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)- }),- grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(256*1024*1024),- grpc.MaxCallSendMsgSize(256*1024*1024),- ),- )+ dialer := func() (*grpc.ClientConn, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ return grpc.DialContext(ctx,+ "passthrough:///vsock",+ grpc.WithTransportCredentials(insecure.NewCredentials()),+ grpc.WithBlock(),+ grpc.WithConnectParams(grpc.ConnectParams{+ Backoff: backoff.Config{+ BaseDelay: 10 * time.Millisecond,+ Multiplier: 1.6,+ Jitter: 0.2,+ 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)+ }),+ grpc.WithDefaultCallOptions(+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),+ ),+ )+ }+ conn, err := dialer()if err != nil {return nil, fmt.Errorf("connect to agent at CID %d: %w", guestCID, err)}-return &AgentClient{conn: conn,client: pb.NewSandboxAgentClient(conn),+ dialer: dialer,}, nil}@@ -479,37 +494,89 @@ func (c *AgentClient) ConnectPTYData(guestCID uint32, dataPort uint32) (net.Conn// NewAgentClientSocket connects to the agent via a Unix socket (virtio-serial chardev).// Used by QEMU backend — virtio-serial survives QEMU live migration.func NewAgentClientSocket(socketPath string) (*AgentClient, error) {- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()-- conn, err := grpc.DialContext(ctx,- "unix://"+socketPath,- grpc.WithTransportCredentials(insecure.NewCredentials()),- grpc.WithBlock(),- grpc.WithConnectParams(grpc.ConnectParams{- Backoff: backoff.Config{- BaseDelay: 10 * time.Millisecond,- Multiplier: 1.6,- Jitter: 0.2,- 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),- ),- )+ dialer := func() (*grpc.ClientConn, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ return grpc.DialContext(ctx,+ "unix://"+socketPath,+ grpc.WithTransportCredentials(insecure.NewCredentials()),+ grpc.WithBlock(),+ grpc.WithConnectParams(grpc.ConnectParams{+ Backoff: backoff.Config{+ BaseDelay: 10 * time.Millisecond,+ Multiplier: 1.6,+ Jitter: 0.2,+ 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),+ ),+ )+ }+ conn, err := dialer()if err != nil {return nil, fmt.Errorf("connect to agent at %s: %w", socketPath, err)}-return &AgentClient{conn: conn,client: pb.NewSandboxAgentClient(conn),+ dialer: dialer,}, nil}++// Redial closes the current gRPC conn and dials a new one using the dialer+// captured at construction. Safe under concurrent callers — only one+// redial happens at a time, others wait and reuse the result.+//+// Use this when an RPC fails with a transport error (Unavailable, EOF,+// closed network connection). After Redial, retry the RPC on the fresh+// conn. If the agent inside the VM is fundamentally wedged this won't+// help — but for the common "stale conn after savevm/loadvm" or+// "control channel dropped at idle" case it recovers transparently.+func (c *AgentClient) Redial() error {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.dialer == nil {+ return fmt.Errorf("AgentClient has no dialer (already closed?)")+ }+ if c.conn != nil {+ _ = c.conn.Close()+ }+ conn, err := c.dialer()+ if err != nil {+ return fmt.Errorf("redial agent: %w", err)+ }+ c.conn = conn+ c.client = pb.NewSandboxAgentClient(conn)+ log.Printf("agent-client: redial succeeded")+ return nil+}++// IsTransportError returns true if err looks like a gRPC transport-level+// failure that a Redial+retry would plausibly fix. Distinguished from+// application errors (NotFound, InvalidArgument, etc.) which are caller+// problems and shouldn't trigger reconnect storms.+func IsTransportError(err error) bool {+ if err == nil {+ return false+ }+ if st, ok := status.FromError(err); ok {+ switch st.Code() {+ case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled:+ return true+ }+ }+ msg := err.Error()+ return strings.Contains(msg, "use of closed network connection") ||+ strings.Contains(msg, "EOF") ||+ strings.Contains(msg, "broken pipe") ||+ strings.Contains(msg, "connection reset") ||+ strings.Contains(msg, "transport is closing")+}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 7b331248..b1adc596 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -58,6 +58,26 @@ func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) {time.Sleep(1 * time.Second)}+// quiesceAndCloseAgent prepares the agent for hibernate, closes the host-side+// gRPC client connection, and waits 200ms for the guest's gRPC server to+// process the EOF and re-enter its Accept poll loop. After this returns it is+// safe for the caller to call savevm — the captured snapshot will not have a+// stale virtioSerialConn whose buffered HTTP/2 framer state could corrupt the+// next host's gRPC handshake on fork/restore.+//+// The 200ms is empirically sufficient for the guest virtio-serial driver to+// surface EOF on /dev/virtio-ports/agent → for the gRPC server's Read goroutine+// to drop its conn → for onClose to run (active=false). Without this wait the+// snapshot can land mid-tear-down and the bug returns.+func quiesceAndCloseAgent(ctx context.Context, agent *AgentClient) {+ if agent == nil {+ return+ }+ prepareAgentForHibernate(ctx, agent)+ _ = agent.Close()+ time.Sleep(200 * time.Millisecond)+}+// Compile-time check that Manager implements sandbox.Manager.var _ sandbox.Manager = (*Manager)(nil)@@ -975,11 +995,18 @@ func patchGuestNetwork(ctx context.Context, agent *AgentClient, netCfg *NetworkC// `ip route replace` is idempotent — works whether the route exists or not.// `ip addr add` may say "File exists" if the address is already there, which// is a no-op for our purposes; suppress and verify at the end.+ //+ // `ip neigh flush all` is critical on cross-worker fork: the captured ARP+ // cache has the SOURCE worker's gateway MAC, but the destination worker's+ // TAP has a different MAC. Without flushing, the kernel keeps the stale+ // REACHABLE entry for ~30s (base_reachable_time) and every outbound packet+ // silently drops. Flush forces a fresh ARP resolve on the next packet.script := fmt.Sprintf(`set +eip addr flush dev eth0ip addr add %s/%d dev eth0 2>/dev/nullip link set eth0 upip route replace default via %s+ip neigh flush all# DNS — always write, independent of network opsecho 'nameserver 8.8.8.8' > /etc/resolv.conf@@ -997,15 +1024,30 @@ exit 0netCfg.GuestIP, netCfg.HostIP,)- execCtx, cancel := context.WithTimeout(ctx, 5*time.Second)- defer cancel()-- resp, err := agent.Exec(execCtx, &pb.ExecRequest{+ // 30s deadline (bumped from 5s) — under host load `ip link` and arping+ // can take several seconds, and the prior 5s budget left no room for the+ // agent's Exec round-trip on top of that. The 5s timeout produced the+ // `network patch failed: rpc error: code = DeadlineExceeded` cluster in+ // load tests. One Redial-on-transport-error retry handles the post-loadvm+ // stale-conn case where the first call hits a wedged virtio-serial channel.+ req := &pb.ExecRequest{Command: "/bin/sh",Args: []string{"-c", script},- TimeoutSeconds: 5,+ TimeoutSeconds: 25,RunAsRoot: true,- })+ }+ rpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ resp, err := agent.Exec(rpcCtx, req)+ if err != nil && IsTransportError(err) {+ log.Printf("qemu: patchGuestNetwork: transport error %v, redialing and retrying once", err)+ if rdErr := agent.Redial(); rdErr != nil {+ return fmt.Errorf("network patch redial: %w (orig: %v)", rdErr, err)+ }+ rpcCtx2, cancel2 := context.WithTimeout(ctx, 30*time.Second)+ defer cancel2()+ resp, err = agent.Exec(rpcCtx2, req)+ }if err != nil {return fmt.Errorf("exec network patch: %w", err)}@@ -1701,13 +1743,24 @@ func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessCcommand = "/bin/sh"}- resp, err := vm.agent.Exec(ctx, &pb.ExecRequest{+ req := &pb.ExecRequest{Command: command,Args: args,Envs: cfg.Env,Cwd: cfg.Cwd,TimeoutSeconds: timeout,- })+ }+ resp, err := vm.agent.Exec(ctx, req)+ if err != nil && IsTransportError(err) {+ // Same recovery path as SyncFS: the gRPC client conn can be in a+ // transient-failure state immediately after fork (waitForAgentSocket+ // passes with one ping, but the next RPC races with conn state).+ // Redial and retry once.+ log.Printf("qemu: Exec %s: transport error (%v), redialing agent", sandboxID, err)+ if rdErr := vm.agent.Redial(); rdErr == nil {+ resp, err = vm.agent.Exec(ctx, req)+ }+ }if err != nil {return nil, fmt.Errorf("exec in %s: %w", sandboxID, err)}@@ -2147,11 +2200,11 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDreturn "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)}- // Sync filesystem and quiesce virtio-serial before snapshot. The PrepareHibernate- // RPC returns only after the guest is fully prepared, so no sleep is needed.+ // Sync filesystem, quiesce virtio-serial, close host conn, and WAIT for+ // the guest to process EOF before savevm. Critical for clean snapshot+ // state — see quiesceAndCloseAgent for the protocol details.if vm.agent != nil {- prepareAgentForHibernate(ctx, vm.agent)- vm.agent.Close()+ quiesceAndCloseAgent(ctx, vm.agent)vm.agent = nil}@@ -2220,15 +2273,19 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDif reconnErr == nil {vm.agent = agentClient} else {- 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- }+ // Agent didn't come back after savevm — the VM is unmanageable. Full+ // teardown via destroyVM, not the partial QMP-quit-only cleanup that+ // used to live here. The old path left the qemu process and TAP/dir+ // behind any time qmp.Quit didn't reach the process, producing the+ // orphan qemu we observed under load (m.vms removed but qemu alive,+ // invisible to the rest of the worker until the orphan reaper runs).+ log.Printf("qemu: CreateCheckpoint %s/%s: CRITICAL: agent reconnect failed, destroying VM cleanly", sandboxID, checkpointID)m.mu.Lock()delete(m.vms, sandboxID)m.mu.Unlock()+ if err := m.destroyVM(vm); err != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: destroyVM also failed: %v (orphan reaper will catch)", sandboxID, checkpointID, err)+ }}// Write metadata and finalize cache.@@ -2851,13 +2908,36 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, clog.Printf("qemu: ForkFromCheckpoint %s → %s: agent connected, patching network...", checkpointID, id)- // Patch network (fork gets new IPs) + sync clock+ // Patch network (fork gets new IPs) + sync clock — both LOAD-BEARING.+ // Earlier this code only logged failures; the fork would "complete" with+ // the wrong IP/route/DNS and an unresponsive agent gRPC channel, leaking+ // a half-broken VM. Now: propagate errors, destroy the half-built fork,+ // and return — caller retries against a clean slate.+ patchT0 := time.Now()if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {- log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)+ log.Printf("qemu: ForkFromCheckpoint %s: ABORT network patch failed (%dms): %v",+ id, time.Since(patchT0).Milliseconds(), err)+ _ = agent.Close()+ _ = qmpClient.Close()+ _ = cmd.Process.Kill()+ _ = cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("fork %s: network patch failed: %w", id, err)}+ log.Printf("qemu: ForkFromCheckpoint %s: network patched (%dms)", id, time.Since(patchT0).Milliseconds())++ clockT0 := time.Now()if err := syncGuestClock(context.Background(), agent); err != nil {- log.Printf("qemu: ForkFromCheckpoint %s: clock sync failed: %v", id, err)+ log.Printf("qemu: ForkFromCheckpoint %s: ABORT clock sync failed (%dms): %v",+ id, time.Since(clockT0).Milliseconds(), err)+ _ = agent.Close()+ _ = qmpClient.Close()+ _ = cmd.Process.Kill()+ _ = cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("fork %s: clock sync failed: %w", id, err)}+ log.Printf("qemu: ForkFromCheckpoint %s: clock synced (%dms)", id, time.Since(clockT0).Milliseconds())// Set env vars (sealed via secrets proxy if configured)envsToInject := m.sealSandboxEnvs(context.Background(), id, netCfg, agent, cfg)@@ -3016,6 +3096,13 @@ func (m *Manager) GetWorkspacePath(sandboxID string) (string, error) {}// SyncFS flushes filesystem buffers inside the VM.+//+// On transport errors (Unavailable, EOF, "closed network connection"), the+// agent client redials and retries once. This is the recovery path for the+// prod scenario where an agent connection silently dropped ~10 min after+// migration restore and stayed dropped: every autosave-driven SyncFS would+// hit a closed conn and log a failure forever, with no reconnect attempt.+// Now we redial on demand and the next autosave succeeds.func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {vm, err := m.getVM(sandboxID)if err != nil {@@ -3024,7 +3111,17 @@ func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {if vm.agent == nil {return fmt.Errorf("no agent connection for %s", sandboxID)}- return vm.agent.SyncFS(ctx)+ if err := vm.agent.SyncFS(ctx); err != nil {+ if !IsTransportError(err) {+ return err+ }+ log.Printf("qemu: SyncFS %s: transport error (%v), redialing agent", sandboxID, err)+ if rdErr := vm.agent.Redial(); rdErr != nil {+ return fmt.Errorf("syncfs failed and redial failed: orig=%v redial=%w", err, rdErr)+ }+ return vm.agent.SyncFS(ctx)+ }+ return nil}// CleanupOrphanedProcesses kills any QEMU processes and TAP devicesdiff --git a/internal/qemu/orphan_reaper.go b/internal/qemu/orphan_reaper.gonew file mode 100644index 00000000..aa7bbf94--- /dev/null+++ b/internal/qemu/orphan_reaper.go@@ -0,0 +1,187 @@+package qemu++import (+ "context"+ "log"+ "os"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"+ "syscall"+ "time"+)++// orphanReapInterval is how often we scan /proc for leaked qemu processes.+// 60s is short enough that a leak doesn't accumulate for hours, long enough+// that the scan cost is negligible (one sweep of /proc per minute).+const orphanReapInterval = 60 * time.Second++// orphanGraceTermDelay is how long we wait between SIGTERM and SIGKILL when+// reaping an orphan. QEMU usually exits cleanly on SIGTERM within ~1s; 5s is+// generous and bounds the reap pass at ~5s per orphan in the worst case.+const orphanGraceTermDelay = 5 * time.Second++// sandboxIDRe extracts an sb-xxxxxxxx sandbox ID from a qemu command line.+// QEMU's cmdline embeds the sandboxDir as a -drive file=… and -chardev path=…+// argument, so the ID always appears in the form /data/sandboxes/sandboxes/sb-XXX/.+var sandboxIDRe = regexp.MustCompile(`/sandboxes/(sb-[a-z0-9]+)/`)++// StartOrphanReaper launches a background goroutine that periodically scans+// /proc for qemu-system processes whose sandbox ID is not in the worker's VM+// registry, and kills them.+//+// Why this is needed: when destroyVM races with a state inconsistency (e.g.,+// a hibernate-on-timeout that ran without the VM being in m.vms, a panic in+// a sandbox goroutine that exits before cleanup, or a worker crash that left+// children behind), a qemu-system-x86_64 process can survive past the worker's+// knowledge of it. Those orphans hold a TAP, an agent.sock, and a vCPU — they+// silently shrink real worker capacity until the worker is restarted. We saw+// this in the field: after a load test, Worker A had 2 zombie + 1 live qemu+// from a session that ended 30 minutes earlier, which then made every new+// fork on that worker fail.+func (m *Manager) StartOrphanReaper(ctx context.Context) {+ go m.orphanReaperLoop(ctx)+}++func (m *Manager) orphanReaperLoop(ctx context.Context) {+ ticker := time.NewTicker(orphanReapInterval)+ defer ticker.Stop()+ // First scan happens after one interval — gives the worker time to+ // register VMs at startup before we start judging them as orphans.+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ m.reapOrphans()+ }+ }+}++// reapOrphans scans /proc for qemu-system processes belonging to sandboxes+// that are no longer in m.vms, and kills them.+func (m *Manager) reapOrphans() {+ pidByID, err := scanQEMUProcesses()+ if err != nil {+ log.Printf("qemu: orphan-reaper: scan failed: %v", err)+ return+ }+ if len(pidByID) == 0 {+ return+ }++ m.mu.RLock()+ known := make(map[string]bool, len(m.vms))+ for id := range m.vms {+ known[id] = true+ }+ m.mu.RUnlock()++ for sandboxID, pid := range pidByID {+ if known[sandboxID] {+ continue+ }+ log.Printf("qemu: orphan-reaper: found leaked qemu pid=%d sandbox=%s (not in vm registry), terminating",+ pid, sandboxID)+ if err := terminateAndWait(pid); err != nil {+ log.Printf("qemu: orphan-reaper: failed to terminate pid=%d: %v", pid, err)+ continue+ }+ // Best-effort sandbox dir cleanup. If destroyVM was supposed to remove+ // it but never did, do it now.+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", "sandboxes", sandboxID)+ if _, err := os.Stat(sandboxDir); err == nil {+ if err := os.RemoveAll(sandboxDir); err != nil {+ log.Printf("qemu: orphan-reaper: removed pid=%d but failed to clean %s: %v",+ pid, sandboxDir, err)+ } else {+ log.Printf("qemu: orphan-reaper: cleaned up sandbox dir %s", sandboxDir)+ }+ }+ }+}++// scanQEMUProcesses walks /proc and returns a map of sandboxID -> pid for+// every qemu-system-x86_64 process whose cmdline references a sandbox dir.+func scanQEMUProcesses() (map[string]int, error) {+ procEntries, err := os.ReadDir("/proc")+ if err != nil {+ return nil, err+ }+ out := make(map[string]int)+ for _, entry := range procEntries {+ if !entry.IsDir() {+ continue+ }+ pid, err := strconv.Atoi(entry.Name())+ if err != nil {+ continue+ }+ // Read /proc/PID/comm — cheap, only ~16 bytes; skip non-qemu fast.+ commBytes, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "comm"))+ if err != nil {+ continue+ }+ comm := strings.TrimSpace(string(commBytes))+ if !strings.HasPrefix(comm, "qemu-system") {+ continue+ }+ // /proc/PID/cmdline is NUL-separated; we scan it as a single blob.+ cmdlineBytes, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "cmdline"))+ if err != nil {+ continue+ }+ cmdline := string(cmdlineBytes)+ match := sandboxIDRe.FindStringSubmatch(cmdline)+ if len(match) < 2 {+ continue+ }+ sandboxID := match[1]+ // Multiple qemu processes for the same sandbox shouldn't exist —+ // if they do, the first one wins; the duplicate will be reaped on+ // the next pass after the registered one is removed.+ if _, dup := out[sandboxID]; !dup {+ out[sandboxID] = pid+ }+ }+ return out, nil+}++// terminateAndWait sends SIGTERM, waits up to orphanGraceTermDelay, then+// SIGKILLs if the process is still alive. Returns nil if the process is+// gone (whatever the path).+func terminateAndWait(pid int) error {+ proc, err := os.FindProcess(pid)+ if err != nil {+ return err+ }+ // SIGTERM lets QEMU shut down its devices cleanly, which avoids leaving+ // stale qcow2 locks. If it's already wedged it won't help; we'll SIGKILL+ // after the grace window.+ _ = proc.Signal(syscall.SIGTERM)++ deadline := time.Now().Add(orphanGraceTermDelay)+ for time.Now().Before(deadline) {+ if !pidAlive(pid) {+ return nil+ }+ time.Sleep(200 * time.Millisecond)+ }+ if pidAlive(pid) {+ _ = proc.Kill()+ // Brief wait for kernel to flush the kill.+ for i := 0; i < 25 && pidAlive(pid); i++ {+ time.Sleep(40 * time.Millisecond)+ }+ }+ return nil+}++// pidAlive returns true if /proc/PID still exists. We don't use kill(0)+// because that fails with EPERM if the worker isn't root for some reason —+// /proc is more permissive.+func pidAlive(pid int) bool {+ _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid)))+ return err == nil+}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 131d27e5..803b232e 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -62,13 +62,11 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoreturn nil, fmt.Errorf("mkdir snapshot dir: %w", err)}- // Step 1: Sync filesystems and quiesce agent.+ // Step 1: Sync filesystems, quiesce agent, close host conn, and WAIT for+ // the guest to process EOF before savevm. See quiesceAndCloseAgent.// Don't unmount /workspace — open FDs prevent clean unmount and cause ext4 corruption.- // PrepareHibernate syncs dirty pages and resets the virtio-serial listener- // synchronously, so no post-close sleep is needed.if vm.agent != nil {- prepareAgentForHibernate(ctx, vm.agent)- vm.agent.Close()+ quiesceAndCloseAgent(ctx, vm.agent)vm.agent = nil}log.Printf("qemu: hibernate %s: guest sync + unmount done (%dms)", vm.ID, time.Since(t0).Milliseconds())@@ -796,15 +794,33 @@ func copyFileReflink(src, dst string) error {}// syncGuestClock sets the guest clock to the current host time via agent exec.+//+// Wraps the underlying RPC with a 10s deadline (caller-side timeout, NOT just+// the agent-side TimeoutSeconds) and one Redial-on-transport-error retry. Prior+// version used the caller's context.Background() which had no deadline at all,+// so a wedged virtio-serial channel would block until gRPC keepalive (~7 min)+// gave up. That stall is what produced the multi-minute "from-checkpoint"+// requests in load tests.func syncGuestClock(ctx context.Context, agent *AgentClient) error {now := time.Now().Unix()- cmd := fmt.Sprintf("date -s @%d > /dev/null 2>&1", now)- resp, err := agent.Exec(ctx, &pb.ExecRequest{+ req := &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", cmd},+ Args: []string{"-c", fmt.Sprintf("date -s @%d > /dev/null 2>&1", now)},TimeoutSeconds: 5,RunAsRoot: true,- })+ }+ rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ resp, err := agent.Exec(rpcCtx, req)+ if err != nil && IsTransportError(err) {+ log.Printf("qemu: syncGuestClock: transport error %v, redialing and retrying once", err)+ if rdErr := agent.Redial(); rdErr != nil {+ return fmt.Errorf("clock sync redial: %w (orig: %v)", rdErr, err)+ }+ rpcCtx2, cancel2 := context.WithTimeout(ctx, 10*time.Second)+ defer cancel2()+ resp, err = agent.Exec(rpcCtx2, req)+ }if err != nil {return fmt.Errorf("exec clock sync: %w", err)}