Skip to content

An open-source, faster Devin alternative

TypeScript

corruption testing

Brian Reardon5419cb38354e
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 4576fe79..a7a23672 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -1438,8 +1438,28 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
if cp.OrgID != orgID {
return nil, http.StatusForbidden, fmt.Errorf("checkpoint does not belong to this organization")
}
+ // Poll for checkpoint readiness — checkpoints transition from "processing" to "ready"
+ // asynchronously. Wait up to 30s so SDK/CLI users don't have to poll manually.
if cp.Status != "ready" {
- return nil, http.StatusBadRequest, fmt.Errorf("checkpoint is not ready (status: %s)", cp.Status)
+ if cp.Status == "failed" {
+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint failed")
+ }
+ for i := 0; i < 30; i++ {
+ time.Sleep(1 * time.Second)
+ cp, err = s.store.GetCheckpoint(ctx, checkpointID)
+ if err != nil {
+ return nil, http.StatusNotFound, fmt.Errorf("checkpoint not found")
+ }
+ if cp.Status == "ready" {
+ break
+ }
+ if cp.Status == "failed" {
+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint failed")
+ }
+ }
+ if cp.Status != "ready" {
+ return nil, http.StatusBadRequest, fmt.Errorf("checkpoint is not ready after 30s (status: %s)", cp.Status)
+ }
}
// Parse optional overrides from request body
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index d39e01fa..0ee1e6c2 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -56,6 +56,7 @@ type VMInstance struct {
bootArgs string
restoring chan struct{}
opMu sync.Mutex // serializes destructive VM ops (checkpoint, restore, hibernate)
+ archiveDone chan struct{} // closed when async hibernate archive completes (nil if no archive in flight)
baseMemoryMB int // initial memory passed to -m (before virtio-mem)
virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)
}
@@ -167,6 +168,18 @@ func NewManager(cfg Config) (*Manager, error) {
log.Printf("qemu: warning: could not enable IP forwarding: %v", err)
}
+ // Verify the data directory supports reflink copy (required for snapshot safety).
+ if err := checkReflinkSupport(cfg.DataDir); err != nil {
+ return nil, fmt.Errorf("data directory does not support reflink: %w (XFS with reflink=1 required)", err)
+ }
+
+ // Clean up stale archive-staging directories from previous crashes
+ staleStaging, _ := filepath.Glob(filepath.Join(cfg.DataDir, "sandboxes", "*", "archive-staging"))
+ for _, d := range staleStaging {
+ os.RemoveAll(d)
+ log.Printf("qemu: cleaned up stale archive-staging: %s", d)
+ }
+
return &Manager{
cfg: cfg,
subnets: NewSubnetAllocator(),
@@ -709,7 +722,9 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
GuestPort: guestPort,
}
if metaJSON, err := json.Marshal(sbMeta); err == nil {
- _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644)
+ if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {
+ log.Printf("qemu: WARNING: failed to write sandbox-meta.json for %s: %v", sandboxDir, writeErr)
+ }
}
log.Printf("qemu: golden-create %s: DONE (%dms total, port=%d→%d, tap=%s, cid=%d)",
@@ -864,6 +879,11 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
// Create launches a new QEMU VM.
func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ // Check disk space before creating — refuse if >95% to prevent ENOSPC corruption
+ if usage, err := diskUsagePercent(m.cfg.DataDir); err == nil && usage > 95 {
+ return nil, fmt.Errorf("disk usage at %d%%, refusing new sandbox (threshold: 95%%)", usage)
+ }
+
id := cfg.SandboxID
if id == "" {
id = "sb-" + uuid.New().String()[:8]
@@ -1084,7 +1104,9 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
GuestPort: guestPort,
}
if metaJSON, err := json.Marshal(sbMeta); err == nil {
- _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644)
+ if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {
+ log.Printf("qemu: WARNING: failed to write sandbox-meta.json for %s: %v", sandboxDir, writeErr)
+ }
}
log.Printf("qemu: created VM %s (template=%s, cpu=%d, mem=%dMB, port=%d→%d, tap=%s, mac=%s, cid=%d)",
@@ -1254,6 +1276,17 @@ func (m *Manager) destroyVM(vm *VMInstance) error {
os.Remove(vm.qmpSockPath)
}
+ // Wait for any in-flight hibernate archive to complete before deleting files.
+ // Without this, os.RemoveAll races with the archive goroutine reading from
+ // archive-staging/ inside sandboxDir.
+ if vm.archiveDone != nil {
+ select {
+ case <-vm.archiveDone:
+ case <-time.After(5 * time.Minute):
+ log.Printf("qemu: CRITICAL: destroy %s: archive goroutine stuck for 5min, force cleanup", vm.ID)
+ }
+ }
+
if vm.sandboxDir != "" {
os.RemoveAll(vm.sandboxDir)
}
@@ -1608,7 +1641,9 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
return nil, err
}
- vm.opMu.Lock()
+ if !vm.opMu.TryLock() {
+ return nil, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)
+ }
defer vm.opMu.Unlock()
// Check if agent needs upgrading before we hibernate.
@@ -1645,7 +1680,16 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointSto
}
// Wake restores a VM from a snapshot.
+// Guards against double-wake: if the sandbox is already running, returns it.
func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey string, checkpointStore *storage.CheckpointStore, timeout int) (*types.Sandbox, error) {
+ // Prevent double wake — if sandbox is already running, return it
+ m.mu.RLock()
+ if existing, ok := m.vms[sandboxID]; ok {
+ m.mu.RUnlock()
+ log.Printf("qemu: wake %s: already running, returning existing VM", sandboxID)
+ return vmToSandbox(existing), nil
+ }
+ m.mu.RUnlock()
return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
}
@@ -1654,6 +1698,18 @@ func (m *Manager) TemplateCachePath(templateID, filename string) string {
return ""
}
+// CleanCheckpointCache removes the local cache for a checkpoint.
+// Acquires checkpointCacheMu write lock to ensure no ForkFromCheckpoint is
+// reading from the cache concurrently.
+func (m *Manager) CleanCheckpointCache(checkpointID string) {
+ m.checkpointCacheMu.Lock()
+ defer m.checkpointCacheMu.Unlock()
+ cacheDir := m.checkpointCacheDir(checkpointID)
+ if err := os.RemoveAll(cacheDir); err != nil {
+ log.Printf("qemu: clean checkpoint cache %s: %v", checkpointID, err)
+ }
+}
+
// checkpointCacheDir returns the local cache directory for a checkpoint's qcow2 files.
// Uses "checkpoint-snapshots/" (not "checkpoints/") to avoid collision with the S3
// checkpoint cache which stores tar.zst files in the "checkpoints/" directory.
@@ -1679,7 +1735,12 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
return "", "", err
}
- vm.opMu.Lock()
+ // Reject if another destructive operation (checkpoint, hibernate, restore) is in progress.
+ // Without this, rapid-fire checkpoints queue up and the agent gets into a bad state
+ // from overlapping SIGUSR1/reconnect cycles.
+ if !vm.opMu.TryLock() {
+ return "", "", fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)
+ }
defer vm.opMu.Unlock()
t0 := time.Now()
@@ -1733,6 +1794,19 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
}
if reconnErr == nil {
vm.agent = agentClient
+ } else {
+ // Agent reconnect failed — kill the VM to prevent an unmanageable orphan.
+ // The checkpoint itself is valid (savevm completed), so the user can fork from it.
+ 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
+ }
+ // Remove from vms map so it's not considered running
+ m.mu.Lock()
+ delete(m.vms, sandboxID)
+ m.mu.Unlock()
}
// Cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process).
@@ -1789,7 +1863,9 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
return err
}
- vm.opMu.Lock()
+ if !vm.opMu.TryLock() {
+ return fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)
+ }
defer vm.opMu.Unlock()
t0 := time.Now()
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index 8e3cc07e..9d5d7a06 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -73,10 +73,12 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strin
return "", "", fmt.Errorf("vm not found: %w", err)
}
- // Sync guest filesystems before copying
+ // Sync guest + reflink-copy drives under opMu to prevent concurrent
+ // checkpoint/destroy from modifying files during the copy.
+ vm.opMu.Lock()
if vm.agent != nil {
syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync", RunAsRoot: true})
+ _, _ = vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "sync"})
cancel()
}
@@ -84,21 +86,41 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strin
rootfsPath := detectDrivePath(sandboxDir, "rootfs")
workspacePath := detectDrivePath(sandboxDir, "workspace")
+ stagingDir, stageErr := os.MkdirTemp(mc.manager.cfg.DataDir, "migration-staging-")
+ if stageErr != nil {
+ vm.opMu.Unlock()
+ return "", "", fmt.Errorf("create staging dir: %w", stageErr)
+ }
+
+ stagedRootfs := filepath.Join(stagingDir, filepath.Base(rootfsPath))
+ stagedWorkspace := filepath.Join(stagingDir, filepath.Base(workspacePath))
+ if cpErr := copyFileReflink(rootfsPath, stagedRootfs); cpErr != nil {
+ vm.opMu.Unlock()
+ os.RemoveAll(stagingDir)
+ return "", "", fmt.Errorf("stage rootfs: %w", cpErr)
+ }
+ if cpErr := copyFileReflink(workspacePath, stagedWorkspace); cpErr != nil {
+ vm.opMu.Unlock()
+ os.RemoveAll(stagingDir)
+ return "", "", fmt.Errorf("stage workspace: %w", cpErr)
+ }
+ vm.opMu.Unlock() // release — uploads read from staging copies, not originals
+ defer os.RemoveAll(stagingDir)
+
rootfsKey = fmt.Sprintf("migrations/%s/rootfs.qcow2", sandboxID)
workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2", sandboxID)
t0 := time.Now()
- // Upload rootfs
+ // Upload from staged copies — QEMU can continue running on originals
state.Phase = "upload-rootfs"
- rootfsSize, err := mc.uploadFile(ctx, rootfsPath, rootfsKey)
+ rootfsSize, err := mc.uploadFile(ctx, stagedRootfs, rootfsKey)
if err != nil {
return "", "", fmt.Errorf("upload rootfs: %w", err)
}
- // Upload workspace
state.Phase = "upload-workspace"
- wsSize, err := mc.uploadFile(ctx, workspacePath, workspaceKey)
+ wsSize, err := mc.uploadFile(ctx, stagedWorkspace, workspaceKey)
if err != nil {
return "", "", fmt.Errorf("upload workspace: %w", err)
}
diff --git a/internal/qemu/network.go b/internal/qemu/network.go
index 1855b3a6..710cbd55 100644
--- a/internal/qemu/network.go
+++ b/internal/qemu/network.go
@@ -43,14 +43,21 @@ func (a *SubnetAllocator) Allocate() (*NetworkConfig, error) {
defer a.mu.Unlock()
block := a.next
+ start := block
for a.used[block] {
block++
if block > 16383 {
- return nil, fmt.Errorf("subnet pool exhausted")
+ block = 0 // wrap around to recycle released blocks
+ }
+ if block == start {
+ return nil, fmt.Errorf("subnet pool exhausted (%d in use)", len(a.used))
}
}
a.used[block] = true
a.next = block + 1
+ if a.next > 16383 {
+ a.next = 0
+ }
base := block * 4
b2 := byte(base >> 8)
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index c562dab4..cbfbbe77 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -10,6 +10,7 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "syscall"
"time"
"github.com/opensandbox/opensandbox/internal/sandbox"
@@ -134,9 +135,14 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
return nil, fmt.Errorf("marshal snapshot meta: %w", err)
}
metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
- if err := os.WriteFile(metaPath, metaJSON, 0644); err != nil {
+ // Atomic write: write to temp file then rename to avoid partial JSON on crash
+ tmpMetaPath := metaPath + ".tmp"
+ if err := os.WriteFile(tmpMetaPath, metaJSON, 0644); err != nil {
return nil, fmt.Errorf("write snapshot meta: %w", err)
}
+ if err := os.Rename(tmpMetaPath, metaPath); err != nil {
+ return nil, fmt.Errorf("rename snapshot meta: %w", err)
+ }
// Step 5: Clean up network
if vm.network != nil {
@@ -156,20 +162,50 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
vm.ID, localElapsed.Milliseconds())
// Step 9: Archive + upload to S3 in the background.
+ // Reflink-copy the qcow2 drives so the archive reads from stable copies
+ // while wake can freely open the originals. Without this, wake starts QEMU
+ // which modifies the qcow2 files while tar is still reading them →
+ // "file changed as we read it" → corrupted archive → data loss on next wake.
sandboxDir := vm.sandboxDir
sandboxID := vm.ID
- // Determine drive filenames for archiving (rootfs + workspace)
workspaceFile := filepath.Base(detectDrivePath(sandboxDir, "workspace"))
rootfsFile := filepath.Base(detectDrivePath(sandboxDir, "rootfs"))
+
+ archiveDir := filepath.Join(sandboxDir, "archive-staging")
+ if err := os.MkdirAll(archiveDir, 0755); err != nil {
+ return nil, fmt.Errorf("mkdir archive-staging: %w", err)
+ }
+ // Copy metadata
+ snapshotStaging := filepath.Join(archiveDir, "snapshot")
+ os.MkdirAll(snapshotStaging, 0755)
+ copyFileReflink(metaPath, filepath.Join(snapshotStaging, "snapshot-meta.json"))
+
+ // Reflink-copy drives (COW — fast, no extra disk until divergence).
+ // cp --reflink=auto falls back to regular copy if reflink not supported.
+ for _, driveFile := range []string{rootfsFile, workspaceFile} {
+ src := filepath.Join(sandboxDir, driveFile)
+ dst := filepath.Join(archiveDir, driveFile)
+ if err := copyFileReflink(src, dst); err != nil {
+ os.RemoveAll(archiveDir)
+ return nil, fmt.Errorf("copy %s for archive staging: %w", driveFile, err)
+ }
+ }
+ log.Printf("qemu: hibernate %s: archive staging ready (reflink copies)", sandboxID)
+
+ // Signal channel so destroyVM can wait for archive completion before deleting files.
+ archiveDone := make(chan struct{})
+ vm.archiveDone = archiveDone
+
m.uploadWg.Add(1)
go func() {
defer m.uploadWg.Done()
+ defer close(archiveDone)
+ defer os.RemoveAll(archiveDir) // clean up staging copies when done
t1 := time.Now()
archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")
- // savevm stores snapshot inside the qcow2 files — no separate mem file needed.
- // Archive just the metadata + drives.
- if err := createArchive(archivePath, sandboxDir, []string{
+ // Archive from the staging copies — originals are free for wake/QEMU.
+ if err := createArchive(archivePath, archiveDir, []string{
"snapshot/snapshot-meta.json",
rootfsFile,
workspaceFile,
@@ -189,7 +225,8 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {
- log.Printf("qemu: async S3 upload failed for %s: %v (keeping local archive for retry)", sandboxID, err)
+ log.Printf("qemu: async S3 upload failed for %s: %v", sandboxID, err)
+ os.Remove(archivePath) // clean up — local qcow2 files are the source of truth for same-worker wake
return
}
log.Printf("qemu: hibernate %s: S3 upload complete (%dms, key=%s)",
@@ -223,6 +260,26 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
snapshotDir := filepath.Join(sandboxDir, "snapshot")
metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")
+ // Wait for any in-flight hibernate archive to finish before proceeding.
+ // Same-worker wake: archive reads from staging copies (safe), but we need
+ // archive-staging/ cleaned up before starting QEMU to avoid disk waste.
+ // Cross-worker wake: S3 upload must complete before download can succeed.
+ archiveStagingDir := filepath.Join(sandboxDir, "archive-staging")
+ if fileExists(archiveStagingDir) {
+ log.Printf("qemu: wake %s: waiting for in-flight archive to complete", sandboxID)
+ for i := 0; i < 60; i++ { // up to 30 seconds
+ if !fileExists(archiveStagingDir) {
+ break
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+ if fileExists(archiveStagingDir) {
+ // Don't force-remove — the archive goroutine's defer will clean up.
+ // Removing while tar is mid-read corrupts the S3 archive.
+ log.Printf("qemu: wake %s: archive staging still present after 30s, proceeding (goroutine will clean up)", sandboxID)
+ }
+ }
+
// Step 1: Ensure qcow2 files are local
t0 := time.Now()
rootfsPath := detectDrivePath(sandboxDir, "rootfs")
@@ -672,6 +729,42 @@ func fileExists(path string) bool {
return err == nil && !info.IsDir()
}
+// checkReflinkSupport verifies the filesystem supports reflink by creating a test file
+// and reflink-copying it. Returns nil if reflink works, error otherwise.
+func checkReflinkSupport(dir string) error {
+ testFile := filepath.Join(dir, ".reflink-test")
+ testCopy := filepath.Join(dir, ".reflink-test-copy")
+ defer os.Remove(testFile)
+ defer os.Remove(testCopy)
+
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return err
+ }
+ if err := os.WriteFile(testFile, []byte("reflink-test"), 0644); err != nil {
+ return err
+ }
+ cmd := exec.Command("cp", "--reflink=always", testFile, testCopy)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("reflink test failed: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// diskUsagePercent returns the disk usage percentage for the given path.
+func diskUsagePercent(path string) (int, error) {
+ var stat syscall.Statfs_t
+ if err := syscall.Statfs(path, &stat); err != nil {
+ return 0, err
+ }
+ total := stat.Blocks * uint64(stat.Bsize)
+ free := stat.Bfree * uint64(stat.Bsize)
+ if total == 0 {
+ return 0, nil
+ }
+ used := total - free
+ return int(used * 100 / total), nil
+}
+
// copyFileReflink copies a file using cp --reflink=auto.
func copyFileReflink(src, dst string) error {
cmd := exec.Command("cp", "--reflink=auto", src, dst)
diff --git a/internal/sandbox/router.go b/internal/sandbox/router.go
index 436f04e1..76b1aa8e 100644
--- a/internal/sandbox/router.go
+++ b/internal/sandbox/router.go
@@ -15,10 +15,11 @@ import (
type SandboxState int
const (
- StateRunning SandboxState = iota
+ StateRunning SandboxState = iota
StateHibernated
StateWaking
- StateCreating // async creation in progress — commands wait until ready
+ StateHibernating // transitional: hibernate in progress, blocks new operations
+ StateCreating // async creation in progress — commands wait until ready
)
func (s SandboxState) String() string {
@@ -29,6 +30,8 @@ func (s SandboxState) String() string {
return "hibernated"
case StateWaking:
return "waking"
+ case StateHibernating:
+ return "hibernating"
case StateCreating:
return "creating"
default:
@@ -345,7 +348,7 @@ func (r *SandboxRouter) ensureRunning(ctx context.Context, sandboxID string) err
entry.mu.Unlock()
return nil
- case StateHibernated:
+ case StateHibernated, StateHibernating:
// Transition to waking, start wake, other requests will queue
entry.state = StateWaking
entry.wakeCh = make(chan struct{})
@@ -529,6 +532,9 @@ func (r *SandboxRouter) onTimeout(sandboxID string) {
entry.mu.Unlock()
return
}
+ // Set transitional state before releasing lock — prevents concurrent exec
+ // calls from routing to a VM that's about to be hibernated.
+ entry.state = StateHibernating
entry.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
diff --git a/scripts/qemu-tests/19-snapshot-corruption.sh b/scripts/qemu-tests/19-snapshot-corruption.sh
new file mode 100755
index 00000000..7af9cc7a
--- /dev/null
+++ b/scripts/qemu-tests/19-snapshot-corruption.sh
@@ -0,0 +1,263 @@
+#!/usr/bin/env bash
+# 19-snapshot-corruption.sh — Reproduce snapshot corruption scenarios
+# Tests the most likely corruption vectors:
+# 1. Kill during hibernate (async archive race)
+# 2. Heavy I/O during checkpoint (guest sync insufficiency)
+# 3. Rapid hibernate/wake cycles (state machine race)
+# 4. Fork under load (concurrent qcow2 access)
+# 5. Checkpoint + autosave collision
+set +u
+source "$(dirname "$0")/common.sh"
+
+TIMEOUT=120
+SANDBOXES=()
+cleanup() {
+ set +u
+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done
+ set -u
+}
+trap cleanup EXIT
+
+# ── Test 1: Kill shortly after hibernate ──────────────────────────────
+# Reproduces: async archive race — Kill arrives before tar finishes
+h "Kill During Hibernate (archive race)"
+
+SB=$(create_sandbox)
+SANDBOXES+=("$SB")
+
+# Write a large file to make the archive take longer
+exec_run "$SB" "bash" "-c" "dd if=/dev/urandom of=/workspace/large.bin bs=1M count=200 2>/dev/null" >/dev/null
+HASH_BEFORE=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/large.bin | cut -d' ' -f1")
+pass "Wrote 200MB, hash: ${HASH_BEFORE:0:16}..."
+
+# Hibernate — returns immediately, archive runs async
+api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null
+
+# Kill immediately — should race with the archive
+sleep 0.5
+KILL_RESULT=$(api -X DELETE "$API_URL/api/sandboxes/$SB")
+pass "Kill sent 500ms after hibernate"
+
+# Try to wake — if archive was corrupted, wake will fail or data will be wrong
+sleep 5
+WAKE_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}')
+if echo "$WAKE_RESULT" | grep -q '"running"'; then
+ HASH_AFTER=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/large.bin | cut -d' ' -f1")
+ if [ "$HASH_BEFORE" = "$HASH_AFTER" ]; then
+ pass "Wake succeeded, 200MB file intact after kill-during-hibernate"
+ else
+ fail "CORRUPTION: hash mismatch after kill-during-hibernate: $HASH_BEFORE vs $HASH_AFTER"
+ fi
+ destroy_sandbox "$SB"
+else
+ # Wake failed — could be because kill won, or archive was corrupted
+ if echo "$WAKE_RESULT" | grep -qi 'not found\|stopped\|gone'; then
+ pass "Kill won the race (sandbox destroyed before archive completed) — no corruption possible"
+ else
+ fail "Wake failed unexpectedly: $WAKE_RESULT"
+ fi
+fi
+
+# ── Test 2: Checkpoint during heavy I/O ──────────────────────────────
+# Reproduces: guest sync not completing before savevm
+h "Checkpoint During Heavy I/O"
+
+SB2=$(create_sandbox)
+SANDBOXES+=("$SB2")
+
+# Start continuous I/O in background
+exec_run "$SB2" "bash" "-c" "setsid bash -c 'while true; do dd if=/dev/urandom of=/workspace/churn.bin bs=1M count=50 conv=notrunc 2>/dev/null; sync; done' </dev/null >/dev/null 2>&1 &" >/dev/null
+pass "Background I/O started (50MB writes in loop)"
+
+# Write a known marker file
+exec_run "$SB2" "bash" "-c" "echo checkpoint-marker-42 > /workspace/marker.txt && sync" >/dev/null
+sleep 1
+
+# Create checkpoint while I/O is happening
+CP_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB2/checkpoints" -d '{"name":"io-stress-test"}')
+CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
+[ -n "$CP_ID" ] && [ "$CP_ID" != "None" ] && pass "Checkpoint during I/O: $CP_ID" || { fail "Checkpoint failed: $CP_RESULT"; }
+
+# Wait for checkpoint to process
+sleep 5
+
+# Fork from checkpoint — verify marker file
+FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":3600}')
+FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then
+ SANDBOXES+=("$FORK_ID")
+ sleep 8
+ MARKER=$(exec_stdout "$FORK_ID" "cat" "/workspace/marker.txt")
+ if [ "$MARKER" = "checkpoint-marker-42" ]; then
+ pass "Fork has correct marker file — checkpoint captured consistent state"
+ else
+ fail "CORRUPTION: marker file wrong in fork: '$MARKER' (expected 'checkpoint-marker-42')"
+ fi
+else
+ fail "Fork from I/O-stress checkpoint failed: $FORK_RESULT"
+fi
+
+# ── Test 3: Rapid hibernate/wake cycles ──────────────────────────────
+# Reproduces: state machine race, stale agent connections
+h "Rapid Hibernate/Wake Cycles (5x)"
+
+SB3=$(create_sandbox)
+SANDBOXES+=("$SB3")
+
+exec_run "$SB3" "bash" "-c" "echo cycle-test > /workspace/cycle.txt" >/dev/null
+
+CYCLE_OK=0
+CYCLE_FAIL=0
+for i in $(seq 1 5); do
+ # Hibernate
+ H_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB3/hibernate")
+ if ! echo "$H_RESULT" | grep -q '"hibernated"'; then
+ CYCLE_FAIL=$((CYCLE_FAIL+1))
+ fail "Cycle $i: hibernate failed: $H_RESULT"
+ continue
+ fi
+
+ # Wake immediately
+ W_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB3/wake" -d '{"timeout":3600}')
+ if ! echo "$W_RESULT" | grep -q '"running"'; then
+ CYCLE_FAIL=$((CYCLE_FAIL+1))
+ fail "Cycle $i: wake failed: $W_RESULT"
+ continue
+ fi
+
+ # Verify data
+ OUT=$(exec_stdout "$SB3" "cat" "/workspace/cycle.txt")
+ if [ "$OUT" = "cycle-test" ]; then
+ CYCLE_OK=$((CYCLE_OK+1))
+ else
+ CYCLE_FAIL=$((CYCLE_FAIL+1))
+ fail "CORRUPTION: cycle $i data wrong: '$OUT'"
+ fi
+done
+[ "$CYCLE_FAIL" -eq 0 ] && pass "All 5 hibernate/wake cycles preserved data" || fail "$CYCLE_FAIL/5 cycles had issues"
+
+# ── Test 4: Multiple forks from same checkpoint under load ───────────
+# Reproduces: concurrent qcow2 reflink races
+h "Concurrent Forks From Same Checkpoint"
+
+SB4=$(create_sandbox)
+SANDBOXES+=("$SB4")
+
+exec_run "$SB4" "bash" "-c" "echo fork-source > /workspace/source.txt && python3 -c 'print(1+1)'" >/dev/null
+CP2_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB4/checkpoints" -d '{"name":"fork-stress"}')
+CP2_ID=$(echo "$CP2_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
+[ -n "$CP2_ID" ] && pass "Checkpoint for fork stress: $CP2_ID" || { fail "Checkpoint failed"; summary; }
+
+sleep 5
+
+# Fire 5 forks simultaneously
+TMPDIR=$(mktemp -d)
+PIDS=()
+for i in $(seq 1 5); do
+ (
+ RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP2_ID" -d '{"timeout":300}')
+ FORK=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null)
+ echo "$FORK" > "$TMPDIR/fork-$i"
+ ) &
+ PIDS+=($!)
+done
+for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done
+
+# Verify each fork
+FORK_OK=0
+FORK_FAIL=0
+for i in $(seq 1 5); do
+ FORK_ID=$(cat "$TMPDIR/fork-$i" 2>/dev/null)
+ if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "FAIL" ]; then
+ SANDBOXES+=("$FORK_ID")
+ sleep 3
+ OUT=$(exec_stdout "$FORK_ID" "cat" "/workspace/source.txt")
+ if [ "$OUT" = "fork-source" ]; then
+ FORK_OK=$((FORK_OK+1))
+ else
+ FORK_FAIL=$((FORK_FAIL+1))
+ fail "CORRUPTION: fork $i has wrong data: '$OUT'"
+ fi
+ else
+ FORK_FAIL=$((FORK_FAIL+1))
+ fail "Fork $i creation failed"
+ fi
+done
+rm -rf "$TMPDIR"
+[ "$FORK_FAIL" -eq 0 ] && pass "All 5 concurrent forks have correct data" || fail "$FORK_FAIL/5 forks corrupted"
+
+# ── Test 5: Checkpoint + immediate exec (autosave collision sim) ─────
+# Reproduces: concurrent agent operations during savevm
+h "Exec During Checkpoint (autosave collision)"
+
+SB5=$(create_sandbox)
+SANDBOXES+=("$SB5")
+
+exec_run "$SB5" "bash" "-c" "echo pre-checkpoint > /workspace/state.txt && sync" >/dev/null
+
+# Fire checkpoint and exec simultaneously
+(
+ CP3_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB5/checkpoints" -d '{"name":"exec-collision"}')
+ echo "$CP3_RESULT" > /tmp/cp3-result.json
+) &
+CP3_PID=$!
+
+# Immediately fire exec commands while checkpoint is processing
+for j in $(seq 1 5); do
+ exec_run "$SB5" "bash" "-c" "echo writing-during-checkpoint-$j >> /workspace/during.txt" >/dev/null 2>&1 &
+done
+wait $CP3_PID 2>/dev/null
+
+CP3_ID=$(cat /tmp/cp3-result.json | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
+if [ -n "$CP3_ID" ] && [ "$CP3_ID" != "None" ]; then
+ pass "Checkpoint created during concurrent execs: $CP3_ID"
+
+ sleep 5
+ # Fork and verify pre-checkpoint state is correct
+ FORK5_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP3_ID" -d '{"timeout":300}')
+ FORK5_ID=$(echo "$FORK5_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+ if [ -n "$FORK5_ID" ] && [ "$FORK5_ID" != "None" ]; then
+ SANDBOXES+=("$FORK5_ID")
+ sleep 8
+ STATE=$(exec_stdout "$FORK5_ID" "cat" "/workspace/state.txt")
+ if [ "$STATE" = "pre-checkpoint" ]; then
+ pass "Fork has correct pre-checkpoint state despite concurrent execs"
+ else
+ fail "CORRUPTION: fork state wrong: '$STATE'"
+ fi
+ else
+ fail "Fork from exec-collision checkpoint failed: $FORK5_RESULT"
+ fi
+else
+ fail "Checkpoint during concurrent execs failed: $(cat /tmp/cp3-result.json)"
+fi
+rm -f /tmp/cp3-result.json
+
+# ── Test 6: Hibernate with large dirty pages ─────────────────────────
+# Reproduces: sync returning before flush completes
+h "Hibernate With Dirty Pages"
+
+SB6=$(create_sandbox)
+SANDBOXES+=("$SB6")
+
+# Write 100MB, then immediately hibernate without waiting for sync
+exec_run "$SB6" "bash" "-c" "dd if=/dev/urandom of=/workspace/dirty.bin bs=1M count=100 2>/dev/null" >/dev/null
+DIRTY_HASH=$(exec_stdout "$SB6" "bash" "-c" "sha256sum /workspace/dirty.bin | cut -d' ' -f1")
+pass "Wrote 100MB dirty data, hash: ${DIRTY_HASH:0:16}..."
+
+# Hibernate immediately — guest may still have dirty pages
+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB6/hibernate")
+echo "$RESULT" | grep -q '"hibernated"' && pass "Hibernated with dirty pages" || fail "Hibernate: $RESULT"
+
+# Wake and verify
+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB6/wake" -d '{"timeout":3600}')
+echo "$RESULT" | grep -q '"running"' && pass "Woke" || { fail "Wake: $RESULT"; summary; }
+
+DIRTY_HASH_AFTER=$(exec_stdout "$SB6" "bash" "-c" "sha256sum /workspace/dirty.bin | cut -d' ' -f1")
+if [ "$DIRTY_HASH" = "$DIRTY_HASH_AFTER" ]; then
+ pass "100MB file intact after hibernate with dirty pages"
+else
+ fail "CORRUPTION: dirty page hash mismatch: $DIRTY_HASH vs $DIRTY_HASH_AFTER"
+fi
+
+summary
diff --git a/scripts/qemu-tests/20-snapshot-stress.sh b/scripts/qemu-tests/20-snapshot-stress.sh
new file mode 100755
index 00000000..715ae7ea
--- /dev/null
+++ b/scripts/qemu-tests/20-snapshot-stress.sh
@@ -0,0 +1,139 @@
+#!/usr/bin/env bash
+# 20-snapshot-stress.sh — Stress test for snapshot corruption
+# Runs corruption-prone operations in tight loops to maximize race window exposure.
+# Each iteration creates a sandbox, writes data, and tests one corruption vector.
+set +u
+source "$(dirname "$0")/common.sh"
+
+TIMEOUT=120
+SANDBOXES=()
+cleanup() {
+ set +u
+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done
+ set -u
+}
+trap cleanup EXIT
+
+ITERATIONS="${1:-10}"
+
+# ── Stress 1: Kill-during-hibernate loop ─────────────────────────────
+h "Kill-During-Hibernate Stress ($ITERATIONS iterations)"
+
+RACE_WINS=0
+RACE_CLEAN=0
+RACE_CORRUPT=0
+for i in $(seq 1 "$ITERATIONS"); do
+ SB=$(create_sandbox)
+ SANDBOXES+=("$SB")
+
+ # Write data + get hash
+ exec_run "$SB" "bash" "-c" "dd if=/dev/urandom of=/workspace/test.bin bs=1M count=50 2>/dev/null && sync" >/dev/null
+ HASH=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/test.bin | cut -d' ' -f1")
+
+ # Hibernate then kill with varying delays (0ms, 100ms, 200ms, etc)
+ api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null
+ DELAY=$(( (i % 5) * 100 ))
+ [ "$DELAY" -gt 0 ] && sleep "0.${DELAY}"
+ api -X DELETE "$API_URL/api/sandboxes/$SB" >/dev/null
+
+ # Try to wake
+ sleep 3
+ WAKE=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":300}')
+ if echo "$WAKE" | grep -q '"running"'; then
+ HASH_AFTER=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/test.bin | cut -d' ' -f1")
+ if [ "$HASH" = "$HASH_AFTER" ]; then
+ RACE_CLEAN=$((RACE_CLEAN+1))
+ else
+ RACE_CORRUPT=$((RACE_CORRUPT+1))
+ fail " Iteration $i: CORRUPTION — hash mismatch (delay=${DELAY}ms)"
+ fi
+ destroy_sandbox "$SB"
+ else
+ RACE_WINS=$((RACE_WINS+1))
+ fi
+done
+printf ' Kill won: %d | Clean wake: %d | Corrupt: %d\n' "$RACE_WINS" "$RACE_CLEAN" "$RACE_CORRUPT"
+[ "$RACE_CORRUPT" -eq 0 ] && pass "No corruption in $ITERATIONS kill-during-hibernate iterations" || fail "$RACE_CORRUPT/$ITERATIONS iterations had corruption"
+
+# ── Stress 2: Rapid checkpoint + fork loop ───────────────────────────
+h "Rapid Checkpoint+Fork Stress ($ITERATIONS iterations)"
+
+SB_BASE=$(create_sandbox)
+SANDBOXES+=("$SB_BASE")
+
+FORK_OK=0
+FORK_FAIL=0
+for i in $(seq 1 "$ITERATIONS"); do
+ # Write unique marker
+ MARKER="marker-$i-$RANDOM"
+ exec_run "$SB_BASE" "bash" "-c" "echo $MARKER > /workspace/marker.txt && sync && sync" >/dev/null
+ sleep 1
+
+ # Checkpoint
+ CP_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB_BASE/checkpoints" -d "{\"name\":\"stress-$i-$RANDOM\"}")
+ CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
+ [ -z "$CP_ID" ] || [ "$CP_ID" = "None" ] && { fail " Checkpoint $i failed"; continue; }
+
+ sleep 5
+
+ # Fork and verify
+ FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":120}')
+ FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+ if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then
+ SANDBOXES+=("$FORK_ID")
+ sleep 5
+ GOT=$(exec_stdout "$FORK_ID" "cat" "/workspace/marker.txt")
+ if [ "$GOT" = "$MARKER" ]; then
+ FORK_OK=$((FORK_OK+1))
+ else
+ FORK_FAIL=$((FORK_FAIL+1))
+ fail " Iteration $i: CORRUPTION — expected '$MARKER' got '$GOT'"
+ fi
+ destroy_sandbox "$FORK_ID"
+ else
+ FORK_FAIL=$((FORK_FAIL+1))
+ fail " Fork $i failed: $FORK_RESULT"
+ fi
+done
+[ "$FORK_FAIL" -eq 0 ] && pass "All $FORK_OK/$ITERATIONS checkpoint+fork iterations clean" || fail "$FORK_FAIL/$ITERATIONS had issues"
+
+# ── Stress 3: Hibernate/wake rapid cycles ────────────────────────────
+h "Hibernate/Wake Rapid Cycles ($ITERATIONS iterations)"
+
+SB_CYCLE=$(create_sandbox)
+SANDBOXES+=("$SB_CYCLE")
+
+exec_run "$SB_CYCLE" "bash" "-c" "dd if=/dev/urandom of=/workspace/persist.bin bs=1M count=20 2>/dev/null && sync" >/dev/null
+PERSIST_HASH=$(exec_stdout "$SB_CYCLE" "bash" "-c" "sha256sum /workspace/persist.bin | cut -d' ' -f1")
+
+CYCLE_OK=0
+CYCLE_FAIL=0
+for i in $(seq 1 "$ITERATIONS"); do
+ H=$(api -X POST "$API_URL/api/sandboxes/$SB_CYCLE/hibernate")
+ if ! echo "$H" | grep -q '"hibernated"'; then
+ CYCLE_FAIL=$((CYCLE_FAIL+1))
+ fail " Cycle $i: hibernate failed"
+ # Try to recover
+ sleep 2
+ continue
+ fi
+
+ W=$(api -X POST "$API_URL/api/sandboxes/$SB_CYCLE/wake" -d '{"timeout":3600}')
+ if ! echo "$W" | grep -q '"running"'; then
+ CYCLE_FAIL=$((CYCLE_FAIL+1))
+ fail " Cycle $i: wake failed: $W"
+ sleep 2
+ continue
+ fi
+
+ GOT_HASH=$(exec_stdout "$SB_CYCLE" "bash" "-c" "sha256sum /workspace/persist.bin | cut -d' ' -f1")
+ if [ "$PERSIST_HASH" = "$GOT_HASH" ]; then
+ CYCLE_OK=$((CYCLE_OK+1))
+ else
+ CYCLE_FAIL=$((CYCLE_FAIL+1))
+ fail " CORRUPTION: cycle $i hash mismatch"
+ fi
+done
+[ "$CYCLE_FAIL" -eq 0 ] && pass "All $CYCLE_OK/$ITERATIONS hibernate/wake cycles clean" || fail "$CYCLE_FAIL/$ITERATIONS cycles had issues"
+
+summary