An open-source, faster Devin alternative
TypeScript
merged disk wip
Brian Reardonc422e12e74bd
diff --git a/cmd/worker/golden_upload.go b/cmd/worker/golden_upload.goindex 636a2179..0b88336d 100644--- a/cmd/worker/golden_upload.go+++ b/cmd/worker/golden_upload.go@@ -29,7 +29,7 @@ import (//// Reads OPENSANDBOX_GLOBAL_BLOB_* env vars for endpoint + creds. Fails loud// if blobstore isn't configured.-func uploadGolden(path string) error {+func uploadGolden(path string, versionedOnly bool) error {// Bootstrap from the appropriate cloud vault — same pattern as main(). One// of these picks up worker-global-blob-* secrets so the upload knows where// to push; the other is a no-op when its trigger env var isn't set.@@ -92,6 +92,16 @@ func uploadGolden(path string) error {}log.Printf("uploaded %s (%dms)", versionedKey, time.Since(t0).Milliseconds())+ // The unversioned "current" pointer is what workers fetch on cache miss.+ // Skip it for --versioned-only (seeding a merged base) so split workers'+ // fallback isn't repointed at a merged image; cross-golden ops still find+ // this base by its hashed key above.+ if versionedOnly {+ log.Printf("skipping default.ext4 current-pointer (--versioned-only)")+ log.Printf("done in %s", time.Since(t0).Round(time.Millisecond))+ return nil+ }+t1 := time.Now()if err := blobstore.Upload(ctx, store, bucket, "default.ext4", path); err != nil {return fmt.Errorf("upload default.ext4: %w", err)diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 13cb0da3..8c0b899a 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -72,11 +72,22 @@ func main() {// run this at AMI-build time. Reads OPENSANDBOX_GLOBAL_BLOB_* env vars// for the destination.if len(os.Args) >= 2 && os.Args[1] == "golden-upload" {- if len(os.Args) != 3 {- fmt.Fprintln(os.Stderr, "usage: opensandbox-worker golden-upload <path-to-default.ext4>")+ // Usage: golden-upload <path> [--versioned-only]+ // --versioned-only pushes ONLY bases/{hash}/default.ext4 and NOT the+ // default.ext4 "current" pointer. Required when seeding a MERGED base so+ // split workers' cache-miss fallback isn't repointed at a 20GB merged+ // image; cross-golden fork/migrate still resolves it by content hash.+ if len(os.Args) < 3 {+ fmt.Fprintln(os.Stderr, "usage: opensandbox-worker golden-upload <path-to-default.ext4> [--versioned-only]")os.Exit(2)}- if err := uploadGolden(os.Args[2]); err != nil {+ versionedOnly := false+ for _, a := range os.Args[3:] {+ if a == "--versioned-only" {+ versionedOnly = true+ }+ }+ if err := uploadGolden(os.Args[2], versionedOnly); err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(1)}@@ -253,6 +264,7 @@ func main() {DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,DefaultCPUs: cfg.DefaultSandboxCPUs,DefaultDiskMB: cfg.DefaultSandboxDiskMB,+ GoldenLayout: cfg.GoldenDiskLayout,GlobalBlob: globalBlob,GlobalBlobGoldensBucket: cfg.GlobalBlobGoldensBucket,GlobalBlobGoldenKey: "default.ext4",diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.shindex be888bea..a38b2d3f 100755--- a/deploy/ec2/build-rootfs-docker.sh+++ b/deploy/ec2/build-rootfs-docker.sh@@ -20,7 +20,21 @@ set -euo pipefailAGENT_BIN="${1:?Usage: $0 AGENT_BIN IMAGES_DIR [IMAGE_NAME]}"IMAGES_DIR="${2:?Usage: $0 AGENT_BIN IMAGES_DIR [IMAGE_NAME]}"IMAGE_NAME="${3:-default}"-EXT4_SIZE_MB="${EXT4_SIZE_MB:-4096}"++# DISK_LAYOUT selects the block topology this base image is built for:+# split (default) — legacy two-disk: a 4GB rootfs (OS) + a separate workspace+# disk (vdb) mounted at /home/sandbox.+# merged — single-disk: OS and /home/sandbox on ONE ~20GB rootfs, no+# vdb. The rootfs image content is identical (same init,+# which already no-ops the vdb mount when no vdb is present);+# only the size floor differs so /home/sandbox has room.+DISK_LAYOUT="${DISK_LAYOUT:-split}"+if [ "$DISK_LAYOUT" = "merged" ]; then+ EXT4_SIZE_MB="${EXT4_SIZE_MB:-20480}"+ ROOTFS_MIN_MB="${ROOTFS_MIN_MB:-20480}"+else+ EXT4_SIZE_MB="${EXT4_SIZE_MB:-4096}"+fiSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"@@ -101,7 +115,11 @@ if mount /dev/vdb /home/sandbox 2>/dev/null || mount /dev/vdb1 /home/sandbox 2>/chown sandbox:sandbox /home/sandbox 2>/dev/nullecho "init: workspace mounted (/dev/vdb -> /home/sandbox)"else- echo "init: warning: no data disk found, /home/sandbox is ephemeral"+ # No vdb attached — merged single-disk layout. /home/sandbox is a directory+ # on the rootfs (persistent, captured in checkpoints/snapshots), not ephemeral.+ mkdir -p /home/sandbox+ chown sandbox:sandbox /home/sandbox 2>/dev/null+ echo "init: single-disk (merged) layout — /home/sandbox on rootfs"fi# ── Mount virtual filesystems (in the final root) ──@@ -252,11 +270,19 @@ docker rm -f osb-rootfs-tmplog "Converting to ext4 (${EXT4_SIZE_MB}MB sparse)..."EXT4_PATH="$TMPDIR/rootfs.ext4"truncate -s "${EXT4_SIZE_MB}M" "$EXT4_PATH"+# Eagerly initialize the inode tables + journal at mkfs time for the merged+# layout. Default (lazy) init leaves most inode-table groups uninitialized, so+# ext4lazyinit zeroes them in the BACKGROUND on first mount of every sandbox —+# and a 20GB fs has ~5x the inode tables of the 4GB split rootfs. Under a+# create-burst that background I/O contends and starves the in-guest agent,+# producing multi-second (sometimes ~30s) agent-ready times. Eager init pays+# that cost once, at build, so every merged box resumes clean.+MKFS_E="lazy_itable_init=0,lazy_journal_init=0"if [ -n "${ROOTFS_UUID:-}" ]; thenlog "Using deterministic UUID: $ROOTFS_UUID"- mkfs.ext4 -q -F -L rootfs -U "$ROOTFS_UUID" -E hash_seed="$ROOTFS_UUID" "$EXT4_PATH"+ mkfs.ext4 -q -F -L rootfs -U "$ROOTFS_UUID" -E "hash_seed=$ROOTFS_UUID,$MKFS_E" "$EXT4_PATH"else- mkfs.ext4 -q -F -L rootfs "$EXT4_PATH"+ mkfs.ext4 -q -F -L rootfs -E "$MKFS_E" "$EXT4_PATH"fiMNT_DIR="$TMPDIR/mnt"diff --git a/internal/config/config.go b/internal/config/config.goindex 2d3d3566..b2d2a533 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -104,6 +104,14 @@ type Config struct {ImagesDir string // Path to base rootfs imagesQEMUBin string // Path to qemu-system binary (default: "qemu-system-x86_64")+ // GoldenDiskLayout selects the block topology this worker builds its golden+ // with — "" / "split" = legacy two-disk (rootfs + workspace), "merged" =+ // single 20GB disk (OS + /home/sandbox). Controls the layout of freshly+ // CREATED sandboxes only; forks/wakes follow each snapshot's recorded layout.+ // This is the Phase-3 merged-create flip — leave empty until the whole fleet+ // runs dual-mode code.+ GoldenDiskLayout string+// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)EC2AMI string // Custom AMI for worker instancesEC2InstanceType string // single fallback type; used only when EC2InstanceTypes is empty@@ -352,6 +360,8 @@ func Load() (*Config, error) {ImagesDir: os.Getenv("OPENSANDBOX_IMAGES_DIR"), // default derived from DataDirQEMUBin: envOrDefault("OPENSANDBOX_QEMU_BIN", "qemu-system-x86_64"),+ GoldenDiskLayout: os.Getenv("OPENSANDBOX_GOLDEN_DISK_LAYOUT"), // "" ⇒ split (merged-create off)+EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),EC2InstanceTypes: splitCSV(os.Getenv("OPENSANDBOX_EC2_INSTANCE_TYPES")),diff --git a/internal/qemu/checkpoint_rebase.go b/internal/qemu/checkpoint_rebase.goindex f17f199c..3a15fb07 100644--- a/internal/qemu/checkpoint_rebase.go+++ b/internal/qemu/checkpoint_rebase.go@@ -50,6 +50,14 @@ func (m *Manager) ensureCheckpointRebased(ctx context.Context, checkpointID strireturn nil}+ // A converted merged variant (see convert_merge.go) is a self-contained,+ // flattened rootfs with no backing and no GoldenVersion — there is nothing+ // to rebase, and the size-guard can't catch a same-size/different-content+ // base, so skip rebase entirely for merged-without-golden checkpoints.+ if IsMerged(meta.DiskLayout) && meta.GoldenVersion == "" {+ return nil+ }+if meta.GoldenVersion == "" {return m.checkLegacyCheckpoint(checkpointID, meta)}diff --git a/internal/qemu/convert_merge.go b/internal/qemu/convert_merge.gonew file mode 100644index 00000000..331c6ecc--- /dev/null+++ b/internal/qemu/convert_merge.go@@ -0,0 +1,271 @@+package qemu++import (+ "context"+ "encoding/json"+ "fmt"+ "log"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"+)++// mergedVariantSuffix names the cache dir of a checkpoint's converted merged+// variant, e.g. "cp-abc123-merged".+const mergedVariantSuffix = "-merged"++// maybeConvertToMergedVariant implements convert-on-fork: when this worker+// creates merged sandboxes, a fork of a legacy SPLIT, disk_only checkpoint is+// transparently served from a memoized MERGED variant instead of a split box,+// so "any new box is merged" holds even for forks of pre-merge templates.+//+// It returns the checkpointID to actually fork from — the merged variant's ID+// when a conversion applies (building it once, on first fork), or "" when no+// conversion is needed (the caller then forks the original as-is). RAM-bearing+// (full) checkpoints are never converted: loadvm welds the saved device model+// to the two-disk topology, so converting would discard process state.+func (m *Manager) maybeConvertToMergedVariant(ctx context.Context, checkpointID string) (string, error) {+ // Only convert when this worker creates merged boxes. On a split worker,+ // forks stay split (dual-mode).+ if !IsMerged(m.cfg.GoldenLayout) {+ return "", nil+ }+ // Don't recurse on an already-merged variant.+ if strings.HasSuffix(checkpointID, mergedVariantSuffix) {+ return "", nil+ }++ srcCacheDir := m.checkpointCacheDir(checkpointID)+ metaPath := filepath.Join(srcCacheDir, "snapshot", "snapshot-meta.json")+ data, err := os.ReadFile(metaPath)+ if err != nil {+ return "", nil // no local meta — let the normal fork path handle it+ }+ var meta SnapshotMeta+ if json.Unmarshal(data, &meta) != nil {+ return "", nil+ }++ // Already merged → nothing to convert.+ if IsMerged(meta.DiskLayout) {+ return "", nil+ }+ // Only disk_only checkpoints can be converted (no RAM to discard).+ if !isDiskOnlyCheckpoint(srcCacheDir) {+ return "", nil+ }++ mergedID := checkpointID + mergedVariantSuffix+ mergedCacheDir := m.checkpointCacheDir(mergedID)+ if mergedVariantReady(mergedCacheDir) {+ return mergedID, nil // memoized hit+ }++ // Collapse concurrent conversions of the same checkpoint.+ _, err, _ = m.convertSF.Do(mergedID, func() (interface{}, error) {+ if mergedVariantReady(mergedCacheDir) {+ return nil, nil+ }+ log.Printf("qemu: convert-on-fork: building merged variant of %s → %s", checkpointID, mergedID)+ t0 := time.Now()+ if err := m.buildMergedVariant(ctx, srcCacheDir, mergedCacheDir, meta); err != nil {+ return nil, err+ }+ log.Printf("qemu: convert-on-fork: merged variant %s ready (%dms)", mergedID, time.Since(t0).Milliseconds())+ return nil, nil+ })+ if err != nil {+ return "", fmt.Errorf("convert %s to merged: %w", checkpointID, err)+ }+ return mergedID, nil+}++// isDiskOnlyCheckpoint reports whether a checkpoint cache holds only disk state+// (no savevm internal snapshot / no memory dump) — the only kind convertible to+// merged, since it cold-boots rather than loadvm-restoring a device model.+func isDiskOnlyCheckpoint(cacheDir string) bool {+ return !fileExists(filepath.Join(cacheDir, "snapshot-name")) &&+ !fileExists(filepath.Join(cacheDir, "mem")) &&+ !fileExists(filepath.Join(cacheDir, "mem.zst"))+}++// mergedVariantReady reports whether a merged variant cache dir is fully built.+func mergedVariantReady(cacheDir string) bool {+ return fileExists(filepath.Join(cacheDir, "rootfs.qcow2")) &&+ fileExists(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json"))+}++// buildMergedVariant produces a merged (single-disk) checkpoint from a split+// disk_only checkpoint: flatten the split rootfs into a self-contained image,+// grow it to the merged default size, fold the workspace's contents into+// /home/sandbox, and publish it atomically with merged metadata.+//+// The result is a SELF-CONTAINED (backing-less) rootfs, tagged merged with an+// empty GoldenVersion — the split OS bytes differ from the merged golden's, so+// it can't be safely rebased onto it; ensureCheckpointRebased skips it.+//+// Requires a Linux host with qemu-nbd + root (the fold step loop-mounts qcow2s).+func (m *Manager) buildMergedVariant(ctx context.Context, srcCacheDir, dstCacheDir string, srcMeta SnapshotMeta) error {+ staging := dstCacheDir + ".staging"+ os.RemoveAll(staging)+ if err := os.MkdirAll(filepath.Join(staging, "snapshot"), 0755); err != nil {+ return fmt.Errorf("mkdir staging: %w", err)+ }+ success := false+ defer func() {+ if !success {+ os.RemoveAll(staging)+ }+ }()++ srcRootfs := filepath.Join(srcCacheDir, "rootfs.qcow2")+ srcWorkspace := filepath.Join(srcCacheDir, "workspace.qcow2")+ dstRootfs := filepath.Join(staging, "rootfs.qcow2")++ // Point the split rootfs at its correct base so the flatten below pulls in+ // the full OS (best-effort — resolveBaseForVersion may need the store).+ if srcMeta.GoldenVersion != "" {+ if basePath, berr := m.resolveBaseForVersion(ctx, srcMeta.GoldenVersion); berr == nil {+ if rerr := rebaseMetadataOnly(ctx, srcRootfs, basePath); rerr != nil {+ log.Printf("qemu: convert-on-fork: pre-flatten rebase of %s failed (continuing): %v", srcRootfs, rerr)+ }+ }+ }++ // 1. Copy + flatten the split rootfs into a self-contained image (merges the+ // backing base into the overlay; preserves internal state).+ if err := copyFileReflink(srcRootfs, dstRootfs); err != nil {+ return fmt.Errorf("copy rootfs: %w", err)+ }+ if out, err := exec.CommandContext(ctx, "qemu-img", "rebase", "-b", "", dstRootfs).CombinedOutput(); err != nil {+ return fmt.Errorf("flatten rootfs: %w (%s)", err, strings.TrimSpace(string(out)))+ }++ // 2. Grow the image to the merged default size (region past the old ext4+ // reads as zeros until resize2fs in the fold step extends the fs).+ targetMB := m.cfg.DefaultDiskMB+ if targetMB <= 0 {+ targetMB = 20480+ }+ if err := ResizeWorkspace(dstRootfs, targetMB); err != nil {+ return fmt.Errorf("grow rootfs to %dMB: %w", targetMB, err)+ }++ // 3. Fold the workspace's /home/sandbox data into the merged rootfs (also+ // grows the root ext4 to fill the resized image).+ if fileExists(srcWorkspace) {+ if err := foldWorkspaceIntoRootfs(ctx, dstRootfs, srcWorkspace); err != nil {+ return fmt.Errorf("fold workspace into rootfs: %w", err)+ }+ } else {+ // No workspace to fold — still grow the ext4 to fill the image.+ if err := growRootfsFilesystem(ctx, dstRootfs); err != nil {+ return fmt.Errorf("grow rootfs filesystem: %w", err)+ }+ }++ // 4. Write merged metadata: self-contained (no GoldenVersion), single disk.+ mergedMeta := srcMeta+ mergedMeta.DiskLayout = LayoutMerged+ mergedMeta.GoldenVersion = ""+ mergedMeta.WorkspacePath = ""+ mergedMeta.RootfsPath = ""+ mergedMeta.SnapshotedAt = time.Now()+ metaJSON, _ := json.Marshal(&mergedMeta)+ if err := os.WriteFile(filepath.Join(staging, "snapshot", "snapshot-meta.json"), metaJSON, 0644); err != nil {+ return fmt.Errorf("write merged meta: %w", err)+ }++ // 5. Publish atomically under the cache write lock.+ m.checkpointCacheMu.Lock()+ os.RemoveAll(dstCacheDir)+ renameErr := os.Rename(staging, dstCacheDir)+ m.checkpointCacheMu.Unlock()+ if renameErr != nil {+ return fmt.Errorf("publish merged variant: %w", renameErr)+ }+ success = true+ return nil+}++// foldWorkspaceIntoRootfs loop-mounts the (resized) merged rootfs and the split+// workspace via qemu-nbd, grows the root ext4 to fill the image, then rsyncs the+// workspace's contents into /home/sandbox. Linux + qemu-nbd + root only.+func foldWorkspaceIntoRootfs(ctx context.Context, rootfsQcow2, workspaceQcow2 string) error {+ return runNBDScript(ctx, foldScript, rootfsQcow2, workspaceQcow2)+}++// growRootfsFilesystem grows the root ext4 to fill a resized image when there is+// no workspace to fold.+func growRootfsFilesystem(ctx context.Context, rootfsQcow2 string) error {+ return runNBDScript(ctx, growScript, rootfsQcow2)+}++func runNBDScript(ctx context.Context, script string, args ...string) error {+ cmdArgs := append([]string{"-c", script, "fold"}, args...)+ cmd := exec.CommandContext(ctx, "bash", cmdArgs...)+ if out, err := cmd.CombinedOutput(); err != nil {+ return fmt.Errorf("%w (%s)", err, strings.TrimSpace(string(out)))+ }+ return nil+}++// foldScript connects the rootfs (rw) and workspace (ro) via qemu-nbd, grows the+// root ext4, and copies workspace → /home/sandbox. $1=rootfs.qcow2 $2=workspace.qcow2+const foldScript = `+set -euo pipefail+ROOTFS="$1"; WS="$2"+modprobe nbd max_part=8 2>/dev/null || true+pick_nbd() {+ for i in $(seq 0 15); do+ if [ -e "/dev/nbd$i" ] && [ ! -s "/sys/block/nbd$i/pid" ]; then echo "/dev/nbd$i"; return 0; fi+ done+ return 1+}+NBD_ROOT=$(pick_nbd) || { echo "no free nbd device"; exit 1; }+qemu-nbd --connect="$NBD_ROOT" "$ROOTFS"+sleep 0.5+NBD_WS=$(pick_nbd) || { qemu-nbd --disconnect "$NBD_ROOT" 2>/dev/null || true; echo "no free nbd device (2)"; exit 1; }+qemu-nbd --connect="$NBD_WS" --read-only "$WS"+sleep 0.5+MNT_ROOT=$(mktemp -d); MNT_WS=$(mktemp -d)+cleanup() {+ umount "$MNT_WS" 2>/dev/null || true+ umount "$MNT_ROOT" 2>/dev/null || true+ qemu-nbd --disconnect "$NBD_WS" 2>/dev/null || true+ qemu-nbd --disconnect "$NBD_ROOT" 2>/dev/null || true+ rmdir "$MNT_ROOT" "$MNT_WS" 2>/dev/null || true+}+trap cleanup EXIT+e2fsck -fy "$NBD_ROOT" || true+resize2fs "$NBD_ROOT"+mount "$NBD_ROOT" "$MNT_ROOT"+mount -o ro "$NBD_WS" "$MNT_WS"+mkdir -p "$MNT_ROOT/home/sandbox"+rsync -aHAX --numeric-ids "$MNT_WS/" "$MNT_ROOT/home/sandbox/"+sync+`++// growScript connects the rootfs (rw) via qemu-nbd and grows the root ext4 to+// fill the resized image (no workspace to fold). $1=rootfs.qcow2+const growScript = `+set -euo pipefail+ROOTFS="$1"+modprobe nbd max_part=8 2>/dev/null || true+pick_nbd() {+ for i in $(seq 0 15); do+ if [ -e "/dev/nbd$i" ] && [ ! -s "/sys/block/nbd$i/pid" ]; then echo "/dev/nbd$i"; return 0; fi+ done+ return 1+}+NBD_ROOT=$(pick_nbd) || { echo "no free nbd device"; exit 1; }+qemu-nbd --connect="$NBD_ROOT" "$ROOTFS"+sleep 0.5+cleanup() { qemu-nbd --disconnect "$NBD_ROOT" 2>/dev/null || true; }+trap cleanup EXIT+e2fsck -fy "$NBD_ROOT" || true+resize2fs "$NBD_ROOT"+sync+`diff --git a/internal/qemu/disk_layout.go b/internal/qemu/disk_layout.gonew file mode 100644index 00000000..84565447--- /dev/null+++ b/internal/qemu/disk_layout.go@@ -0,0 +1,57 @@+package qemu++// DiskLayout describes how a sandbox's block storage is arranged. It is an+// immutable birth property of a box: chosen at create time and copied verbatim+// onto every derived resource (checkpoint inherits the sandbox's; a fork+// inherits the checkpoint's; a migration carries the source's). It is NEVER+// mutated in place — the disk topology is fixed at QEMU launch (the -drive set)+// and welded into every RAM snapshot, so a running/snapshotted box cannot change+// layout without being rebuilt.+//+// Two layouts coexist during the rollout (dual-mode workers understand both):+//+// - LayoutSplit (legacy): two disks — rootfs qcow2 overlay on the golden base+// mounted at "/", plus a separate workspace qcow2 (/dev/vdb) mounted at+// /home/sandbox. This is every box created before the merge.+// - LayoutMerged (new): one disk — a single qcow2 overlay on a 20GB golden base+// holding both the OS and /home/sandbox as a directory. No /dev/vdb.+//+// The zero value ("") means LayoutSplit: metadata written before this field+// existed, and any resource we haven't explicitly tagged, is a split box. Always+// route layout values through EffectiveDiskLayout so absent ⇒ split holds+// everywhere.+type DiskLayout = string++const (+ // LayoutSplit is the legacy two-disk topology (rootfs + workspace). It is+ // also the meaning of the empty string, for backward compatibility with+ // metadata that predates the DiskLayout field.+ LayoutSplit DiskLayout = "split"++ // LayoutMerged is the single-disk topology (OS + /home/sandbox on one disk).+ LayoutMerged DiskLayout = "merged"+)++// EffectiveDiskLayout normalizes a possibly-empty layout string to a concrete+// layout, applying the "absent ⇒ split" rule. Every branch on layout must go+// through this so that untagged (pre-merge) resources are treated as split.+func EffectiveDiskLayout(layout string) DiskLayout {+ if layout == LayoutMerged {+ return LayoutMerged+ }+ return LayoutSplit+}++// IsMerged reports whether the given (possibly-empty) layout is the merged+// single-disk topology.+func IsMerged(layout string) bool {+ return EffectiveDiskLayout(layout) == LayoutMerged+}++// boolToLayout maps a "merged?" bool to the corresponding layout constant.+func boolToLayout(merged bool) DiskLayout {+ if merged {+ return LayoutMerged+ }+ return LayoutSplit+}diff --git a/internal/qemu/disk_layout_test.go b/internal/qemu/disk_layout_test.gonew file mode 100644index 00000000..95f0c6aa--- /dev/null+++ b/internal/qemu/disk_layout_test.go@@ -0,0 +1,45 @@+package qemu++import "testing"++// The whole dual-mode rollout leans on "absent ⇒ split": any resource whose+// DiskLayout was never stamped (every box/checkpoint created before the merge)+// must be treated as the legacy two-disk layout. These tests pin that.+func TestEffectiveDiskLayout(t *testing.T) {+ cases := []struct {+ in string+ want DiskLayout+ }{+ {"", LayoutSplit}, // untagged (pre-merge) ⇒ split+ {"split", LayoutSplit}, // explicit split+ {"merged", LayoutMerged}, // explicit merged+ {"garbage", LayoutSplit}, // unknown value ⇒ split (fail safe)+ {"MERGED", LayoutSplit}, // case-sensitive: not the merged constant+ }+ for _, c := range cases {+ if got := EffectiveDiskLayout(c.in); got != c.want {+ t.Errorf("EffectiveDiskLayout(%q) = %q, want %q", c.in, got, c.want)+ }+ }+}++func TestIsMerged(t *testing.T) {+ if IsMerged("") {+ t.Error("IsMerged(\"\") = true, want false (absent ⇒ split)")+ }+ if IsMerged("split") {+ t.Error(`IsMerged("split") = true, want false`)+ }+ if !IsMerged("merged") {+ t.Error(`IsMerged("merged") = false, want true`)+ }+}++func TestBoolToLayout(t *testing.T) {+ if boolToLayout(true) != LayoutMerged {+ t.Errorf("boolToLayout(true) = %q, want %q", boolToLayout(true), LayoutMerged)+ }+ if boolToLayout(false) != LayoutSplit {+ t.Errorf("boolToLayout(false) = %q, want %q", boolToLayout(false), LayoutSplit)+ }+}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 8287043e..682a860d 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -268,6 +268,7 @@ type VMInstance struct {baseMemoryMB int // initial memory passed to -m (before virtio-mem)virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)goldenVersion string // golden version this sandbox was created from (empty if cold-booted)+ diskLayout string // block topology (see disk_layout.go); empty ⇒ split (legacy two-disk)// Set when this VM is started as a migration receiver (paused, -incoming) and// cleared once CompleteIncomingMigration resumes it. While set, the VM is a// not-yet-completed receiver: it's alive (so it passes vmAlive and would be@@ -344,6 +345,14 @@ type Config struct {DefaultDiskMB intDefaultPort int+ // GoldenLayout selects the block topology this worker builds its golden+ // with, and therefore the layout of every sandbox freshly created here+ // (see disk_layout.go). Empty ⇒ split (the legacy two-disk golden). Set to+ // LayoutMerged only after the whole fleet runs dual-mode code — this is the+ // Phase-3 merged-create flip. Forks/wakes of existing snapshots follow the+ // snapshot's own recorded layout regardless of this setting.+ GoldenLayout DiskLayout+// GlobalBlob is the abstract S3-compat backend (Tigris, R2, etc.) the// worker pulls canonical golden rootfs blobs from on cache miss.// Nil disables — worker falls back to local-only behavior (whatever@@ -373,6 +382,12 @@ type Manager struct {// same sandbox dir — racing on rootfs.qcow2 and contending for the host.wakeSF singleflight.Group+ // convertSF collapses concurrent convert-on-fork requests for the same+ // split checkpoint into a single conversion (see convert_merge.go), so+ // parallel forks of an un-migrated split template don't each rebuild the+ // merged variant.+ convertSF singleflight.Group+// Checkpoint cache mutex: write-locked during cache creation, read-locked during forkcheckpointCacheMu sync.RWMutex@@ -382,6 +397,7 @@ type Manager struct {goldenGuestIP string // guest IP baked into the golden snapshotgoldenHostIP string // host IP of the golden subnet (for temp addr on TAP)goldenVersion string // hash of base image — used for overlay-based migration+ goldenLayout string // block topology the golden was built with (see disk_layout.go); empty ⇒ split// Metadata service callbacks (set via SetMetadataCallbacks)onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)@@ -826,6 +842,13 @@ func (m *Manager) PrepareGoldenSnapshot() error {storedVersion = string(vBytes)}+ // Load stored golden layout (empty file / absent ⇒ split, for goldens+ // built before the DiskLayout field existed).+ var storedLayout string+ if lBytes, err := os.ReadFile(filepath.Join(goldenDir, "layout")); err == nil {+ storedLayout = string(lBytes)+ }+// Check if the base image on disk matches the golden snapshotstale := falsebaseImage, _ := ResolveBaseImage(m.cfg.ImagesDir, "default")@@ -836,9 +859,19 @@ func (m *Manager) PrepareGoldenSnapshot() error {}}+ // A flag-flip of GoldenLayout must rebuild: the on-disk golden's topology+ // (and its RAM snapshot's device model) can't be reinterpreted as the+ // other layout.+ if EffectiveDiskLayout(storedLayout) != EffectiveDiskLayout(m.cfg.GoldenLayout) {+ log.Printf("qemu: golden layout changed (golden=%s, configured=%s), rebuilding golden snapshot",+ EffectiveDiskLayout(storedLayout), EffectiveDiskLayout(m.cfg.GoldenLayout))+ stale = true+ }+if !stale {m.goldenDir = goldenDirm.goldenVersion = storedVersion+ m.goldenLayout = EffectiveDiskLayout(storedLayout)if cidBytes, err := os.ReadFile(filepath.Join(goldenDir, "cid")); err == nil {fmt.Sscanf(string(cidBytes), "%d", &m.goldenCID)}@@ -884,20 +917,29 @@ func (m *Manager) PrepareGoldenSnapshot() error {return fmt.Errorf("prepare golden rootfs: %w", err)}- // Create workspace as qcow2 — must match DefaultDiskMB so the virtio-blk- // device geometry in the golden migration state matches sandbox workspaces.- workspaceFile := filepath.Join(goldenDir, "workspace.qcow2")- if err := CreateWorkspace(workspaceFile, m.cfg.DefaultDiskMB); err != nil {- return fmt.Errorf("create golden workspace: %w", err)- }+ goldenLayout := EffectiveDiskLayout(m.cfg.GoldenLayout)++ // Split layout: create a separate workspace disk (vdb) for the golden boot,+ // sized to DefaultDiskMB so the virtio-blk device geometry in the golden+ // migration state matches sandbox workspaces. Merged layout: no workspace+ // disk — /home/sandbox is a directory on the rootfs, so the golden boots+ // with a single drive and workspaceFile stays "".+ var workspaceFile string+ if goldenLayout == LayoutSplit {+ workspaceFile = filepath.Join(goldenDir, "workspace.qcow2")+ if err := CreateWorkspace(workspaceFile, m.cfg.DefaultDiskMB); err != nil {+ return fmt.Errorf("create golden workspace: %w", err)+ }- // Save the workspace ext4 UUID so createFromGolden can stamp new workspaces- // with the same UUID. The golden kernel caches ext4 metadata (superblock,- // journal) by UUID — a new workspace with a different UUID triggers checksum- // errors ("Bad message" / EBADMSG) because the cached metadata doesn't match.- if wsUUID, uuidErr := getWorkspaceUUID(workspaceFile); uuidErr == nil {- os.WriteFile(filepath.Join(goldenDir, "workspace_uuid"), []byte(wsUUID), 0644)- log.Printf("qemu: golden: workspace UUID=%s", wsUUID)+ // Save the workspace ext4 UUID so createFromGolden can stamp new+ // workspaces with the same UUID. The golden kernel caches ext4 metadata+ // (superblock, journal) by UUID — a new workspace with a different UUID+ // triggers checksum errors ("Bad message" / EBADMSG) because the cached+ // metadata doesn't match.+ if wsUUID, uuidErr := getWorkspaceUUID(workspaceFile); uuidErr == nil {+ os.WriteFile(filepath.Join(goldenDir, "workspace_uuid"), []byte(wsUUID), 0644)+ log.Printf("qemu: golden: workspace UUID=%s", wsUUID)+ }}// Allocate a temporary network for golden boot@@ -989,21 +1031,25 @@ func (m *Manager) PrepareGoldenSnapshot() error {}log.Printf("qemu: golden: virtio_mem module loaded")- // Unmount /home/sandbox and sync before snapshot — the golden migration state- // includes virtio-blk device state (ring buffers, pending I/O). If the data disk- // is mounted when we snapshot, those stale I/O ops will corrupt any fresh- // workspace.qcow2 that createFromGolden boots with.- umountCtx, umountCancel := context.WithTimeout(context.Background(), 10*time.Second)- _, umountErr := agentClient.Exec(umountCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "umount -f /home/sandbox 2>/dev/null; sync; echo 3 > /proc/sys/vm/drop_caches; echo 3 > /proc/sys/vm/drop_caches; blockdev --flushbufs /dev/vdb 2>/dev/null; true"},- RunAsRoot: true,- })- umountCancel()- if umountErr != nil {- log.Printf("qemu: golden: umount /home/sandbox failed (non-fatal): %v", umountErr)- } else {- log.Printf("qemu: golden: /home/sandbox unmounted and synced")+ // Split layout only: unmount /home/sandbox and sync before snapshot — the+ // golden migration state includes virtio-blk device state (ring buffers,+ // pending I/O). If the data disk is mounted when we snapshot, those stale+ // I/O ops will corrupt any fresh workspace.qcow2 that createFromGolden boots+ // with. In the merged layout /home/sandbox is a directory on the rootfs+ // (no vdb), so there is nothing to unmount — the fsfreeze / below covers it.+ if goldenLayout == LayoutSplit {+ umountCtx, umountCancel := context.WithTimeout(context.Background(), 10*time.Second)+ _, umountErr := agentClient.Exec(umountCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "umount -f /home/sandbox 2>/dev/null; sync; echo 3 > /proc/sys/vm/drop_caches; echo 3 > /proc/sys/vm/drop_caches; blockdev --flushbufs /dev/vdb 2>/dev/null; true"},+ RunAsRoot: true,+ })+ umountCancel()+ if umountErr != nil {+ log.Printf("qemu: golden: umount /home/sandbox failed (non-fatal): %v", umountErr)+ } else {+ log.Printf("qemu: golden: /home/sandbox unmounted and synced")+ }}// Freeze the rootfs before the snapshot so the golden RAM's ext4 metadata is@@ -1029,6 +1075,32 @@ func (m *Manager) PrepareGoldenSnapshot() error {log.Printf("qemu: golden: rootfs frozen for consistent snapshot")}+ // Reset the agent's virtio-serial listener before the snapshot (exactly as+ // the hibernate/checkpoint path does via prepareAgentForHibernate). This+ // captures the listener with active=false, so createFromGolden's fresh host+ // connection gets a clean Accept on restore.+ //+ // Without this the golden build only closes the host side of the connection+ // and sleeps 500ms — but virtio-serial doesn't reliably signal disconnect to+ // the guest, so the listener's `active` flag is captured nondeterministically.+ // When a golden happens to capture active=true, EVERY box restored from it+ // spins in the agent's Accept() loop (100ms poll) until the stale connection+ // is detected — the guest agent doesn't answer pings for several seconds even+ // though VM-resume finished in ~270ms. This surfaced as per-worker "agent+ // ready in 4-8s vs 0.3s" variance that had nothing to do with the box; it was+ // purely which listener state that worker's golden captured. SIGUSR1 fallback+ // for older agents. See cmd/agent/listen_linux.go Accept().+ phCtx, phCancel := context.WithTimeout(context.Background(), 10*time.Second)+ if _, phErr := agentClient.PrepareHibernate(phCtx, &pb.PrepareHibernateRequest{}); phErr != nil {+ log.Printf("qemu: golden: PrepareHibernate listener reset failed (%v) — SIGUSR1 fallback", phErr)+ fbCtx, fbCancel := context.WithTimeout(context.Background(), 5*time.Second)+ _, _ = agentClient.Exec(fbCtx, &pb.ExecRequest{Command: "/bin/sh", Args: []string{"-c", "kill -USR1 1"}, RunAsRoot: true})+ fbCancel()+ } else {+ log.Printf("qemu: golden: agent virtio-serial listener reset for clean restore")+ }+ phCancel()+// Close agent connection before migration. Use a timeout because gRPC's// graceful close over vsock can hang if vhost-vsock doesn't drain cleanly.closeDone := make(chan struct{})@@ -1078,8 +1150,10 @@ func (m *Manager) PrepareGoldenSnapshot() error {<-done}- // Clean up temp files- os.Remove(workspaceFile)+ // Clean up temp files (workspaceFile is "" in the merged layout)+ if workspaceFile != "" {+ os.Remove(workspaceFile)+ }os.Remove(qmpSockPath)// Compress golden mem with zstd — on EBS volumes, reading less data from disk@@ -1097,6 +1171,12 @@ func (m *Manager) PrepareGoldenSnapshot() error {_ = os.WriteFile(filepath.Join(goldenDir, "version"), []byte(v), 0644)}+ // Persist the golden's disk layout so createFromGolden and the restart-reuse+ // path stamp new sandboxes with the right topology (and so a later flag-flip+ // is detected as stale).+ m.goldenLayout = goldenLayout+ _ = os.WriteFile(filepath.Join(goldenDir, "layout"), []byte(goldenLayout), 0644)+// Remove preparing marker — golden snapshot is completeos.Remove(preparingMarker)@@ -1181,33 +1261,63 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,return nil, fmt.Errorf("copy golden rootfs: %w", err)}- // Create fresh workspace as qcow2 with the golden's ext4 UUID.- // The golden kernel caches ext4 metadata by UUID — mismatched UUIDs cause- // "Bad message" (EBADMSG) checksum errors on the restored workspace.- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")- diskMB := m.cfg.DefaultDiskMB- var goldenWSUUID string- if data, readErr := os.ReadFile(filepath.Join(m.goldenDir, "workspace_uuid")); readErr == nil {- goldenWSUUID = strings.TrimSpace(string(data))- }- if err := CreateWorkspace(workspacePath, diskMB, goldenWSUUID); err != nil {- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("create workspace: %w", err)- }-- // Resize workspace if requested size exceeds default (golden geometry)- requestedDiskMB := cfg.DiskMB- if requestedDiskMB <= 0 {- requestedDiskMB = m.cfg.DefaultDiskMB- }- if requestedDiskMB > diskMB {- if err := ResizeWorkspace(workspacePath, requestedDiskMB); err != nil {+ // Workspace disk (vdb) exists only in the split layout. In the merged layout+ // /home/sandbox is a directory on the rootfs, so workspacePath stays "" and+ // buildQEMUArgs emits a single drive.+ var workspacePath string+ // >0 when the workspace qcow2 was grown past the golden geometry before+ // launch — drives the post-launch QMP block_resize below (split only).+ var workspaceResizedToMB int+ // >0 when the merged rootfs overlay was grown past the golden base size —+ // drives the post-restore rootfs block_resize + online resize2fs / below.+ var rootfsResizedToMB int+ if m.goldenLayout == LayoutSplit {+ // Create fresh workspace as qcow2 with the golden's ext4 UUID.+ // The golden kernel caches ext4 metadata by UUID — mismatched UUIDs cause+ // "Bad message" (EBADMSG) checksum errors on the restored workspace.+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ diskMB := m.cfg.DefaultDiskMB+ var goldenWSUUID string+ if data, readErr := os.ReadFile(filepath.Join(m.goldenDir, "workspace_uuid")); readErr == nil {+ goldenWSUUID = strings.TrimSpace(string(data))+ }+ if err := CreateWorkspace(workspacePath, diskMB, goldenWSUUID); err != nil {os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("resize workspace: %w", err)+ return nil, fmt.Errorf("create workspace: %w", err)+ }++ // Resize workspace if requested size exceeds default (golden geometry)+ requestedDiskMB := cfg.DiskMB+ if requestedDiskMB <= 0 {+ requestedDiskMB = m.cfg.DefaultDiskMB+ }+ if requestedDiskMB > diskMB {+ if err := ResizeWorkspace(workspacePath, requestedDiskMB); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("resize workspace: %w", err)+ }+ workspaceResizedToMB = requestedDiskMB}- }- log.Printf("qemu: golden-create %s: rootfs+workspace ready (%dms)", id, time.Since(t0).Milliseconds())+ log.Printf("qemu: golden-create %s: rootfs+workspace ready (%dms)", id, time.Since(t0).Milliseconds())+ } else {+ // Merged layout: single disk, no workspace. To exceed the golden base+ // size (DefaultDiskMB), grow the rootfs overlay now — the virtual region+ // past the backing reads as zeros — then online-resize2fs / after the+ // guest resumes (block_resize section below).+ requestedDiskMB := cfg.DiskMB+ if requestedDiskMB <= 0 {+ requestedDiskMB = m.cfg.DefaultDiskMB+ }+ if requestedDiskMB > m.cfg.DefaultDiskMB {+ if err := ResizeWorkspace(rootfsPath, requestedDiskMB); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("resize merged rootfs: %w", err)+ }+ rootfsResizedToMB = requestedDiskMB+ }+ log.Printf("qemu: golden-create %s: rootfs ready (merged, %dms)", id, time.Since(t0).Milliseconds())+ }// Allocate networknetCfg, err := m.subnets.Allocate()@@ -1366,6 +1476,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,guestCID: guestCID,bootArgs: bootArgs,goldenVersion: m.goldenVersion,+ diskLayout: m.goldenLayout,}// Connect to agent via Unix socket@@ -1392,9 +1503,10 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,// If we resized the workspace qcow2 before launch, notify QEMU via QMP// block_resize so virtio-blk fires a capacity-change event to the guest.// Without this, the guest kernel still sees the golden-snapshot-captured- // 20GB geometry even though the backing file is larger.- if requestedDiskMB > diskMB {- newSizeBytes := int64(requestedDiskMB) * 1024 * 1024+ // 20GB geometry even though the backing file is larger. (Split only —+ // workspaceResizedToMB stays 0 in the merged layout.)+ if workspaceResizedToMB > 0 {+ newSizeBytes := int64(workspaceResizedToMB) * 1024 * 1024devs, qbErr := qmpClient.QueryBlock()if qbErr != nil {log.Printf("qemu: golden-create %s: query-block failed: %v", id, qbErr)@@ -1411,7 +1523,44 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,} else if err := qmpClient.BlockResize(devID, newSizeBytes); err != nil {log.Printf("qemu: golden-create %s: block_resize failed: %v", id, err)} else {- log.Printf("qemu: golden-create %s: block_resize %s → %dMB", id, devID, requestedDiskMB)+ log.Printf("qemu: golden-create %s: block_resize %s → %dMB", id, devID, workspaceResizedToMB)+ }+ }+ }++ // Merged layout: the rootfs overlay was grown past the base before launch.+ // Notify QEMU (block_resize on the rootfs device) so the guest sees the+ // larger vda, then online-grow the root ext4 to fill it.+ if rootfsResizedToMB > 0 {+ newSizeBytes := int64(rootfsResizedToMB) * 1024 * 1024+ devs, qbErr := qmpClient.QueryBlock()+ if qbErr != nil {+ log.Printf("qemu: golden-create %s: query-block failed (merged resize): %v", id, qbErr)+ } else {+ var devID string+ for _, d := range devs {+ if d.Inserted.File == rootfsPath {+ devID = d.Device+ break+ }+ }+ if devID == "" {+ log.Printf("qemu: golden-create %s: rootfs device not found in query-block (merged resize)", id)+ } else if err := qmpClient.BlockResize(devID, newSizeBytes); err != nil {+ log.Printf("qemu: golden-create %s: block_resize rootfs failed: %v", id, err)+ } else {+ rCtx, rCancel := context.WithTimeout(context.Background(), 20*time.Second)+ _, rErr := agentClient.Exec(rCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "resize2fs /dev/vda 2>/dev/null || resize2fs /dev/vda1 2>/dev/null || true"},+ RunAsRoot: true,+ })+ rCancel()+ if rErr != nil {+ log.Printf("qemu: golden-create %s: resize2fs / failed: %v", id, rErr)+ } else {+ log.Printf("qemu: golden-create %s: merged rootfs grown to %dMB", id, rootfsResizedToMB)+ }}}}@@ -1426,12 +1575,13 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,log.Printf("qemu: golden-create %s: clock sync failed: %v", id, err)}- // Mount /home/sandbox — the data disk is mounted directly as the user's home.- // The golden snapshot was taken with it unmounted to keep vdb device state clean.- // Drop caches first: the golden VM's kernel has cached ext4 metadata from the- // golden workspace. The new sandbox has a DIFFERENT workspace qcow2 on the same- // virtio-blk device. Without dropping caches, the kernel uses stale superblock/- // journal data → ext4 checksum errors ("Bad message").+ // Split layout only: mount /home/sandbox — the data disk (vdb) is mounted+ // directly as the user's home. The golden snapshot was taken with it+ // unmounted to keep vdb device state clean. Drop caches first: the golden+ // VM's kernel has cached ext4 metadata from the golden workspace. The new+ // sandbox has a DIFFERENT workspace qcow2 on the same virtio-blk device.+ // Without dropping caches, the kernel uses stale superblock/journal data →+ // ext4 checksum errors ("Bad message").//// After /home/sandbox is mounted, redirect /var/cache/apt/archives onto// workspace via bind-mount. apt downloads packages there before installing@@ -1440,23 +1590,30 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,// (mountpoint -q short-circuits) and survives only in the running kernel —// re-applied on every wake/spawn through this same hook. Failure to bind-// mount is non-fatal (apt-cache stays on rootfs, status quo).- mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)- _, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", strings.Join([]string{- "echo 3 > /proc/sys/vm/drop_caches",- "echo 3 > /proc/sys/vm/drop_caches",- "mount /dev/vdb /home/sandbox 2>/dev/null || true",- "resize2fs /dev/vdb 2>/dev/null || true",- "chown 1000:1000 /home/sandbox",- "mkdir -p /home/sandbox/.osb-apt-cache /var/cache/apt/archives",- "mountpoint -q /var/cache/apt/archives || mount --bind /home/sandbox/.osb-apt-cache /var/cache/apt/archives 2>/dev/null || true",- }, " && ")},- RunAsRoot: true,- })- mountCancel()- if mountErr != nil {- log.Printf("qemu: golden-create %s: mount /home/sandbox failed: %v", id, mountErr)+ //+ // Merged layout skips all of this: /home/sandbox is a directory on the 20GB+ // rootfs (already owned by the sandbox user in the base), there is no second+ // disk to swap/drop-caches for, and apt can write straight to the roomy+ // rootfs so no bind-mount is needed.+ if m.goldenLayout == LayoutSplit {+ mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)+ _, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", strings.Join([]string{+ "echo 3 > /proc/sys/vm/drop_caches",+ "echo 3 > /proc/sys/vm/drop_caches",+ "mount /dev/vdb /home/sandbox 2>/dev/null || true",+ "resize2fs /dev/vdb 2>/dev/null || true",+ "chown 1000:1000 /home/sandbox",+ "mkdir -p /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ "mountpoint -q /var/cache/apt/archives || mount --bind /home/sandbox/.osb-apt-cache /var/cache/apt/archives 2>/dev/null || true",+ }, " && ")},+ RunAsRoot: true,+ })+ mountCancel()+ if mountErr != nil {+ log.Printf("qemu: golden-create %s: mount /home/sandbox failed: %v", id, mountErr)+ }}log.Printf("qemu: golden-create %s: network patched (%dms)", id, time.Since(t0).Milliseconds())@@ -1661,6 +1818,13 @@ func (m *Manager) allocateCID() uint32 {// buildQEMUArgs constructs the QEMU command-line arguments.// agentSock is the Unix socket path for the virtio-serial agent channel.+// buildQEMUArgs assembles the QEMU command line. The disk topology is driven by+// workspacePath: a non-empty path yields the legacy two-disk layout (rootfs+// vda + workspace vdb); an EMPTY workspacePath yields the merged single-disk+// layout (rootfs vda only, with /home/sandbox as a directory on it). The device+// order and IDs are otherwise identical, so a snapshot's -drive set must be+// reconstructed with the same workspacePath-empty-ness it was captured with, or+// an incoming RAM migration will fail on device-model mismatch.func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapName, mac, agentSock, qmpSock, bootArgs string) []string {// Detect drive format from file extensionrootfsFmt := "qcow2"@@ -1681,7 +1845,7 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN}maxMemMB := memMB + virtioMemPoolMB- return []string{+ args := []string{"-machine", "q35,accel=kvm","-cpu", "host","-m", fmt.Sprintf("%dM,slots=1,maxmem=%dM", memMB, maxMemMB),@@ -1692,7 +1856,14 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN"-kernel", m.cfg.KernelPath,"-append", bootArgs,"-drive", fmt.Sprintf("file=%s,format=%s,if=virtio,cache=writethrough", rootfsPath, rootfsFmt),- "-drive", fmt.Sprintf("file=%s,format=%s,if=virtio,cache=writethrough", workspacePath, wsFmt),+ }+ // Workspace (vdb) drive only in the split layout. An empty workspacePath is+ // the merged single-disk layout — /home/sandbox lives on the rootfs disk.+ if workspacePath != "" {+ args = append(args,+ "-drive", fmt.Sprintf("file=%s,format=%s,if=virtio,cache=writethrough", workspacePath, wsFmt))+ }+ args = append(args,"-netdev", fmt.Sprintf("tap,id=net0,ifname=%s,script=no,downscript=no", tapName),"-device", fmt.Sprintf("virtio-net-pci,netdev=net0,mac=%s", mac),// Agent communication via virtio-serial (survives QEMU migration,@@ -1704,7 +1875,8 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN"-nographic","-nodefaults","-serial", "stdio",- }+ )+ return args}// Create launches a new QEMU VM.@@ -1749,21 +1921,32 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type}rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")+ // workspacePath stays "" in the merged single-disk layout (see disk_layout.go),+ // which makes buildQEMUArgs emit a single drive.+ var workspacePath string+ var coldMerged boolif cfg.TemplateRootfsKey != "" {+ // Template cold-boot: layout follows the template. An empty+ // TemplateWorkspaceKey marks a merged (single-disk) template.+ coldMerged = cfg.TemplateWorkspaceKey == ""srcRootfs := strings.TrimPrefix(cfg.TemplateRootfsKey, "local://")- srcWorkspace := strings.TrimPrefix(cfg.TemplateWorkspaceKey, "local://")- log.Printf("qemu: create %s from snapshot template (rootfs=%s, workspace=%s)", id, srcRootfs, srcWorkspace)+ log.Printf("qemu: create %s from snapshot template (rootfs=%s, workspace=%q, merged=%v)", id, srcRootfs, cfg.TemplateWorkspaceKey, coldMerged)if err := copyFileReflink(srcRootfs, rootfsPath); err != nil {os.RemoveAll(sandboxDir)return nil, fmt.Errorf("copy template rootfs: %w", err)}- if err := copyFileReflink(srcWorkspace, workspacePath); err != nil {- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("copy template workspace: %w", err)+ if !coldMerged {+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ srcWorkspace := strings.TrimPrefix(cfg.TemplateWorkspaceKey, "local://")+ if err := copyFileReflink(srcWorkspace, workspacePath); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("copy template workspace: %w", err)+ }}} else {+ // Base cold-boot fallback: layout follows the worker's configured golden.+ coldMerged = IsMerged(m.cfg.GoldenLayout)baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)if err != nil {os.RemoveAll(sandboxDir)@@ -1774,13 +1957,16 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *typereturn nil, fmt.Errorf("prepare rootfs: %w", err)}- diskMB := cfg.DiskMB- if diskMB <= 0 {- diskMB = m.cfg.DefaultDiskMB- }- if err := CreateWorkspace(workspacePath, diskMB); err != nil {- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("create workspace: %w", err)+ if !coldMerged {+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ diskMB := cfg.DiskMB+ if diskMB <= 0 {+ diskMB = m.cfg.DefaultDiskMB+ }+ if err := CreateWorkspace(workspacePath, diskMB); err != nil {+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("create workspace: %w", err)+ }}}@@ -1907,6 +2093,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *typeguestCID: guestCID,bootArgs: bootArgs,goldenVersion: m.goldenVersion, // set even on cold boot — VM uses the same base image+ diskLayout: boolToLayout(coldMerged),}// Wait for agent via Unix socket. Default 30s; callers can extend it (the@@ -3011,10 +3198,17 @@ func (m *Manager) CreateCheckpointFinalized(ctx context.Context, buildSandboxID,log.Printf("qemu: finalize %s: SyncFS warning: %v (continuing)", buildSandboxID, syncErr)}+ // The build sandbox's layout drives whether there's a workspace disk to+ // finalize from. Merged builds have a single rootfs disk.+ buildMerged := false+ if bvm, gerr := m.getVM(buildSandboxID); gerr == nil {+ buildMerged = IsMerged(bvm.diskLayout)+ }+buildDir := filepath.Join(m.cfg.DataDir, "sandboxes", buildSandboxID)buildRootfs := filepath.Join(buildDir, "rootfs.qcow2")buildWorkspace := filepath.Join(buildDir, "workspace.qcow2")- if !fileExists(buildRootfs) || !fileExists(buildWorkspace) {+ if !fileExists(buildRootfs) || (!buildMerged && !fileExists(buildWorkspace)) {return "", "", 0, fmt.Errorf("finalize: build disks not found for %s", buildSandboxID)}@@ -3036,17 +3230,21 @@ func (m *Manager) CreateCheckpointFinalized(ctx context.Context, buildSandboxID,finalizeID := buildSandboxID + "-fin"netEnabled := truefinCfg := types.SandboxConfig{- SandboxID: finalizeID,- MemoryMB: finalizeMemMB,- NetworkEnabled: &netEnabled,- TemplateRootfsKey: "local://" + buildRootfs,- TemplateWorkspaceKey: "local://" + buildWorkspace,+ SandboxID: finalizeID,+ MemoryMB: finalizeMemMB,+ NetworkEnabled: &netEnabled,+ TemplateRootfsKey: "local://" + buildRootfs,// A heavy user-built rootfs (many apt/npm layers) can legitimately take// longer than a stock base to reach agent-ready on cold boot. Give the// finalize bring-up generous headroom so we don't fail a correct image// on the default 30s wait.AgentReadyTimeout: finalizeAgentReadyTimeout,}+ // Merged builds have no workspace disk — an empty TemplateWorkspaceKey tells+ // Create() to cold-boot the finalize VM as a single-disk (merged) sandbox.+ if !buildMerged {+ finCfg.TemplateWorkspaceKey = "local://" + buildWorkspace+ }log.Printf("qemu: finalize: cold-booting %s from %s disks at %dMB", finalizeID, buildSandboxID, finalizeMemMB)if _, err := m.Create(ctx, finCfg); err != nil {return "", "", 0, fmt.Errorf("finalize: cold-boot at %dMB: %w", finalizeMemMB, err)@@ -3236,17 +3434,21 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// 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.+ merged := IsMerged(vm.diskLayout)srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.qcow2")- srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")if err := copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2")); err != nil {os.RemoveAll(stagingDir)failureReason = "qcow2_copy"return "", "", 0, fmt.Errorf("copy rootfs: %w", err)}- if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {- os.RemoveAll(stagingDir)- failureReason = "qcow2_copy"- return "", "", 0, fmt.Errorf("copy workspace: %w", err)+ // Merged layout has no workspace disk — /home/sandbox lives on the rootfs.+ if !merged {+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")+ if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {+ os.RemoveAll(stagingDir)+ failureReason = "qcow2_copy"+ return "", "", 0, fmt.Errorf("copy workspace: %w", err)+ }}// Record the savevm snapshot name so ForkFromCheckpoint / RestoreFromCheckpoint// know which internal snapshot to loadvm.@@ -3287,7 +3489,9 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// Write metadata and finalize cache.rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)- workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)+ if !merged {+ workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)+ }meta := &SnapshotMeta{SandboxID: vm.ID,@@ -3301,6 +3505,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDTemplate: vm.Template,GuestPort: vm.GuestPort,GoldenVersion: vm.goldenVersion,+ DiskLayout: vm.diskLayout,SnapshotedAt: time.Now(),}// Persist secrets proxy state so RestoreFromCheckpoint can re-register the session.@@ -3341,7 +3546,10 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// state inside the qcow2 drives and record the snapshot name; migrate-// based legacy checkpoints (from older builds) also include a mem file.var archiveFiles []string- archiveFiles = append(archiveFiles, "rootfs.qcow2", "workspace.qcow2")+ archiveFiles = append(archiveFiles, "rootfs.qcow2")+ if !merged {+ archiveFiles = append(archiveFiles, "workspace.qcow2")+ }if fileExists(filepath.Join(cacheDir, "snapshot-name")) {archiveFiles = append(archiveFiles, "snapshot-name")}@@ -3470,15 +3678,19 @@ func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, check}stopped = true+ merged := IsMerged(vm.diskLayout)srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.qcow2")- srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")if err := copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2")); err != nil {failureReason = "qcow2_copy"return "", "", 0, fmt.Errorf("copy rootfs: %w", err)}- if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {- failureReason = "qcow2_copy"- return "", "", 0, fmt.Errorf("copy workspace: %w", err)+ // Merged layout has no workspace disk — /home/sandbox lives on the rootfs.+ if !merged {+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")+ if err := copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2")); err != nil {+ failureReason = "qcow2_copy"+ return "", "", 0, fmt.Errorf("copy workspace: %w", err)+ }}if contErr := vm.qmp.Cont(); contErr != nil {log.Printf("qemu: DiskOnlyCheckpoint %s/%s: failed to resume VM after copy: %v", sandboxID, checkpointID, contErr)@@ -3489,7 +3701,9 @@ func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkfrozen = falserootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)- workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)+ if !merged {+ workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)+ }meta := &SnapshotMeta{SandboxID: vm.ID,Network: vm.network,@@ -3502,6 +3716,7 @@ func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkTemplate: vm.Template,GuestPort: vm.GuestPort,GoldenVersion: vm.goldenVersion,+ DiskLayout: vm.diskLayout,SnapshotedAt: time.Now(),}if m.secretsProxy != nil && vm.network != nil {@@ -3523,7 +3738,11 @@ func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checklog.Printf("qemu: disk-only checkpoint %s: cache saved (%dms)", checkpointID, time.Since(t0).Milliseconds())if checkpointStore != nil {- archiveFiles := []string{"rootfs.qcow2", "workspace.qcow2", filepath.Join("snapshot", "snapshot-meta.json")}+ archiveFiles := []string{"rootfs.qcow2"}+ if !merged {+ archiveFiles = append(archiveFiles, "workspace.qcow2")+ }+ archiveFiles = append(archiveFiles, filepath.Join("snapshot", "snapshot-meta.json"))archivePath := filepath.Join(cacheDir, "checkpoint.tar.zst")if archErr := createArchive(archivePath, cacheDir, archiveFiles); archErr != nil {failureReason = "archive"@@ -3604,18 +3823,21 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi// Step 3: Copy fresh qcow2 drives from checkpoint cachem.checkpointCacheMu.RLock()cacheDir := m.checkpointCacheDir(checkpointID)- cachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")- cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")- if !fileExists(cachedRootfs) || !fileExists(cachedWorkspace) {- m.checkpointCacheMu.RUnlock()- return fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)- }- // Read checkpoint metadata for base topology.+ // Read checkpoint metadata for base topology + disk layout.var cpMeta SnapshotMetaif metaData, err := os.ReadFile(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")); err == nil {json.Unmarshal(metaData, &cpMeta)}+ merged := IsMerged(cpMeta.DiskLayout)++ cachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")+ // Merged checkpoints have only a rootfs qcow2; split checkpoints have both.+ if !fileExists(cachedRootfs) || (!merged && !fileExists(cachedWorkspace)) {+ m.checkpointCacheMu.RUnlock()+ return fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)+ }// Determine restore mode: prefer migration-based (-incoming) over savevm (loadvm).// CreateCheckpoint uses QEMU migrate which produces a standalone mem dump file.@@ -3639,18 +3861,23 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoisandboxDir := vm.sandboxDirrootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")+ // workspacePath stays "" for merged so buildQEMUArgs reconstructs the+ // single-disk device model the checkpoint's savevm state was captured with.+ var workspacePath string// Remove old drives and copy fresh onesos.Remove(rootfsPath)- os.Remove(workspacePath)+ os.Remove(filepath.Join(sandboxDir, "workspace.qcow2"))if err := copyFileReflink(cachedRootfs, rootfsPath); err != nil {m.checkpointCacheMu.RUnlock()return fmt.Errorf("copy rootfs from cache: %w", err)}- if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {- m.checkpointCacheMu.RUnlock()- return fmt.Errorf("copy workspace from cache: %w", err)+ if !merged {+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {+ m.checkpointCacheMu.RUnlock()+ return fmt.Errorf("copy workspace from cache: %w", err)+ }}m.checkpointCacheMu.RUnlock()@@ -3871,6 +4098,17 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoifunc (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {t0 := time.Now()+ // Convert-on-fork: on a merged worker, a fork of a legacy split disk_only+ // checkpoint is transparently served from a memoized MERGED variant, so+ // forks of pre-merge templates come out as single-disk boxes too. Returns+ // "" (fork the original as-is) for already-merged, RAM-bearing, or split-+ // worker cases. See convert_merge.go.+ if mergedID, err := m.maybeConvertToMergedVariant(ctx, checkpointID); err != nil {+ return nil, err+ } else if mergedID != "" {+ checkpointID = mergedID+ }+// Ensure checkpoint is compatible with current base image — rebases inline if needed.// Return the error so we don't silently fork a stale checkpoint against the wrong base.if err := m.ensureCheckpointRebased(ctx, checkpointID); err != nil {@@ -3882,18 +4120,20 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, ccacheDir := m.checkpointCacheDir(checkpointID)metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")+ var meta SnapshotMeta+ if data, err := os.ReadFile(metaPath); err == nil {+ json.Unmarshal(data, &meta)+ }+ merged := IsMerged(meta.DiskLayout)+cachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")- if !fileExists(cachedRootfs) || !fileExists(cachedWorkspace) {+ // Merged checkpoints have only a rootfs qcow2; split checkpoints have both.+ if !fileExists(cachedRootfs) || (!merged && !fileExists(cachedWorkspace)) {m.checkpointCacheMu.RUnlock()return nil, fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)}- var meta SnapshotMeta- if data, err := os.ReadFile(metaPath); err == nil {- json.Unmarshal(data, &meta)- }-id := cfg.SandboxIDif id == "" {id = "sb-" + uuid.New().String()[:8]@@ -3904,18 +4144,23 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, creturn nil, fmt.Errorf("mkdir sandbox dir: %w", err)}- // Copy qcow2 drives (contain snapshot data)+ // Copy qcow2 drives (contain snapshot data). Merged forks have only a rootfs;+ // workspacePath stays "" so the reconstructed QEMU matches the single-disk+ // device model the checkpoint's savevm state was captured with.rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")+ var workspacePath stringif err := copyFileReflink(cachedRootfs, rootfsPath); err != nil {m.checkpointCacheMu.RUnlock()os.RemoveAll(sandboxDir)return nil, fmt.Errorf("copy rootfs: %w", err)}- if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {- m.checkpointCacheMu.RUnlock()- os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("copy workspace: %w", err)+ if !merged {+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {+ m.checkpointCacheMu.RUnlock()+ os.RemoveAll(sandboxDir)+ return nil, fmt.Errorf("copy workspace: %w", err)+ }}m.checkpointCacheMu.RUnlock()@@ -4313,6 +4558,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cbootArgs: bootArgs,agent: agent,goldenVersion: forkGolden,+ diskLayout: EffectiveDiskLayout(meta.DiskLayout),}m.mu.Lock()@@ -4477,6 +4723,11 @@ func (m *Manager) GetWorkspacePath(sandboxID string) (string, error) {if err != nil {return "", err}+ // Merged boxes have no workspace disk — data lives on the rootfs, so gate+ // the autosave mtime check on rootfs.qcow2 instead.+ if IsMerged(vm.diskLayout) {+ return filepath.Join(vm.sandboxDir, "rootfs.qcow2"), nil+ }return filepath.Join(vm.sandboxDir, "workspace.qcow2"), nil}diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex a380e260..87e903e3 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -86,8 +86,8 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strin}sandboxDir := vm.sandboxDir+ merged := IsMerged(vm.diskLayout)rootfsPath := detectDrivePath(sandboxDir, "rootfs")- workspacePath := detectDrivePath(sandboxDir, "workspace")stagingDir, stageErr := os.MkdirTemp(mc.manager.cfg.DataDir, "migration-staging-")if stageErr != nil {@@ -96,25 +96,45 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strin}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)+ // Merged sandboxes have no workspace disk — an empty workspaceKey is the+ // signal the target uses to reconstruct a single-disk incoming migration.+ var stagedWorkspace string+ if !merged {+ workspacePath := detectDrivePath(sandboxDir, "workspace")+ stagedWorkspace = filepath.Join(stagingDir, filepath.Base(workspacePath))+ 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 originalsdefer os.RemoveAll(stagingDir)rootfsKey = fmt.Sprintf("migrations/%s/rootfs.qcow2", sandboxID)- workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2.zst", sandboxID)t0 := time.Now()+ // Merged migrations move a single disk — upload the rootfs and return with+ // an empty workspaceKey.+ if merged {+ state.Phase = "upload"+ sz, uerr := mc.uploadFile(ctx, stagedRootfs, rootfsKey)+ if uerr != nil {+ return "", "", fmt.Errorf("upload rootfs: %w", uerr)+ }+ log.Printf("qemu: migration pre-copy %s: rootfs=%.1fMB (merged, single disk) (%dms)",+ sandboxID, float64(sz)/(1024*1024), time.Since(t0).Milliseconds())+ return rootfsKey, "", nil+ }++ workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2.zst", sandboxID)+// Compress workspace with zstd before upload — typically 2-4x smaller,// proportionally faster to upload/download over S3.state.Phase = "compress-workspace"@@ -361,8 +381,15 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco}// PrepareIncomingMigration sets up QEMU on the target worker to receive a live migration.-// Returns the TCP address for the source to connect to.+// Returns the TCP address for the source to connect to. This exported entry+// point (the direct, non-S3 migration path via the Migrator interface) is+// always split; the merged path comes in through PrepareIncomingMigrationWithS3,+// which calls prepareIncomingMigration directly with merged=true.func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (incomingAddr string, hostPort int, err error) {+ return m.prepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template, false)+}++func (m *Manager) prepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string, merged bool) (incomingAddr string, hostPort int, err error) {sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)if err := os.MkdirAll(sandboxDir, 0755); err != nil {return "", 0, fmt.Errorf("mkdir: %w", err)@@ -383,8 +410,11 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootf}log.Printf("qemu: migration %s: prepared rootfs from template %q: %s", sandboxID, template, rootfsPath)}- // Create workspace if not provided- if workspacePath == "" {+ // Create workspace if not provided (split only). A merged sandbox has no+ // workspace disk, so an empty workspacePath there is intentional — do NOT+ // synthesize one, or the incoming QEMU would carry an extra drive the+ // migrated RAM's device model doesn't expect.+ if workspacePath == "" && !merged {workspacePath = filepath.Join(sandboxDir, "workspace.ext4")if err := CreateWorkspace(workspacePath, 4096); err != nil {return "", 0, fmt.Errorf("create workspace: %w", err)@@ -528,6 +558,7 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfguestCID: guestCID,bootArgs: bootArgs,goldenVersion: m.GoldenVersion(),+ diskLayout: boolToLayout(merged),// Marks this as an in-flight migration receiver until CompleteIncoming-// Migration clears it. The reaper uses this to tear down receivers whose// migration is abandoned (never completed), which otherwise stay alive@@ -718,11 +749,15 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,return "", 0, fmt.Errorf("mkdir: %w", err)}+ // An empty workspaceS3Key means the source was a merged (single-disk)+ // sandbox; workspacePath stays "" so PrepareIncomingMigration builds a+ // single drive, matching the migrated RAM's device model.+ merged := workspaceS3Key == ""rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")+ var workspacePath string- // Download rootfs + workspace in parallel. Workspace may be zstd-compressed.- // Rebase runs as soon as rootfs is ready (overlaps with workspace download).+ // Download rootfs (and, for split, workspace) in parallel. Workspace may be+ // zstd-compressed. Rebase runs as soon as rootfs is ready.type dlResult struct {err error}@@ -732,25 +767,28 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,go func() {rootfsCh <- dlResult{downloadS3ToFile(ctx, checkpointStore, rootfsS3Key, rootfsPath)}}()- go func() {- isCompressed := strings.HasSuffix(workspaceS3Key, ".zst")- dlPath := workspacePath- if isCompressed {- dlPath = workspacePath + ".zst"- }- if err := downloadS3ToFile(ctx, checkpointStore, workspaceS3Key, dlPath); err != nil {- workspaceCh <- dlResult{fmt.Errorf("download workspace: %w", err)}- return- }- if isCompressed {- decompressCmd := exec.CommandContext(ctx, "zstd", "-d", "--rm", "-q", dlPath, "-o", workspacePath)- if out, err := decompressCmd.CombinedOutput(); err != nil {- workspaceCh <- dlResult{fmt.Errorf("decompress workspace: %w (%s)", err, strings.TrimSpace(string(out)))}+ if !merged {+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ go func() {+ isCompressed := strings.HasSuffix(workspaceS3Key, ".zst")+ dlPath := workspacePath+ if isCompressed {+ dlPath = workspacePath + ".zst"+ }+ if err := downloadS3ToFile(ctx, checkpointStore, workspaceS3Key, dlPath); err != nil {+ workspaceCh <- dlResult{fmt.Errorf("download workspace: %w", err)}return}- }- workspaceCh <- dlResult{nil}- }()+ if isCompressed {+ decompressCmd := exec.CommandContext(ctx, "zstd", "-d", "--rm", "-q", dlPath, "-o", workspacePath)+ if out, err := decompressCmd.CombinedOutput(); err != nil {+ workspaceCh <- dlResult{fmt.Errorf("decompress workspace: %w (%s)", err, strings.TrimSpace(string(out)))}+ return+ }+ }+ workspaceCh <- dlResult{nil}+ }()+ }// Wait for rootfs download, then rebase (workspace downloads in parallel)if r := <-rootfsCh; r.err != nil {@@ -779,12 +817,14 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,log.Printf("qemu: migration %s: rootfs pinned to base %s", sandboxID, resolveVer)}- // Wait for workspace download + decompress to finish- if r := <-workspaceCh; r.err != nil {- return "", 0, r.err+ // Wait for workspace download + decompress to finish (split only)+ if !merged {+ if r := <-workspaceCh; r.err != nil {+ return "", 0, r.err+ }}- incomingAddr, hostPort, err = m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)+ incomingAddr, hostPort, err = m.prepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template, merged)if err != nil {return "", 0, err}diff --git a/internal/qemu/reset.go b/internal/qemu/reset.goindex d4a0f8ec..a6337922 100644--- a/internal/qemu/reset.go+++ b/internal/qemu/reset.go@@ -177,11 +177,17 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (host// and resource shape. The on-disk rootfs.qcow2 / workspace.qcow2 are// unchanged — this is "same box, freshly powered."sandboxDir := vm.sandboxDir+ merged := IsMerged(vm.diskLayout)rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")- if !fileExists(rootfsPath) || !fileExists(workspacePath) {- return 0, fmt.Errorf("sandbox %s: drives missing (rootfs=%v, workspace=%v)",- sandboxID, fileExists(rootfsPath), fileExists(workspacePath))+ // Merged boxes have no workspace disk; workspacePath stays "" so buildQEMUArgs+ // rebuilds the same single-drive topology the box was running with.+ var workspacePath string+ if !merged {+ workspacePath = filepath.Join(sandboxDir, "workspace.qcow2")+ }+ if !fileExists(rootfsPath) || (!merged && !fileExists(workspacePath)) {+ return 0, fmt.Errorf("sandbox %s: drives missing (rootfs=%v, merged=%v, workspace=%v)",+ sandboxID, fileExists(rootfsPath), merged, !merged && fileExists(workspacePath))}var meta SandboxMetadiff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex fdf423e8..43691f29 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -35,6 +35,10 @@ type SnapshotMeta struct {Template string `json:"template"`GuestPort int `json:"guestPort"`GoldenVersion string `json:"goldenVersion,omitempty"`+ // DiskLayout records the block topology this snapshot was captured with+ // (see disk_layout.go). Empty ⇒ split (legacy two-disk), so pre-merge+ // snapshots restore as split. Route through EffectiveDiskLayout on read.+ DiskLayout string `json:"diskLayout,omitempty"`SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`SealedTokens map[string]string `json:"sealedTokens,omitempty"`// SealedNames is the env-var-name → sealed-token index. Persisted alongside@@ -156,6 +160,11 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStotime.Sleep(200 * time.Millisecond)// Step 4: Write snapshot metadata+ merged := IsMerged(vm.diskLayout)+ workspaceMetaPath := ""+ if !merged {+ workspaceMetaPath = detectDrivePath(vm.sandboxDir, "workspace")+ }meta := &SnapshotMeta{SandboxID: vm.ID,Network: vm.network,@@ -163,13 +172,14 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoGuestMAC: vm.guestMAC,BootArgs: vm.bootArgs,RootfsPath: detectDrivePath(vm.sandboxDir, "rootfs"),- WorkspacePath: detectDrivePath(vm.sandboxDir, "workspace"),+ WorkspacePath: workspaceMetaPath,CpuCount: vm.CpuCount,MemoryMB: vm.MemoryMB,BaseMemoryMB: vm.baseMemoryMB,Template: vm.Template,GuestPort: vm.GuestPort,GoldenVersion: vm.goldenVersion,+ DiskLayout: vm.diskLayout,SnapshotedAt: time.Now(),}@@ -227,8 +237,12 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// "file changed as we read it" → corrupted archive → data loss on next wake.sandboxDir := vm.sandboxDirsandboxID := vm.ID- workspaceFile := filepath.Base(detectDrivePath(sandboxDir, "workspace"))rootfsFile := filepath.Base(detectDrivePath(sandboxDir, "rootfs"))+ // Merged hibernations archive only the rootfs; split archive both drives.+ driveFiles := []string{rootfsFile}+ if !merged {+ driveFiles = append(driveFiles, filepath.Base(detectDrivePath(sandboxDir, "workspace")))+ }archiveDir := filepath.Join(sandboxDir, fmt.Sprintf("archive-staging-%d", time.Now().UnixNano()))if err := os.MkdirAll(archiveDir, 0755); err != nil {@@ -241,7 +255,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// 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} {+ for _, driveFile := range driveFiles {src := filepath.Join(sandboxDir, driveFile)dst := filepath.Join(archiveDir, driveFile)if err := copyFileReflink(src, dst); err != nil {@@ -286,11 +300,9 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoarchivePath := filepath.Join(archiveDir, "checkpoint.tar.zst")// Archive from the staging copies — originals are free for wake/QEMU.- if err := createArchive(archivePath, archiveDir, []string{+ if err := createArchive(archivePath, archiveDir, append([]string{"snapshot/snapshot-meta.json",- rootfsFile,- workspaceFile,- }); err != nil {+ }, driveFiles...)); err != nil {goroutineErr = fmt.Errorf("archive: %w", err)log.Printf("qemu: async archive failed for %s: %v", sandboxID, err)return@@ -408,9 +420,15 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("parse snapshot meta: %w", err)}- workspacePath := detectDrivePath(sandboxDir, "workspace")- if !fileExists(workspacePath) {- return nil, fmt.Errorf("workspace not found at %s", workspacePath)+ // Merged snapshots have no workspace disk; workspacePath stays "" so the+ // woken QEMU reconstructs the single-disk device model captured in the+ // savevm state. Split snapshots must still have their workspace present.+ var workspacePath string+ if !IsMerged(meta.DiskLayout) {+ workspacePath = detectDrivePath(sandboxDir, "workspace")+ if !fileExists(workspacePath) {+ return nil, fmt.Errorf("workspace not found at %s", workspacePath)+ }}// Step 3: Set up network. Prefer the original TAP/subnet so the gateway@@ -656,6 +674,7 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cguestCID: guestCID,bootArgs: bootArgs,goldenVersion: m.goldenVersion, // set on wake — VM runs on the current worker's base+ diskLayout: EffectiveDiskLayout(meta.DiskLayout),}// Recompute virtio-mem amount from the meta. Without this the field// stays at zero on wake, which would (a) make grow deltas under-charge@@ -841,11 +860,24 @@ func lastLines(s string, n int) string {func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, timeout int) (*types.Sandbox, error) {sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)- workspacePath := detectDrivePath(sandboxDir, "workspace")rootfsPath := detectDrivePath(sandboxDir, "rootfs")- if !fileExists(workspacePath) {- return nil, fmt.Errorf("workspace not found at %s", workspacePath)+ // Determine the disk layout from the snapshot meta (authoritative). A merged+ // sandbox has no workspace disk to require or attach; workspacePath stays "".+ merged := false+ if snapJSON, err := os.ReadFile(filepath.Join(sandboxDir, "snapshot", "snapshot-meta.json")); err == nil {+ var sm SnapshotMeta+ if json.Unmarshal(snapJSON, &sm) == nil {+ merged = IsMerged(sm.DiskLayout)+ }+ }++ var workspacePath string+ if !merged {+ workspacePath = detectDrivePath(sandboxDir, "workspace")+ if !fileExists(workspacePath) {+ return nil, fmt.Errorf("workspace not found at %s", workspacePath)+ }}// Resolve the sandbox config. The create-time sandbox-meta.json lives only@@ -1017,6 +1049,7 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, timeguestCID: guestCID,bootArgs: bootArgs,goldenVersion: m.goldenVersion, // cold boot: VM runs on the current worker's base+ diskLayout: boolToLayout(merged),}// Generous agent wait: coldBootLocalInner is only reached on the