An open-source, faster Devin alternative
TypeScript
default to split with merged-create behind an env flip, ship both split and merged base images in one worker image, stamp migrated boxes with the golden their disk actually uses to prevent stranding, and drop convert-on-fork
Brian Reardon5e1f2a4b925b
diff --git a/cmd/worker/golden_upload.go b/cmd/worker/golden_upload.goindex 0b88336d..2cd1aadb 100644--- a/cmd/worker/golden_upload.go+++ b/cmd/worker/golden_upload.go@@ -5,6 +5,7 @@ import ("fmt""log""os"+ "path/filepath""time""github.com/opensandbox/opensandbox/internal/blobstore"@@ -74,11 +75,17 @@ func uploadGolden(path string, versionedOnly bool) error {return fmt.Errorf("blobstore returned nil — check endpoint/access-key env vars")}+ // The current-pointer key follows the file's basename so a merged base seeds+ // its own pointer ("default-merged.ext4") instead of overwriting the split+ // "default.ext4" — matching what ensureBaseImageFromBlob fetches per layout.+ // The versioned key keeps the "default.ext4" filename; its hash dir already+ // distinguishes a merged base from a split one.+ currentKey := filepath.Base(path)versionedKey := fmt.Sprintf("bases/%s/default.ext4", hash)bucket := cfg.GlobalBlobGoldensBucket- log.Printf("uploading %s (%.1fMB, hash=%s) to %s://%s/{default.ext4, %s}",- path, float64(st.Size())/(1024*1024), hash, store.Name(), bucket, versionedKey)+ log.Printf("uploading %s (%.1fMB, hash=%s) to %s://%s/{%s, %s}",+ path, float64(st.Size())/(1024*1024), hash, store.Name(), bucket, currentKey, versionedKey)t0 := time.Now()// Long timeout — multi-GB upload over residential or cross-region network.@@ -103,10 +110,10 @@ func uploadGolden(path string, versionedOnly bool) error {}t1 := time.Now()- if err := blobstore.Upload(ctx, store, bucket, "default.ext4", path); err != nil {- return fmt.Errorf("upload default.ext4: %w", err)+ if err := blobstore.Upload(ctx, store, bucket, currentKey, path); err != nil {+ return fmt.Errorf("upload %s: %w", currentKey, err)}- log.Printf("uploaded default.ext4 (%dms)", time.Since(t1).Milliseconds())+ log.Printf("uploaded %s (%dms)", currentKey, time.Since(t1).Milliseconds())log.Printf("done in %s", time.Since(t0).Round(time.Millisecond))return nildiff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.shindex a38b2d3f..21cd8932 100755--- a/deploy/ec2/build-rootfs-docker.sh+++ b/deploy/ec2/build-rootfs-docker.sh@@ -267,38 +267,15 @@ docker rm -f osb-rootfs-tmp# didn't actually change the rootfs content. When unset, mkfs generates a# random UUID (previous behaviour), which makes every build produce a new# goldenVersion even for identical inputs.-log "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.+# Eagerly initialize the inode tables + journal at mkfs time. 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.MKFS_E="lazy_itable_init=0,lazy_journal_init=0"-if [ -n "${ROOTFS_UUID:-}" ]; then- log "Using deterministic UUID: $ROOTFS_UUID"- 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 -E "$MKFS_E" "$EXT4_PATH"-fi--MNT_DIR="$TMPDIR/mnt"-mkdir -p "$MNT_DIR"-mount -o loop "$EXT4_PATH" "$MNT_DIR"--tar xf "$TMPDIR/rootfs.tar" -C "$MNT_DIR"--# Ensure key directories exist (workspace is created by Dockerfile)-for dir in proc sys dev dev/pts dev/shm tmp run; do- mkdir -p "$MNT_DIR/$dir"-done-# Inject guest kernel modules into rootfs.-# Copy the full /lib/modules/<kver> tree so all modules (Docker networking,-# vsock, overlay, virtio_mem, etc.) are available with correct dependencies.+# Resolve guest kernel version once (shared across every ext4 we emit).GUEST_KVER_FILE="/opt/opensandbox/guest-kernel-version"if [ -f "$GUEST_KVER_FILE" ]; thenGUEST_KVER=$(cat "$GUEST_KVER_FILE")@@ -306,33 +283,84 @@ elif ls -d /lib/modules/*-generic >/dev/null 2>&1; thenGUEST_KVER=$(ls -d /lib/modules/*-generic | sort -V | tail -1 | xargs basename)fi-if [ -n "${GUEST_KVER:-}" ] && [ -d "/lib/modules/$GUEST_KVER" ]; then- log "Injecting kernel modules for $GUEST_KVER..."- rm -rf "$MNT_DIR/lib/modules"/*- mkdir -p "$MNT_DIR/lib/modules"- cp -a "/lib/modules/$GUEST_KVER" "$MNT_DIR/lib/modules/"- depmod -b "$MNT_DIR" "$GUEST_KVER" 2>/dev/null || log "depmod failed (non-fatal)"- MOD_COUNT=$(find "$MNT_DIR/lib/modules/$GUEST_KVER" -name "*.ko*" | wc -l)- log "Injected $MOD_COUNT modules for kernel $GUEST_KVER"-else- log "WARNING: No guest kernel modules found — Docker networking and virtio_mem will not work"-fi+# make_ext4 OUTNAME SIZE_MB FLOOR_MB — build a populated ext4 from rootfs.tar.+# Merged and split bases have IDENTICAL content (the init already no-ops the vdb+# mount when no vdb is present); only the size/floor differ. So one rootfs build+# emits both default.ext4 (4GB split) and default-merged.ext4 (20GB merged),+# letting one worker image carry both so enabling merged-create is a pure env+# flip (OPENSANDBOX_GOLDEN_DISK_LAYOUT=merged) rather than an image rebuild.+make_ext4() {+ local outname="$1" size_mb="$2" floor_mb="$3"+ local ext4_path="$TMPDIR/${outname}.ext4"+ log "Converting to ext4 (${outname}: ${size_mb}MB, floor ${floor_mb}MB)..."+ rm -f "$ext4_path"+ truncate -s "${size_mb}M" "$ext4_path"+ if [ -n "${ROOTFS_UUID:-}" ]; then+ 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 -E "$MKFS_E" "$ext4_path"+ fi++ local mnt_dir="$TMPDIR/mnt"+ mkdir -p "$mnt_dir"+ mount -o loop "$ext4_path" "$mnt_dir"-sync-umount "$MNT_DIR"+ tar xf "$TMPDIR/rootfs.tar" -C "$mnt_dir"++ # Ensure key directories exist (workspace is created by Dockerfile)+ for dir in proc sys dev dev/pts dev/shm tmp run; do+ mkdir -p "$mnt_dir/$dir"+ done++ # Inject guest kernel modules (full /lib/modules/<kver> tree — Docker+ # networking, vsock, overlay, virtio_mem, etc. with correct dependencies).+ if [ -n "${GUEST_KVER:-}" ] && [ -d "/lib/modules/$GUEST_KVER" ]; then+ rm -rf "$mnt_dir/lib/modules"/*+ mkdir -p "$mnt_dir/lib/modules"+ cp -a "/lib/modules/$GUEST_KVER" "$mnt_dir/lib/modules/"+ depmod -b "$mnt_dir" "$GUEST_KVER" 2>/dev/null || log "depmod failed (non-fatal)"+ local mod_count+ mod_count=$(find "$mnt_dir/lib/modules/$GUEST_KVER" -name "*.ko*" | wc -l)+ log "Injected $mod_count modules for kernel $GUEST_KVER"+ else+ log "WARNING: No guest kernel modules found — Docker networking and virtio_mem will not work"+ fi++ sync+ umount "$mnt_dir"++ # Shrink to a usable floor — the ext4 is inside a qcow2 COW overlay, so unused+ # space costs nothing on disk.+ log "Resizing ${outname} to ${floor_mb}MB floor (sparse)..."+ resize2fs "$ext4_path" "${floor_mb}M" 2>/dev/null || log "resize2fs failed (non-fatal)"++ mkdir -p "$IMAGES_DIR"+ cp "$ext4_path" "$IMAGES_DIR/${outname}.ext4"+ log "Done: $IMAGES_DIR/${outname}.ext4 ($(du -h "$IMAGES_DIR/${outname}.ext4" | cut -f1))"+}-# Shrink to a usable floor — leave room for apt install, Docker, kernel modules etc.-# The ext4 is inside a qcow2 COW overlay, so unused space costs nothing on disk.ROOTFS_MIN_MB="${ROOTFS_MIN_MB:-4096}"-log "Resizing ext4 to ${ROOTFS_MIN_MB}MB floor (sparse — actual disk usage stays low)..."-resize2fs "$EXT4_PATH" "${ROOTFS_MIN_MB}M" 2>/dev/null || log "resize2fs failed (non-fatal)"-# Place in output directory-mkdir -p "$IMAGES_DIR"-cp "$EXT4_PATH" "$IMAGES_DIR/${IMAGE_NAME}.ext4"+# Primary base for this build's configured layout.+make_ext4 "$IMAGE_NAME" "$EXT4_SIZE_MB" "$ROOTFS_MIN_MB"++# Companion merged base: alongside the split "default" build, ship+# default-merged.ext4 so one worker image carries both bases (enabling merged-+# create is then a pure OPENSANDBOX_GOLDEN_DISK_LAYOUT=merged flip). The two are+# byte-identical content; the merged one is just grown to 20GB. Derive it from+# the split base (cp + resize2fs) rather than a fresh mkfs so it can be+# reproduced from a CACHED default.ext4 with no rootfs tar — the Packer worker-+# image build applies the exact same derivation on a rootfs-cache hit. Skipped+# for the merged build itself, non-default templates, or EMIT_MERGED_VARIANT=0.+if [ "$IMAGE_NAME" = "default" ] && [ "$DISK_LAYOUT" != "merged" ] && [ "${EMIT_MERGED_VARIANT:-1}" = "1" ]; then+ MERGED_SIZE_MB="${MERGED_SIZE_MB:-20480}"+ log "Deriving companion merged base default-merged.ext4 (${MERGED_SIZE_MB}MB) from ${IMAGE_NAME}.ext4..."+ cp --reflink=auto "$IMAGES_DIR/${IMAGE_NAME}.ext4" "$IMAGES_DIR/default-merged.ext4" 2>/dev/null \+ || cp "$IMAGES_DIR/${IMAGE_NAME}.ext4" "$IMAGES_DIR/default-merged.ext4"+ e2fsck -fy "$IMAGES_DIR/default-merged.ext4" >/dev/null 2>&1 || true+ resize2fs "$IMAGES_DIR/default-merged.ext4" "${MERGED_SIZE_MB}M" 2>/dev/null || log "resize2fs merged failed (non-fatal)"+ log "Done: $IMAGES_DIR/default-merged.ext4 ($(du -h "$IMAGES_DIR/default-merged.ext4" | cut -f1))"+fi# Clean up Docker imagedocker rmi -f "osb-rootfs-${IMAGE_NAME}:build" &>/dev/null || true--FINAL_SIZE=$(du -h "$IMAGES_DIR/${IMAGE_NAME}.ext4" | cut -f1)-log "Done: $IMAGES_DIR/${IMAGE_NAME}.ext4 ($FINAL_SIZE)"diff --git a/deploy/packer/worker-ami.pkr.hcl b/deploy/packer/worker-ami.pkr.hclindex de4ddb08..629320ba 100644--- a/deploy/packer/worker-ami.pkr.hcl+++ b/deploy/packer/worker-ami.pkr.hcl@@ -356,6 +356,17 @@ build {"PYEOF","fi",+ # Ensure the 20GB merged base exists before staging. build-rootfs-docker.sh+ # emits it on a cache MISS, but on a cache HIT the Docker build is skipped,+ # so derive it here from the (cached) default.ext4 — identical content grown+ # to 20GB, the exact same cp+resize2fs derivation the build script uses.+ "if [ ! -f /data/firecracker/images/default-merged.ext4 ]; then",+ " echo 'Deriving default-merged.ext4 from default.ext4 (rootfs-cache hit)'",+ " cp --reflink=auto /data/firecracker/images/default.ext4 /data/firecracker/images/default-merged.ext4 2>/dev/null || cp /data/firecracker/images/default.ext4 /data/firecracker/images/default-merged.ext4",+ " e2fsck -fy /data/firecracker/images/default-merged.ext4 >/dev/null 2>&1 || true",+ " resize2fs /data/firecracker/images/default-merged.ext4 20480M || echo 'resize2fs merged failed (non-fatal)'",+ "fi",+# Save rootfs to /opt (survives NVMe mount overlay on /data)"mkdir -p /opt/opensandbox/images","cp /data/firecracker/images/*.ext4 /opt/opensandbox/images/",@@ -503,6 +514,15 @@ build {"fi","echo 'Tigris dual-write: uploading /opt/opensandbox/images/default.ext4 via golden-upload subcommand'","/usr/local/bin/opensandbox-worker golden-upload /opt/opensandbox/images/default.ext4",+ "# Also seed the 20GB merged base so a fresh merged-create worker can fetch",+ "# it on cache miss (golden-upload names the current pointer by basename:",+ "# 'default-merged.ext4'; the versioned bases/{hash}/ key is separate).",+ "if [ -f /opt/opensandbox/images/default-merged.ext4 ]; then",+ " echo 'Tigris dual-write: uploading /opt/opensandbox/images/default-merged.ext4'",+ " /usr/local/bin/opensandbox-worker golden-upload /opt/opensandbox/images/default-merged.ext4",+ "else",+ " echo 'Tigris dual-write: default-merged.ext4 not present, skipping (older rootfs build)'",+ "fi",]}diff --git a/internal/config/config.go b/internal/config/config.goindex b2d2a533..224c2004 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -105,11 +105,15 @@ type Config struct {QEMUBin 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.+ // with — "" / "split" (default) = 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, and a dual-mode worker still HOSTS the other layout via migrate-in.+ // Defaults to split so deploying the merged-capable binary is behaviour-+ // neutral (no merged boxes appear at deploy). Flip to merged only AFTER the+ // whole fleet runs this binary AND ships the ~20GB base image (see+ // build-rootfs-docker.sh DISK_LAYOUT=merged) — set+ // OPENSANDBOX_GOLDEN_DISK_LAYOUT=merged to enable merged-create.GoldenDiskLayout string// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)@@ -360,7 +364,7 @@ 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)+ GoldenDiskLayout: os.Getenv("OPENSANDBOX_GOLDEN_DISK_LAYOUT"), // "" ⇒ split; set "merged" to enable merged-create (see field doc)EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),diff --git a/internal/qemu/blobstore_fetch.go b/internal/qemu/blobstore_fetch.goindex 3e3f35b0..e4c4e451 100644--- a/internal/qemu/blobstore_fetch.go+++ b/internal/qemu/blobstore_fetch.go@@ -6,7 +6,6 @@ import ("fmt""log""os"- "path/filepath""time""github.com/opensandbox/opensandbox/internal/blobstore"@@ -29,7 +28,10 @@ import (// Returns nil with a log warning if blobstore is unconfigured — callers// proceed with whatever's local (or fail downstream with a clear error).func (m *Manager) ensureBaseImageFromBlob(ctx context.Context) error {- target := filepath.Join(m.cfg.ImagesDir, "default.ext4")+ // Fetch the base for THIS worker's layout (default-merged.ext4 for a merged-+ // create worker). The split base for hosting other-layout resources arrives+ // separately, on-demand and version-keyed, via resolveBaseForVersion.+ target := m.goldenBaseFile()if fileExists(target) {return nil // already cached locally}@@ -42,7 +44,7 @@ func (m *Manager) ensureBaseImageFromBlob(ctx context.Context) error {bucket := m.cfg.GlobalBlobGoldensBucketkey := m.cfg.GlobalBlobGoldenKeyif key == "" {- key = "default.ext4"+ key = m.goldenBaseName() + ".ext4" // merged workers pull default-merged.ext4 by default}if bucket == "" {return errors.New("qemu: GlobalBlobGoldensBucket required to fetch from blob store")diff --git a/internal/qemu/checkpoint_rebase.go b/internal/qemu/checkpoint_rebase.goindex 3a15fb07..1d4c1dea 100644--- a/internal/qemu/checkpoint_rebase.go+++ b/internal/qemu/checkpoint_rebase.go@@ -50,14 +50,6 @@ 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)}@@ -162,7 +154,7 @@ func (m *Manager) resolveBaseForVersion(ctx context.Context, goldenVersion strinreturn "", fmt.Errorf("empty goldenVersion")}if goldenVersion == m.GoldenVersion() {- return filepath.Join(m.cfg.ImagesDir, "default.ext4"), nil+ return m.goldenBaseFile(), nil // this worker's own base (default.ext4 or default-merged.ext4)}retained := filepath.Join(m.cfg.ImagesDir, "bases", goldenVersion, "default.ext4")@@ -307,7 +299,7 @@ func (m *Manager) uploadBaseImageIfNew(goldenVersion string) {if m.checkpointStore == nil || goldenVersion == "" {return}- baseImage := filepath.Join(m.cfg.ImagesDir, "default.ext4")+ baseImage := m.goldenBaseFile() // upload this worker's actual base (merged=20GB) under its version keyif !fileExists(baseImage) {log.Printf("qemu: base image archival skipped: %s not found", baseImage)returndiff --git a/internal/qemu/convert_merge.go b/internal/qemu/convert_merge.godeleted file mode 100644index 331c6ecc..00000000--- a/internal/qemu/convert_merge.go+++ /dev/null@@ -1,271 +0,0 @@-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/manager.go b/internal/qemu/manager.goindex 682a860d..1f865afb 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -382,12 +382,6 @@ 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@@ -810,6 +804,26 @@ func (m *Manager) agentFsThawAfterWake(ctx context.Context, sandboxID string, ag}}+// goldenBaseName is the base-image template this worker builds its golden from:+// "default-merged" for a merged-create worker, "default" for split. The two are+// distinct files (default.ext4 = 4GB split, default-merged.ext4 = 20GB merged)+// shipped together in the worker image, so enabling merged-create is a pure+// OPENSANDBOX_GOLDEN_DISK_LAYOUT=merged flip rather than an image rebuild. The+// versioned S3 base cache (bases/{version}/default.ext4) stays layout-agnostic —+// the version hash already distinguishes a 20GB merged base from a 4GB split one.+func (m *Manager) goldenBaseName() string {+ if IsMerged(m.cfg.GoldenLayout) {+ return "default-merged"+ }+ return "default"+}++// goldenBaseFile is the absolute path to this worker's golden base ext4+// (default-merged.ext4 for merged-create, default.ext4 for split).+func (m *Manager) goldenBaseFile() string {+ return filepath.Join(m.cfg.ImagesDir, m.goldenBaseName()+".ext4")+}+// PrepareGoldenSnapshot boots a temporary VM, waits for the agent, then// hibernates it to create a reusable snapshot. Subsequent Create() calls// restore from this snapshot instead of cold-booting, cutting start time@@ -851,7 +865,7 @@ func (m *Manager) PrepareGoldenSnapshot() error {// Check if the base image on disk matches the golden snapshotstale := false- baseImage, _ := ResolveBaseImage(m.cfg.ImagesDir, "default")+ baseImage, _ := ResolveBaseImage(m.cfg.ImagesDir, m.goldenBaseName())if baseImage != "" && storedVersion != "" {if currentHash, err := computeGoldenVersion(baseImage); err == nil && currentHash != storedVersion {log.Printf("qemu: base image changed (golden=%s, disk=%s), rebuilding golden snapshot", storedVersion, currentHash)@@ -908,8 +922,9 @@ func (m *Manager) PrepareGoldenSnapshot() error {return fmt.Errorf("write preparing marker: %w", err)}- // Prepare rootfs from default template- baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, "default")+ // Prepare rootfs from the layout-appropriate base (default-merged.ext4 for+ // merged-create, default.ext4 for split).+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, m.goldenBaseName())if err != nil {return fmt.Errorf("resolve base image for golden: %w", err)}@@ -1946,8 +1961,14 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type}} else {// Base cold-boot fallback: layout follows the worker's configured golden.+ // For the default template on a merged worker, use the 20GB merged base+ // (default-merged.ext4); custom templates resolve as-is.coldMerged = IsMerged(m.cfg.GoldenLayout)- baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)+ baseTemplate := template+ if coldMerged && (baseTemplate == "" || baseTemplate == "default") {+ baseTemplate = "default-merged"+ }+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, baseTemplate)if err != nil {os.RemoveAll(sandboxDir)return nil, fmt.Errorf("resolve base image: %w", err)@@ -4098,16 +4119,11 @@ 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- }+ // Forks keep the checkpoint's recorded layout: a split checkpoint forks as a+ // split box (booted on the split base, which every dual-mode worker has via+ // the image or an on-demand versioned fetch), a merged checkpoint as merged.+ // (There is no convert-on-fork; split resources age out rather than being+ // rewritten to merged.)// 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.diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex 87e903e3..e33e8d74 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -386,10 +386,19 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco// 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)+ 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) {+// pinnedGolden is the golden version the rootfs overlay is actually rebased+// onto (the SOURCE's pinned golden, resolved+downloaded by the S3 caller). It+// may differ from this worker's current golden — and crucially may be a+// different base SIZE (split 4G vs merged 20G) in a dual-mode fleet. Stamping+// the VM with it (rather than m.GoldenVersion()) keeps the recorded golden+// consistent with the overlay's real base, so a later rebase (re-migration or+// fork) resolves the correct-size base instead of tripping the size guard and+// stranding the box. Empty ⇒ fall back to this worker's golden (non-S3 path,+// where the rootfs is prepared from the local base).+func (m *Manager) prepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string, merged bool, pinnedGolden string) (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)@@ -529,12 +538,19 @@ func (m *Manager) prepareIncomingMigration(ctx context.Context, sandboxID, rootf}// Store the VM (will be completed after migration arrives).- // goldenVersion is set to this worker's current golden — after migration,- // PrepareIncomingMigrationWithS3 rebased the overlay to point at this- // worker's base, so the VM is effectively running against that golden.- // Without this, any checkpoint taken after migration would record an- // empty goldenVersion and subsequent cross-golden forks of that- // checkpoint can't locate the correct old base to rebase from.+ // goldenVersion must match the base the overlay is ACTUALLY rebased onto.+ // The S3 path pins the overlay to the source's golden (pinnedGolden), which+ // in a dual-mode fleet can be a different base size than this worker's+ // golden — so stamping m.GoldenVersion() would misrecord the base and make+ // the next rebase (re-migration or fork) trip the size guard and strand the+ // box. Fall back to this worker's golden only when pinnedGolden is empty+ // (the non-S3 path, where the rootfs is prepared from the local base).+ // Without a value here, a checkpoint taken after migration would record an+ // empty goldenVersion and cross-golden forks couldn't locate the old base.+ stampGolden := pinnedGolden+ if stampGolden == "" {+ stampGolden = m.GoldenVersion()+ }now := time.Now()vm := &VMInstance{ID: sandboxID,@@ -557,7 +573,7 @@ func (m *Manager) prepareIncomingMigration(ctx context.Context, sandboxID, rootfguestMAC: guestMAC,guestCID: guestCID,bootArgs: bootArgs,- goldenVersion: m.GoldenVersion(),+ goldenVersion: stampGolden,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@@ -795,6 +811,10 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,return "", 0, fmt.Errorf("download rootfs from S3: %w", r.err)}+ // pinnedGolden records which golden the overlay ends up rebased onto, so the+ // VM is stamped with a version whose base matches the overlay (see the note+ // on prepareIncomingMigration). Empty for the flatten/local-base path.+ pinnedGolden := ""if overlayMode {if m.checkpointStore == nil && checkpointStore != nil {m.SetCheckpointStore(checkpointStore)@@ -814,6 +834,7 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,if err := rebaseMetadataOnly(ctx, rootfsPath, absBase); err != nil {return "", 0, fmt.Errorf("rebase rootfs to local base %s: %w", resolveVer, err)}+ pinnedGolden = resolveVerlog.Printf("qemu: migration %s: rootfs pinned to base %s", sandboxID, resolveVer)}@@ -824,7 +845,7 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,}}- incomingAddr, hostPort, err = m.prepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template, merged)+ incomingAddr, hostPort, err = m.prepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template, merged, pinnedGolden)if err != nil {return "", 0, err}