An open-source, faster Devin alternative
TypeScript
Fix fork corruption + hibernate/wake race conditions (#128)
Brian Reardonf21a4d2f9a63
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 4f588b65..85690e64 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1093,6 +1093,13 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) errorsession.Region, session.Template, session.Config)_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)+ // Invalidate the proxy route cache: wake may land the sandbox on a+ // different worker, so subsequent data-plane requests must re-resolve+ // the routing from the DB instead of hitting the old worker.+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }+resp := map[string]interface{}{"sandboxID": sandboxID,"status": "hibernated",@@ -1217,6 +1224,13 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W_ = s.store.MarkHibernationRestored(c.Request().Context(), sandboxID)_ = s.store.UpdateSandboxSessionForWake(c.Request().Context(), sandboxID, worker.ID)+ // Refresh the proxy route cache with the new worker — wake may have moved+ // the sandbox to a different worker than where it was hibernated, and any+ // stale cache entry would route data-plane requests to the wrong worker.+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }+// Apply pending checkpoint patches in backgroundgo s.applyPendingPatches(sandboxID, worker.ID)@@ -1727,7 +1741,67 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st}}- // Record session immediately+ // Boot VM synchronously so the worker's in-memory sandbox map is populated+ // before we respond or record the session. Previously this ran in a goroutine+ // with the session row written first as status=running, which allowed+ // immediate hibernate/restore/etc. to route to a worker whose m.vms[id] was+ // not yet populated and 500 with "sandbox not found".+ var createErr error+ if grpcClient != nil {+ // 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,+ MemoryMb: int32(originalCfg.MemoryMB),+ CpuCount: int32(originalCfg.CpuCount),+ NetworkEnabled: originalCfg.NetworkEnabled,+ Port: int32(originalCfg.Port),+ TemplateRootfsKey: *cp.RootfsS3Key,+ TemplateWorkspaceKey: *cp.WorkspaceS3Key,+ CheckpointId: checkpointID.String(),+ SandboxId: sandboxID,+ EgressAllowlist: originalCfg.EgressAllowlist,+ SecretAllowedHosts: flattenSecretAllowedHosts(originalCfg.SecretAllowedHosts),+ SecretEnvs: originalCfg.SecretEnvs,+ })+ } else {+ // Combined mode: create locally — no external timeout, same reasoning as above+ cfg := originalCfg+ cfg.Timeout = timeout+ cfg.TemplateRootfsKey = *cp.RootfsS3Key+ cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key+ cfg.SandboxID = sandboxID+ cfg.CheckpointID = checkpointID.String()++ forkMgr, hasFork := s.manager.(interface {+ ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)+ })+ if hasFork {+ _, createErr = forkMgr.ForkFromCheckpoint(context.Background(), checkpointID.String(), cfg)+ } else {+ _, createErr = s.manager.Create(context.Background(), cfg)+ }+ }++ // Unblock any callers waiting on this pendingCreate entry with the outcome.+ pending.err = createErr+ close(pending.ready)+ if s.router != nil {+ s.router.MarkCreated(sandboxID, createErr)+ }++ if createErr != nil {+ s.pendingCreates.Delete(sandboxID)+ log.Printf("api: fork %s failed: %v", sandboxID, createErr)+ return nil, http.StatusInternalServerError, fmt.Errorf("fork from checkpoint: %w", createErr)+ }++ // Record session only after the worker has the VM registered so the session+ // row never points at a worker that does not yet own the VM.if s.store != nil {template := originalCfg.Templateif template == "" {@@ -1740,72 +1814,11 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st_ = s.store.SetSandboxCheckpointID(ctx, sandboxID, checkpointID)}- // Boot VM in background- go func() {- var createErr error-- if grpcClient != nil {- // 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,- MemoryMb: int32(originalCfg.MemoryMB),- CpuCount: int32(originalCfg.CpuCount),- NetworkEnabled: originalCfg.NetworkEnabled,- Port: int32(originalCfg.Port),- TemplateRootfsKey: *cp.RootfsS3Key,- TemplateWorkspaceKey: *cp.WorkspaceS3Key,- CheckpointId: checkpointID.String(),- SandboxId: sandboxID,- EgressAllowlist: originalCfg.EgressAllowlist,- SecretAllowedHosts: flattenSecretAllowedHosts(originalCfg.SecretAllowedHosts),- SecretEnvs: originalCfg.SecretEnvs,- })- } else {- // Combined mode: create locally — no external timeout, same reasoning as above- cfg := originalCfg- cfg.Timeout = timeout- cfg.TemplateRootfsKey = *cp.RootfsS3Key- cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key- cfg.SandboxID = sandboxID- cfg.CheckpointID = checkpointID.String()-- forkMgr, hasFork := s.manager.(interface {- ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)- })- if hasFork {- _, createErr = forkMgr.ForkFromCheckpoint(context.Background(), checkpointID.String(), cfg)- } else {- _, createErr = s.manager.Create(context.Background(), cfg)- }- }-- if createErr != nil {- log.Printf("api: async fork %s failed: %v", sandboxID, createErr)- }-- // Signal completion- pending.err = createErr- close(pending.ready)-- // Also signal router if available (combined mode)- if s.router != nil {- s.router.MarkCreated(sandboxID, createErr)- }-- // Apply any existing patches for this checkpoint after boot- if createErr == nil {- s.applyPendingPatches(sandboxID, workerID)- }- }()+ s.applyPendingPatches(sandboxID, workerID)result := map[string]interface{}{"sandboxID": sandboxID,- "status": "creating",+ "status": "running","token": token,"region": region,"workerID": workerID,diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex a415fff5..5a96673b 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -1839,69 +1839,71 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// resets the virtio-serial listener so forks start with a clean Accept state.vm.agent.Close()vm.agent = nil- time.Sleep(500 * time.Millisecond) // let guest process SIGUSR1- }-- // 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.+ // Give the guest time to fully quiesce virtio-serial state. 500ms was+ // observed to leave a small residual rate of "agent not ready" failures+ // on fork after loadvm (post-loadvm virtio-serial comes up but Accept+ // doesn't land cleanly). 1s should give the guest enough time without+ // noticeably adding to checkpoint latency.+ time.Sleep(1 * time.Second)+ }++ // Savevm-based checkpoint: pack memory + device state + disk deltas into+ // the qcow2 drive files as an internal snapshot, atomically. This matches+ // doHibernate's proven approach and avoids the migrate-based checkpoint's+ // consistency hazards (migrate marks source drives read-only after+ // "completed", so we can't use QMP drive-backup post-migrate; and the+ // previous external cp --reflink of drives post-migrate produced ~30%+ // fork corruption because QEMU may still have virtio-blk writes pending+ // when the reflink copy is taken).+ //+ // Prior concern: a comment claimed savevm/loadvm had a ~0.5% virtio-serial+ // corruption rate. That is not re-observed today — doHibernate uses the+ // same savevm/loadvm path and is reliable. The existing mitigation+ // (close agent + let SIGUSR1 reset the virtio-serial listener before+ // savevm) is preserved above.if vm.qmp == nil {return "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)}- // 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 failurereturn "", "", 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()+ // savevm pauses the VM, writes memory+device+disk-delta into every qcow2+ // drive as an internal snapshot, then resumes. The qcow2 files now carry+ // the full VM state; no external memory file is needed.+ snapshotName := "cp-" + checkpointID+ if err := vm.qmp.SaveVM(snapshotName); err != nil {os.RemoveAll(stagingDir)- return "", "", fmt.Errorf("wait migration: %w", err)+ return "", "", fmt.Errorf("savevm: %w", err)}+ log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())- // Copy drives while VM is still paused — guaranteed consistent.+ // Copy the qcow2 files (now containing the internal snapshot) into the+ // checkpoint cache staging dir. The VM has already been resumed by savevm,+ // but qcow2 internal snapshots are immutable once written, so the reflink+ // copy captures exactly the snapshot bytes regardless of any new writes.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+ if err := copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2")); err != nil {+ os.RemoveAll(stagingDir)+ return "", "", fmt.Errorf("copy rootfs: %w", err)}-- 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)+ if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {+ os.RemoveAll(stagingDir)+ return "", "", fmt.Errorf("copy workspace: %w", err)}+ // Record the savevm snapshot name so ForkFromCheckpoint / RestoreFromCheckpoint+ // know which internal snapshot to loadvm.+ _ = os.WriteFile(filepath.Join(stagingDir, "snapshot-name"), []byte(snapshotName), 0644)++ log.Printf("qemu: CreateCheckpoint %s/%s: qcow2 copied (%dms total)", sandboxID, checkpointID, time.Since(t0).Milliseconds())- // Reconnect agent (connection was closed before migration).+ // Reconnect agent — savevm auto-resumed the VM, but the agent connection+ // was closed above and the guest's SIGUSR1 handler reset the virtio-serial+ // listener, so we need a fresh Accept.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", sandboxID, checkpointID, reconnErr)@@ -1961,9 +1963,14 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// The archive includes drives + memory dump + metadata — everything ForkFromCheckpoint needs.// Image builder waits for upload to finish (via WaitUploads) before forking.if checkpointStore != nil {- // Build list of files to archive+ // Build list of files to archive. Savevm-based checkpoints store the VM+ // state inside the qcow2 drives and record the snapshot name; migrate-+ // based legacy checkpoints (from older builds) also include a mem file.var archiveFiles []stringarchiveFiles = append(archiveFiles, "rootfs.qcow2", "workspace.qcow2")+ if fileExists(filepath.Join(cacheDir, "snapshot-name")) {+ archiveFiles = append(archiveFiles, "snapshot-name")+ }if fileExists(filepath.Join(cacheDir, "mem.zst")) {archiveFiles = append(archiveFiles, "mem.zst")} else if fileExists(filepath.Join(cacheDir, "mem")) {@@ -2402,96 +2409,108 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cincomingURI = ""}- os.Remove(qmpSockPath)- os.Remove(agentSockPath)-- logPath := filepath.Join(sandboxDir, "qemu.log")- logFile, err := os.Create(logPath)- if err != nil {- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("create log file: %w", err)- }+ // Boot QEMU, load the checkpoint (migration or loadvm), and connect the+ // agent inside. Post-loadvm virtio-serial occasionally comes up with the+ // Accept side not ready (the guest resumes, the kernel brings up the+ // virtio-serial port, but the agent's accept() doesn't land in time).+ // That's a transient flake — retrying a fresh boot from the same checkpoint+ // usually recovers. Wrap boot-to-agent-connect in one retry.+ bootAndRestore := func() (*exec.Cmd, *QMPClient, *AgentClient, error) {+ os.Remove(qmpSockPath)+ os.Remove(agentSockPath)- args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,- netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)+ logPath := filepath.Join(sandboxDir, "qemu.log")+ logFile, err := os.Create(logPath)+ if err != nil {+ return nil, nil, nil, fmt.Errorf("create log file: %w", err)+ }- 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")- }+ args := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,+ netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)+ if incomingURI != "" {+ args = append(args, "-incoming", incomingURI)+ } else {+ args = append(args, "-S")+ }- cmd := exec.Command(m.cfg.QEMUBin, args...)- cmd.Stdout = logFile- cmd.Stderr = logFile- if err := cmd.Start(); err != nil {+ cmd := exec.Command(m.cfg.QEMUBin, args...)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ if err := cmd.Start(); err != nil {+ logFile.Close()+ return nil, nil, nil, fmt.Errorf("start qemu for fork: %w", err)+ }logFile.Close()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("start qemu for fork: %w", err)- }- logFile.Close()- log.Printf("qemu: ForkFromCheckpoint %s → %s: QEMU started (pid=%d, migration=%v)",- checkpointID, id, cmd.Process.Pid, incomingURI != "")+ 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 {- cmd.Process.Kill()- cmd.Wait()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("QMP connect: %w", err)- }+ qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ return nil, nil, nil, fmt.Errorf("QMP connect: %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 {+ if incomingURI != "" {+ if err := m.waitForMigrationReady(qmpClient, 30*time.Second); err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ return nil, nil, nil, fmt.Errorf("migration load: %w", err)+ }+ } else {+ 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()+ return nil, nil, nil, fmt.Errorf("loadvm: %w", err)+ }+ }++ if err := qmpClient.Cont(); err != nil {qmpClient.Close()cmd.Process.Kill()cmd.Wait()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("migration load: %w", err)+ return nil, nil, nil, fmt.Errorf("QMP cont: %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))+ log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms), connecting agent...",+ checkpointID, id, time.Since(t0).Milliseconds())++ agentTimeout := 30 * time.Second+ if incomingURI != "" {+ agentTimeout = 10 * time.Second}- if err := qmpClient.LoadVM(snapshotName); err != nil {+ agent, err := m.waitForAgentSocket(context.Background(), agentSockPath, agentTimeout)+ if err != nil {qmpClient.Close()cmd.Process.Kill()cmd.Wait()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("loadvm: %w", err)+ return nil, nil, nil, fmt.Errorf("agent connect: %w", err)}+ return cmd, qmpClient, agent, nil}- if err := qmpClient.Cont(); err != nil {- qmpClient.Close()- cmd.Process.Kill()- cmd.Wait()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("QMP cont: %w", err)- }- log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms), connecting agent...",- checkpointID, id, time.Since(t0).Milliseconds())-- // 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- }+ var cmd *exec.Cmd+ var qmpClient *QMPClientvar agent *AgentClient- agent, err = m.waitForAgentSocket(context.Background(), agentSockPath, agentTimeout)- if err != nil {- qmpClient.Close()- cmd.Process.Kill()- cmd.Wait()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("agent connect: %w", err)+ for attempt := 1; attempt <= 2; attempt++ {+ c, q, a, bErr := bootAndRestore()+ if bErr == nil {+ cmd, qmpClient, agent = c, q, a+ break+ }+ retriable := attempt == 1 && strings.Contains(bErr.Error(), "agent connect")+ if !retriable {+ m.cleanupVM(netCfg, sandboxDir)+ return nil, bErr+ }+ log.Printf("qemu: ForkFromCheckpoint %s → %s: transient virtio-serial flake on attempt %d, retrying: %v",+ checkpointID, id, attempt, bErr)}log.Printf("qemu: ForkFromCheckpoint %s → %s: agent connected, patching network...", checkpointID, id)diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 99b42b05..c042662c 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -465,17 +465,15 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("agent not ready: %w", err)}- // Mount /home/sandbox (data disk, was unmounted before savevm)- postCtx, postCancel := context.WithTimeout(context.Background(), 10*time.Second)- _, _ = agentClient.Exec(postCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", strings.Join([]string{- "mount /dev/vdb /home/sandbox 2>/dev/null || true",- "chown 1000:1000 /home/sandbox",- }, " && ")},- RunAsRoot: true,- })- postCancel()+ // Hibernate captured the guest with its mount state intact (we never+ // unmount before savevm), so loadvm restores the correct mount layout+ // automatically. Do NOT blindly mount /dev/vdb on /home/sandbox here:+ // cold-booted VMs have their workspace disk mounted at /workspace per the+ // guest's fstab, with /home/sandbox being a regular directory on the+ // rootfs. If we force-mount /dev/vdb over /home/sandbox post-wake, we+ // shadow any files the user wrote to /home/sandbox (which live on the+ // rootfs qcow2) with the empty workspace qcow2 view, silently losing+ // their data.if err := patchGuestNetwork(context.Background(), agentClient, netCfg); err != nil {log.Printf("qemu: wake %s: network patch failed: %v", sandboxID, err)diff --git a/scripts/integration-tests/01-fork-sync-hibernate.ts b/scripts/integration-tests/01-fork-sync-hibernate.tsnew file mode 100644index 00000000..12709e2b--- /dev/null+++ b/scripts/integration-tests/01-fork-sync-hibernate.ts@@ -0,0 +1,72 @@+/**+ * Regression test for: fix(api): make createFromCheckpoint synchronous (08d5320)+ *+ * Before the fix, createFromCheckpoint wrote the sandbox_sessions row with+ * status=running upfront, then kicked the actual fork into a background+ * goroutine. For 2-5s the worker's m.vms[id] wasn't populated yet, so any+ * control-plane RPC routed to the worker returned+ * 500 "sandbox not found"+ *+ * This test forks from a checkpoint and IMMEDIATELY calls hibernate. If the+ * fix is in place, hibernate works; otherwise we see "sandbox not found".+ *+ * Usage:+ * OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... npx tsx 01-fork-sync-hibernate.ts+ */++import { Sandbox } from "../../sdks/typescript/src";++const ITERATIONS = 3;++async function main() {+ const source = await Sandbox.create({ template: "base", timeout: 600 });+ const toKill: string[] = [source.sandboxId];+ let passed = 0, failed = 0;++ try {+ // Seed minimal state and create a checkpoint on the source+ await source.exec.run("echo seed > /home/sandbox/seed.txt && sync", { timeout: 30 });+ const cp = await source.createCheckpoint("sync-fork-test");+ for (let i = 0; i < 60; i++) {+ const cps = await source.listCheckpoints();+ const found = cps.find((c: any) => c.id === cp.id);+ if (found && (found as any).status === "ready") break;+ await new Promise(r => setTimeout(r, 1000));+ }+ console.log(`checkpoint ${cp.id} ready`);++ // Run ITERATIONS of: fork -> immediate hibernate+ for (let i = 0; i < ITERATIONS; i++) {+ let fork: Sandbox | null = null;+ try {+ fork = await Sandbox.createFromCheckpoint(cp.id, { timeout: 300 });+ toKill.push(fork.sandboxId);+ // Immediate hibernate — previously this would race with the worker's+ // m.vms[id] registration and 500.+ await fork.hibernate();+ console.log(`[${i + 1}/${ITERATIONS}] ✓ fork ${fork.sandboxId} -> hibernate OK`);+ passed++;+ } catch (e: any) {+ const msg = e?.message ?? String(e);+ if (msg.includes("sandbox") && msg.includes("not found")) {+ console.log(`[${i + 1}/${ITERATIONS}] ✗ REGRESSION: sync-fork race returned: ${msg}`);+ } else {+ console.log(`[${i + 1}/${ITERATIONS}] ✗ unexpected failure: ${msg}`);+ }+ failed++;+ }+ }++ // Clean up checkpoint+ try { await source.deleteCheckpoint(cp.id); } catch {}+ } finally {+ for (const id of toKill) {+ try { const s = await Sandbox.connect(id); await s.kill(); } catch {}+ }+ }++ console.log(`\n=== ${passed} passed, ${failed} failed ===`);+ process.exit(failed === 0 ? 0 : 1);+}++main().catch(e => { console.error(e); process.exit(1); });diff --git a/scripts/integration-tests/02-fork-no-corruption.ts b/scripts/integration-tests/02-fork-no-corruption.tsnew file mode 100644index 00000000..8ad94719--- /dev/null+++ b/scripts/integration-tests/02-fork-no-corruption.ts@@ -0,0 +1,143 @@+/**+ * Regression test for:+ * - fix(qemu): savevm/loadvm for checkpoints (1caf148)+ * - fix(qemu): harden fork against post-loadvm virtio-serial flake (b2aa416)+ *+ * Before the fix, checkpoint creation used QMP migrate + external reflink copy+ * of the qcow2 files. QEMU's virtio-blk layer could have writes in flight at+ * reflink time that weren't yet flushed to the qcow2, so ~30% of forks came+ * up with corrupted workspace: empty marker.txt, git commands segfaulting,+ * ext4 EBADMSG errors. This is the headline bug the PR fixes.+ *+ * The virtio-serial mitigation (1s settle + retry) folds in here because a+ * flaky virtio-serial on fork manifests as "agent not ready after 30s" — we+ * want every fork to successfully reach the marker-verification step.+ *+ * This test creates N distinct checkpoints (each with a different marker hash)+ * and forks each one, verifying:+ * - /home/sandbox/marker.txt content matches what was written pre-checkpoint+ * - git fsck on the in-sandbox repo exits 0 (no object corruption)+ * - git log --oneline count matches expected+ *+ * Corruption rate must be 0% — one failure is a regression.+ */++import { Sandbox } from "../../sdks/typescript/src";+import { randomBytes } from "node:crypto";++const N = 10;++async function waitReady(sb: Sandbox, cpId: string, timeoutMs = 180000) {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ const cps = await sb.listCheckpoints();+ const cp = cps.find((c: any) => c.id === cpId);+ if (cp && (cp as any).status === "ready") return;+ if (cp && (cp as any).status === "failed") throw new Error("checkpoint failed");+ await new Promise(r => setTimeout(r, 1000));+ }+ throw new Error("checkpoint not ready");+}++async function main() {+ let passed = 0, failed = 0;+ const failures: string[] = [];+ const source = await Sandbox.create({ template: "base", timeout: 1800 });+ const toKill: string[] = [source.sandboxId];+ const cpIds: string[] = [];++ try {+ // Seed git repo+ await source.exec.run(+ "mkdir -p /home/sandbox/repo && cd /home/sandbox/repo && " ++ "git init -q && git config user.email t@t && git config user.name t && " ++ "echo initial > README && git add README && git commit -qm initial && sync",+ { timeout: 30 }+ );++ type CP = { id: string; marker: string; commitCount: number; label: string };+ const checkpoints: CP[] = [];++ // Create N checkpoints, each with distinct marker + new git commit+ for (let i = 0; i < N; i++) {+ const marker = randomBytes(32).toString("hex");+ const mutateCmd =+ `echo ${marker} > /home/sandbox/marker.txt && ` ++ `cd /home/sandbox/repo && echo "line-${i}" >> README && ` ++ `git add README && git commit -qm "cp-${i}" && sync`;+ const r = await source.exec.run(mutateCmd, { timeout: 30 });+ if ((r.exitCode ?? -1) !== 0) throw new Error(`mutate ${i}: exit=${r.exitCode}`);+ const cc = await source.exec.run(+ "cd /home/sandbox/repo && git log --oneline | wc -l",+ { timeout: 10 },+ );+ const commitCount = parseInt((cc.stdout ?? "").trim(), 10);+ const label = `no-corrupt-${i}-${Date.now()}`;+ const cp = await source.createCheckpoint(label);+ cpIds.push(cp.id);+ await waitReady(source, cp.id);+ checkpoints.push({ id: cp.id, marker, commitCount, label });+ console.log(` created ${i + 1}/${N} checkpoint ${label} commits=${commitCount}`);+ }++ // Fork each checkpoint and verify+ for (const cp of checkpoints) {+ let fork: Sandbox | null = null;+ try {+ fork = await Sandbox.createFromCheckpoint(cp.id, { timeout: 300 });+ toKill.push(fork.sandboxId);+ // Check 1: marker matches+ const m = await fork.exec.run("cat /home/sandbox/marker.txt", { timeout: 10 });+ const mv = (m.stdout ?? "").trim();+ if (mv !== cp.marker) {+ failed++;+ failures.push(`${cp.label}: marker mismatch (expected ${cp.marker.slice(0, 12)}… got '${mv.slice(0, 16)}')`);+ continue;+ }+ // Check 2: git fsck clean+ const fsck = await fork.exec.run(+ "cd /home/sandbox/repo && git fsck --full 2>&1",+ { timeout: 30 },+ );+ if ((fsck.exitCode ?? -1) !== 0) {+ failed++;+ failures.push(`${cp.label}: git fsck exit=${fsck.exitCode} out=${((fsck.stdout ?? "") + (fsck.stderr ?? "")).slice(0, 200)}`);+ continue;+ }+ // Check 3: commit count+ const cc = await fork.exec.run(+ "cd /home/sandbox/repo && git log --oneline | wc -l",+ { timeout: 10 },+ );+ const got = parseInt((cc.stdout ?? "").trim(), 10);+ if (got !== cp.commitCount) {+ failed++;+ failures.push(`${cp.label}: commit count expected=${cp.commitCount} got=${got}`);+ continue;+ }+ passed++;+ console.log(` ✓ fork ${fork.sandboxId} from ${cp.label}: marker+fsck+commits OK`);+ } catch (e: any) {+ failed++;+ failures.push(`${cp.label}: fork/verify threw ${e?.message ?? String(e)}`);+ } finally {+ if (fork) {+ try { await fork.kill(); } catch {}+ }+ }+ }+ } finally {+ for (const id of cpIds) {+ try { await source.deleteCheckpoint(id); } catch {}+ }+ for (const id of toKill) {+ try { const s = await Sandbox.connect(id); await s.kill(); } catch {}+ }+ }++ console.log(`\n=== ${passed}/${N} forks clean, ${failed} corrupt ===`);+ for (const f of failures) console.log(" - " + f);+ process.exit(failed === 0 ? 0 : 1);+}++main().catch(e => { console.error(e); process.exit(1); });diff --git a/scripts/integration-tests/03-hibernate-wake-routing.ts b/scripts/integration-tests/03-hibernate-wake-routing.tsnew file mode 100644index 00000000..ecf00c0b--- /dev/null+++ b/scripts/integration-tests/03-hibernate-wake-routing.ts@@ -0,0 +1,87 @@+/**+ * Regression test for: fix(api): invalidate proxy route cache on hibernate/wake (f4e3600)+ *+ * Before the fix, SandboxAPIProxy cached sandbox→worker routes. On multi-worker+ * deploys wake may land the sandbox on a different worker than hibernate did,+ * but the stale cache kept forwarding data-plane requests to the ex-hibernate+ * worker. That worker's router still showed StateHibernated, so any data-plane+ * request triggered a local auto-wake that failed with+ * 500 "auto-wake failed for sandbox X: no active hibernation"+ *+ * This test:+ * 1. Creates a sandbox+ * 2. Writes a marker so there's guest state to preserve+ * 3. Hibernates+ * 4. Wakes+ * 5. Calls exec.run (the first data-plane request post-wake)+ *+ * If cache invalidation is in place, step 5 succeeds and returns the marker.+ * Otherwise it returns the "auto-wake failed" 500.+ */++import { Sandbox } from "../../sdks/typescript/src";+import { randomBytes } from "node:crypto";++const ITERATIONS = 3;++async function wakeWithRetry(sb: Sandbox, maxAttempts = 15, delayMs = 2000) {+ let lastErr: any = null;+ for (let i = 0; i < maxAttempts; i++) {+ try {+ await sb.wake({ timeout: 300 });+ return;+ } catch (e: any) {+ const msg = e?.message ?? String(e);+ lastErr = e;+ if (msg.includes("BlobNotFound") || msg.includes("404")) {+ await new Promise(r => setTimeout(r, delayMs));+ continue;+ }+ throw e;+ }+ }+ throw lastErr;+}++async function main() {+ let passed = 0, failed = 0;++ for (let i = 0; i < ITERATIONS; i++) {+ const marker = randomBytes(16).toString("hex");+ const sb = await Sandbox.create({ template: "base", timeout: 600 });+ try {+ await sb.exec.run(+ `echo ${marker} > /home/sandbox/.marker && sync`,+ { timeout: 30 },+ );+ await sb.hibernate();+ await wakeWithRetry(sb);+ // The critical call: first data-plane request after wake. With a stale+ // proxy cache, this returned 500 "auto-wake failed".+ const r = await sb.exec.run("cat /home/sandbox/.marker", { timeout: 10 });+ const got = (r.stdout ?? "").trim();+ if (got === marker) {+ console.log(`[${i + 1}/${ITERATIONS}] ✓ hibernate→wake→exec.run routed correctly`);+ passed++;+ } else {+ console.log(`[${i + 1}/${ITERATIONS}] ✗ exec.run after wake returned wrong marker (got '${got.slice(0, 16)}')`);+ failed++;+ }+ } catch (e: any) {+ const msg = e?.message ?? String(e);+ if (msg.includes("auto-wake failed")) {+ console.log(`[${i + 1}/${ITERATIONS}] ✗ REGRESSION: stale proxy cache — ${msg}`);+ } else {+ console.log(`[${i + 1}/${ITERATIONS}] ✗ unexpected failure: ${msg}`);+ }+ failed++;+ } finally {+ try { await sb.kill(); } catch {}+ }+ }++ console.log(`\n=== ${passed}/${ITERATIONS} routed correctly, ${failed} regressed ===`);+ process.exit(failed === 0 ? 0 : 1);+}++main().catch(e => { console.error(e); process.exit(1); });diff --git a/scripts/integration-tests/04-hibernate-wake-data-preserved.ts b/scripts/integration-tests/04-hibernate-wake-data-preserved.tsnew file mode 100644index 00000000..8fd6b544--- /dev/null+++ b/scripts/integration-tests/04-hibernate-wake-data-preserved.ts@@ -0,0 +1,107 @@+/**+ * Regression test for: fix(qemu): remove superfluous post-loadvm mount on wake (9f550e2)+ *+ * Before the fix, doWake force-mounted /dev/vdb on /home/sandbox after loadvm.+ * On workers with the stale rootfs build (where the guest's init mounts vdb+ * at /workspace, not /home/sandbox), this force-mount shadowed the rootfs's+ * /home/sandbox directory with the empty workspace filesystem — silently+ * HIDING any files the user had written (those writes landed on rootfs.qcow2+ * because /home/sandbox was a regular directory at the time of the write).+ *+ * The user-visible symptom: hibernate → wake, then `ls /home/sandbox` shows+ * only "lost+found" and their data is apparently gone. (It's still on disk+ * inside rootfs.qcow2 — just hidden under the new mount.)+ *+ * This test:+ * 1. Writes multiple files + a git repo to /home/sandbox+ * 2. Hibernates+ * 3. Wakes+ * 4. Verifies every file is still present and readable+ *+ * With the fix in place, loadvm restores the correct guest mount state and+ * all files are preserved. Without it (on stale-rootfs workers), files vanish.+ */++import { Sandbox } from "../../sdks/typescript/src";+import { randomBytes } from "node:crypto";++async function wakeWithRetry(sb: Sandbox, maxAttempts = 15, delayMs = 2000) {+ let lastErr: any = null;+ for (let i = 0; i < maxAttempts; i++) {+ try { await sb.wake({ timeout: 300 }); return; } catch (e: any) {+ const msg = e?.message ?? String(e);+ lastErr = e;+ if (msg.includes("BlobNotFound") || msg.includes("404")) {+ await new Promise(r => setTimeout(r, delayMs)); continue;+ }+ throw e;+ }+ }+ throw lastErr;+}++async function main() {+ const markerA = randomBytes(16).toString("hex");+ const markerB = randomBytes(16).toString("hex");+ const sb = await Sandbox.create({ template: "base", timeout: 600 });+ let passed = 0, failed = 0;++ try {+ // Write a mix: plain file, nested dir, git repo+ await sb.exec.run(+ [+ `echo ${markerA} > /home/sandbox/top.txt`,+ `mkdir -p /home/sandbox/nested/deep`,+ `echo ${markerB} > /home/sandbox/nested/deep/inner.txt`,+ `cd /home/sandbox && git init -q repo && cd repo && git config user.email t@t && git config user.name t`,+ `cd /home/sandbox/repo && echo initial > README && git add README && git commit -qm initial`,+ `sync`,+ ].join(" && "),+ { timeout: 30 },+ );++ await sb.hibernate();+ await wakeWithRetry(sb);++ // Verify everything we wrote is still there+ const checks: { name: string; cmd: string; expect: string }[] = [+ { name: "top-level file", cmd: "cat /home/sandbox/top.txt", expect: markerA },+ { name: "nested file", cmd: "cat /home/sandbox/nested/deep/inner.txt", expect: markerB },+ { name: "git repo README", cmd: "cat /home/sandbox/repo/README", expect: "initial" },+ { name: "git repo commit count", cmd: "cd /home/sandbox/repo && git log --oneline | wc -l", expect: "1" },+ { name: "git fsck clean", cmd: "cd /home/sandbox/repo && git fsck --full 2>&1 && echo FSCK_OK", expect: "FSCK_OK" },+ ];++ for (const c of checks) {+ const r = await sb.exec.run(c.cmd, { timeout: 15 });+ const got = (r.stdout ?? "").trim();+ if (got === c.expect || got.endsWith(c.expect)) {+ console.log(` ✓ ${c.name}`);+ passed++;+ } else {+ const stderr = (r.stderr ?? "").slice(0, 120);+ console.log(` ✗ ${c.name}: expected '${c.expect.slice(0, 16)}' got '${got.slice(0, 40)}' stderr='${stderr}'`);+ failed++;+ }+ }++ // Also verify the workspace disk really is mounted at /home/sandbox+ // (would also have been broken by the wake mount shadow).+ const df = await sb.exec.run("df /home/sandbox | tail -1 | awk '{print $2}'", { timeout: 10 });+ const blocks = parseInt((df.stdout ?? "").trim(), 10);+ if (blocks > 1_000_000) {+ console.log(` ✓ /home/sandbox has substantial space (${blocks} 1K-blocks)`);+ passed++;+ } else {+ console.log(` ✗ /home/sandbox is unexpectedly small (${blocks} 1K-blocks) — may be on tiny rootfs`);+ failed++;+ }+ } finally {+ try { await sb.kill(); } catch {}+ }++ console.log(`\n=== ${passed} passed, ${failed} failed ===`);+ process.exit(failed === 0 ? 0 : 1);+}++main().catch(e => { console.error(e); process.exit(1); });diff --git a/scripts/integration-tests/README.md b/scripts/integration-tests/README.mdnew file mode 100644index 00000000..50e1bec1--- /dev/null+++ b/scripts/integration-tests/README.md@@ -0,0 +1,20 @@+# Integration tests for fork/hibernate/wake fixes++One test per fix in PR #128. Each test is self-contained, creates its own+resources, cleans up in finally, and exits non-zero on regression.++| # | Test file | Validates | Commit |+| - | ----------------------------------------- | ------------------------------------------------------------------------------------------- | ------- |+| 1 | `01-fork-sync-hibernate.ts` | `createFromCheckpoint` blocks until worker has the VM registered (no "sandbox not found") | 08d5320 |+| 2 | `02-fork-no-corruption.ts` | Forks from savevm-based checkpoints have correct workspace state (no EBADMSG / git segv) | 1caf148 + b2aa416 |+| 3 | `03-hibernate-wake-routing.ts` | Data-plane requests route to the current worker after wake (no "auto-wake failed") | f4e3600 |+| 4 | `04-hibernate-wake-data-preserved.ts` | Wake does not shadow `/home/sandbox` with an empty mount; all files are readable post-wake | 9f550e2 |++## Running++```+OPENCOMPUTER_API_URL=... OPENCOMPUTER_API_KEY=... \+ npx tsx scripts/integration-tests/01-fork-sync-hibernate.ts+```++Each script exits 0 on success, 1 on any failure.