Skip to content

An open-source, faster Devin alternative

TypeScript

pin to base, reduce thrashing

Brian Reardon9f151cc8170a
diff --git a/.github/workflows/build-worker-ami.yml b/.github/workflows/build-worker-ami.yml
index 99bcf663..3a5df849 100644
--- a/.github/workflows/build-worker-ami.yml
+++ b/.github/workflows/build-worker-ami.yml
@@ -3,29 +3,22 @@ name: Build Worker Image
on:
push:
branches: [main, autoscaling-etc]
- # Only trigger on paths the worker binary actually depends on.
- # Server-only directories (internal/api, internal/billing) don't trigger rebuild.
- # If you add a new internal package used by cmd/worker, add it here.
+ # Paths that actually change what's inside the worker AMI.
+ # cmd/worker's transitive import surface (verified via `go list -deps
+ # ./cmd/worker/`) covers almost every internal package we have. Missing
+ # triggers here cause silent bugs where new worker code never gets
+ # shipped.
+ #
+ # Rootfs content-addressed caching (deploy/packer/worker-ami.pkr.hcl)
+ # means builds from unchanged rootfs inputs reuse the same cached ext4,
+ # so goldenVersion stays stable even when we rebuild the AMI for a
+ # worker-binary-only change. The narrowing here is just about avoiding
+ # wasted CI minutes on pushes that don't affect the worker binary
+ # (e.g. cmd/server/**, web/**, docs/**).
paths:
- 'cmd/worker/**'
- 'cmd/agent/**'
- - 'internal/agent/**'
- - 'internal/analytics/**'
- - 'internal/auth/**'
- - 'internal/compute/**'
- - 'internal/config/**'
- - 'internal/controlplane/**'
- - 'internal/crypto/**'
- - 'internal/db/**'
- - 'internal/grpctls/**'
- - 'internal/metrics/**'
- - 'internal/proxy/**'
- - 'internal/qemu/**'
- - 'internal/sandbox/**'
- - 'internal/secretsproxy/**'
- - 'internal/sparse/**'
- - 'internal/storage/**'
- - 'internal/worker/**'
+ - 'internal/**'
- 'pkg/**'
- 'proto/agent/**'
- 'proto/worker/**'
@@ -37,6 +30,15 @@ on:
- 'go.mod'
- 'go.sum'
- '.github/workflows/build-worker-ami.yml'
+ paths-ignore:
+ # Control-plane-only packages (shipped via deploy-server.yml).
+ # NOTE: internal/observability stays IN — cmd/worker imports it.
+ - 'internal/api/**'
+ - 'internal/billing/**'
+ - 'cmd/server/**'
+ - 'web/**'
+ - 'docs/**'
+ - '**.md'
workflow_dispatch:
env:
@@ -109,6 +111,19 @@ jobs:
- name: Packer init
run: packer init deploy/packer/worker-ami.pkr.hcl
+ - name: Read previous golden-version from Key Vault
+ id: prev-golden
+ run: |
+ # Previous successful build wrote its goldenVersion here; the
+ # NEW AMI bakes that base in so customers pinned to the last
+ # golden skip a runtime blob download on first fork.
+ PREV=$(az keyvault secret show \
+ --vault-name "${{ secrets.AZURE_KEY_VAULT_NAME }}" \
+ --name "golden-version" \
+ --query value -o tsv 2>/dev/null || echo "")
+ echo "prev=$PREV" >> $GITHUB_OUTPUT
+ echo "Previous golden version: ${PREV:-<none>}"
+
- name: Build image
run: |
# Use run number as patch version for gallery (must be integer)
@@ -124,6 +139,7 @@ jobs:
-var "image_version_patch=$PATCH" \
-var "base_archive_account=${{ secrets.AZURE_STORAGE_ACCOUNT }}" \
-var "base_archive_key=${{ secrets.AZURE_STORAGE_KEY }}" \
+ -var "prev_golden_version=${{ steps.prev-golden.outputs.prev }}" \
deploy/packer/worker-ami.pkr.hcl | tee /tmp/packer-output.txt
# Use the gallery image ID (NVMe-compatible for v7 VMs)
@@ -162,6 +178,19 @@ jobs:
--name "worker-image-version" \
--value "$VERSION"
+ # Record this build's goldenVersion so the NEXT AMI build can
+ # retain it as "previous golden" in /opt/opensandbox/images/bases/.
+ NEW_GOLDEN=$(grep -a 'Base image golden version:' /tmp/packer-output.txt | tail -1 | awk '{print $NF}' | tr -d '\r')
+ if [ -n "$NEW_GOLDEN" ]; then
+ az keyvault secret set \
+ --vault-name "${{ secrets.AZURE_KEY_VAULT_NAME }}" \
+ --name "golden-version" \
+ --value "$NEW_GOLDEN"
+ echo "Recorded new golden-version: $NEW_GOLDEN"
+ else
+ echo "WARN: could not extract goldenVersion from packer output — next build won't retain this base"
+ fi
+
echo "Published image ID to Key Vault"
- name: Cleanup old images
diff --git a/deploy/ec2/build-rootfs-docker.sh b/deploy/ec2/build-rootfs-docker.sh
index 40758cd5..d9b463c9 100755
--- a/deploy/ec2/build-rootfs-docker.sh
+++ b/deploy/ec2/build-rootfs-docker.sh
@@ -226,11 +226,21 @@ docker create --name osb-rootfs-tmp "osb-rootfs-${IMAGE_NAME}:build" /bin/true
docker export osb-rootfs-tmp -o "$TMPDIR/rootfs.tar"
docker rm -f osb-rootfs-tmp
-# Convert tar to ext4
+# Convert tar to ext4. When ROOTFS_UUID is set (by caller), stamp that UUID into
+# the filesystem so identical inputs produce byte-identical ext4 output — the
+# goldenVersion (sha256 of the file) then stays stable across builds that
+# 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"
-mkfs.ext4 -q -F -L rootfs "$EXT4_PATH"
+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" "$EXT4_PATH"
+else
+ mkfs.ext4 -q -F -L rootfs "$EXT4_PATH"
+fi
MNT_DIR="$TMPDIR/mnt"
mkdir -p "$MNT_DIR"
diff --git a/deploy/packer/worker-ami.pkr.hcl b/deploy/packer/worker-ami.pkr.hcl
index 8ac15b1a..52126a4e 100644
--- a/deploy/packer/worker-ami.pkr.hcl
+++ b/deploy/packer/worker-ami.pkr.hcl
@@ -109,6 +109,12 @@ variable "base_archive_container" {
description = "Container name for the base archive."
}
+variable "prev_golden_version" {
+ type = string
+ default = ""
+ description = "Previous AMI's golden version. When set, Packer downloads bases/{prev}/default.ext4 from blob storage and bakes it into the AMI at /opt/opensandbox/images/bases/{prev}/default.ext4 so forks of checkpoints pinned to the previous golden don't need a runtime blob download."
+}
+
# ---------------------------------------------------------------------
# Source: Ubuntu 24.04 x86_64 on Azure
# ---------------------------------------------------------------------
@@ -180,9 +186,27 @@ build {
script = "deploy/azure/setup-azure-host.sh"
}
- # 4. Install binaries and build rootfs
+ # 4. Install binaries and build (or restore from cache) rootfs.
+ #
+ # Rootfs content-addressed caching:
+ # - Compute ROOTFS_INPUT_HASH from agent binary + all rootfs source files
+ # + guest kernel modules. Same inputs → same hash → same cached artifact
+ # → same goldenVersion at runtime. A commit that doesn't touch any
+ # rootfs input reuses the existing blob and produces a byte-identical
+ # default.ext4 across AMIs, so the worker fleet stays on one golden.
+ #
+ # Deterministic ext4 build:
+ # - ROOTFS_UUID is derived from the input hash and passed into
+ # build-rootfs-docker.sh, which stamps it as the ext4 UUID + hash seed.
+ # This makes mkfs.ext4 output byte-stable — the file hash matches across
+ # workers even if the cache download races multiple AMI builds.
provisioner "shell" {
execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
+ environment_vars = [
+ "CACHE_ACCOUNT=${var.base_archive_account}",
+ "CACHE_KEY=${var.base_archive_key}",
+ "CACHE_CONTAINER=${var.base_archive_container}",
+ ]
inline = [
# Install worker and agent binaries
"mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker",
@@ -194,11 +218,59 @@ build {
"mkdir -p /tmp/rootfs-ctx",
"cd /tmp/rootfs-ctx && tar xzf /tmp/rootfs-ctx.tar.gz",
- # Build rootfs images (Docker was installed by setup-azure-host.sh)
+ # Compute a stable hash over all rootfs inputs. Order must be
+ # deterministic — use `sort` — so the same inputs always hash to the
+ # same value regardless of filesystem enumeration order.
+ "INPUT_HASH=$({ sha256sum /usr/local/bin/osb-agent; find /tmp/rootfs-ctx -type f | sort | xargs sha256sum; sha256sum /opt/opensandbox/guest-modules/*.ko* 2>/dev/null; } | sha256sum | awk '{print $1}')",
+ "echo \"Rootfs input hash: $INPUT_HASH\"",
+ "# Derive ext4 UUID from the hash (first 32 hex chars, dashed to UUID form).",
+ "ROOTFS_UUID=$(echo \"$INPUT_HASH\" | head -c 32 | sed 's/\\(........\\)\\(....\\)\\(....\\)\\(....\\)\\(............\\)/\\1-\\2-\\3-\\4-\\5/')",
+ "export ROOTFS_UUID",
+ "# Cache key: short hash for blob path.",
+ "INPUT_HASH_SHORT=$(echo \"$INPUT_HASH\" | cut -c1-16)",
+ "CACHE_BLOB=\"rootfs-cache/$INPUT_HASH_SHORT/default.ext4\"",
+
"mkdir -p /data/firecracker/images",
- "cd /tmp/rootfs-ctx && bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default",
- # Inject guest kernel modules into rootfs
+ "# Try cache download first. Fall through to fresh build on any error.",
+ "CACHE_HIT=0",
+ "if [ -n \"$CACHE_ACCOUNT\" ] && [ -n \"$CACHE_KEY\" ]; then",
+ " echo \"Checking rootfs cache: $CACHE_BLOB\"",
+ " CACHE_OUT=/data/firecracker/images/default.ext4",
+ " if python3 - <<PYEOF; then CACHE_HIT=1; fi",
+ "import http.client, hashlib, hmac, base64, datetime, os, sys",
+ "account = os.environ['CACHE_ACCOUNT']",
+ "key = os.environ['CACHE_KEY']",
+ "container = os.environ['CACHE_CONTAINER']",
+ "blob = '$CACHE_BLOB'",
+ "out_path = '$CACHE_OUT'",
+ "now = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')",
+ "string_to_sign = f'GET\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nx-ms-date:{now}\\nx-ms-version:2020-10-02\\n/{account}/{container}/{blob}'",
+ "sig = base64.b64encode(hmac.new(base64.b64decode(key), string_to_sign.encode(), hashlib.sha256).digest()).decode()",
+ "conn = http.client.HTTPSConnection(f'{account}.blob.core.windows.net')",
+ "headers = {'x-ms-date': now, 'x-ms-version': '2020-10-02', 'Authorization': f'SharedKey {account}:{sig}'}",
+ "conn.request('GET', f'/{container}/{blob}', headers=headers)",
+ "resp = conn.getresponse()",
+ "if resp.status != 200:",
+ " print(f'cache miss: {resp.status}'); sys.exit(1)",
+ "with open(out_path, 'wb') as f:",
+ " while True:",
+ " chunk = resp.read(8 * 1024 * 1024)",
+ " if not chunk: break",
+ " f.write(chunk)",
+ "print(f'cache hit: {os.path.getsize(out_path)} bytes')",
+ "sys.exit(0)",
+ "PYEOF",
+ "fi",
+
+ "if [ \"$CACHE_HIT\" = \"1\" ]; then",
+ " echo \"Rootfs restored from cache — skipping Docker build\"",
+ "else",
+ " echo \"Cache miss — building rootfs from source with ROOTFS_UUID=$ROOTFS_UUID\"",
+ " cd /tmp/rootfs-ctx && ROOTFS_UUID=\"$ROOTFS_UUID\" bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default",
+ "fi",
+
+ # Inject guest kernel modules into rootfs (applies to both cached and freshly-built images)
"GUEST_MODDIR=/opt/opensandbox/guest-modules",
"if [ -d \"$GUEST_MODDIR\" ] && [ -f /data/firecracker/images/default.ext4 ]; then",
" MNTDIR=$(mktemp -d)",
@@ -210,6 +282,30 @@ build {
" echo 'Guest kernel modules injected into rootfs'",
"fi",
+ "# On cache miss, upload the freshly built ext4 to the cache for future builds.",
+ "if [ \"$CACHE_HIT\" != \"1\" ] && [ -n \"$CACHE_ACCOUNT\" ] && [ -n \"$CACHE_KEY\" ]; then",
+ " echo \"Uploading fresh rootfs to cache: $CACHE_BLOB\"",
+ " python3 - <<PYEOF || echo 'cache upload failed (non-fatal)'",
+ "import http.client, hashlib, hmac, base64, datetime, os, sys",
+ "account = os.environ['CACHE_ACCOUNT']",
+ "key = os.environ['CACHE_KEY']",
+ "container = os.environ['CACHE_CONTAINER']",
+ "blob = '$CACHE_BLOB'",
+ "path = '/data/firecracker/images/default.ext4'",
+ "size = os.path.getsize(path)",
+ "now = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')",
+ "string_to_sign = f'PUT\\n\\n\\n{size}\\n\\napplication/octet-stream\\n\\n\\n\\n\\n\\n\\nx-ms-blob-type:BlockBlob\\nx-ms-date:{now}\\nx-ms-version:2020-10-02\\n/{account}/{container}/{blob}'",
+ "sig = base64.b64encode(hmac.new(base64.b64decode(key), string_to_sign.encode(), hashlib.sha256).digest()).decode()",
+ "conn = http.client.HTTPSConnection(f'{account}.blob.core.windows.net')",
+ "headers = {'x-ms-blob-type': 'BlockBlob', 'x-ms-date': now, 'x-ms-version': '2020-10-02', 'Content-Length': str(size), 'Content-Type': 'application/octet-stream', 'Authorization': f'SharedKey {account}:{sig}'}",
+ "with open(path, 'rb') as f:",
+ " conn.request('PUT', f'/{container}/{blob}', body=f, headers=headers)",
+ " resp = conn.getresponse()",
+ " print(f'cache upload: {resp.status} {resp.reason}')",
+ " sys.exit(0 if resp.status < 400 else 1)",
+ "PYEOF",
+ "fi",
+
# Save rootfs to /opt (survives NVMe mount overlay on /data)
"mkdir -p /opt/opensandbox/images",
"cp /data/firecracker/images/*.ext4 /opt/opensandbox/images/",
@@ -298,6 +394,63 @@ build {
]
}
+ # 4c. Bake previous golden's default.ext4 into the AMI under
+ # /opt/opensandbox/images/bases/{prev}/default.ext4. At first boot the
+ # Azure custom-data script copies /opt/opensandbox/images/bases/* to
+ # /data/firecracker/images/bases/* so forks of checkpoints pinned to
+ # the previous golden skip the ~4 GB blob download.
+ provisioner "shell" {
+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
+ environment_vars = [
+ "ARCHIVE_ACCOUNT=${var.base_archive_account}",
+ "ARCHIVE_KEY=${var.base_archive_key}",
+ "ARCHIVE_CONTAINER=${var.base_archive_container}",
+ "PREV_GOLDEN=${var.prev_golden_version}",
+ ]
+ inline = [
+ "if [ -z \"$PREV_GOLDEN\" ] || [ -z \"$ARCHIVE_ACCOUNT\" ] || [ -z \"$ARCHIVE_KEY\" ]; then",
+ " echo 'No previous golden version — skipping retention'",
+ " exit 0",
+ "fi",
+ "GOLDEN_VER=$(/usr/local/bin/opensandbox-worker golden-version /opt/opensandbox/images/default.ext4)",
+ "if [ \"$GOLDEN_VER\" = \"$PREV_GOLDEN\" ]; then",
+ " echo 'Previous golden matches current — skipping retention (no change this build)'",
+ " exit 0",
+ "fi",
+ "mkdir -p /opt/opensandbox/images/bases/$PREV_GOLDEN",
+ "OUT_PATH=/opt/opensandbox/images/bases/$PREV_GOLDEN/default.ext4",
+ "echo \"Downloading previous base $PREV_GOLDEN → $OUT_PATH\"",
+ "python3 - <<PYEOF",
+ "import http.client, hashlib, hmac, base64, datetime, os, sys",
+ "account = os.environ['ARCHIVE_ACCOUNT']",
+ "key = os.environ['ARCHIVE_KEY']",
+ "container = os.environ['ARCHIVE_CONTAINER']",
+ "prev = os.environ['PREV_GOLDEN']",
+ "blob = f'bases/{prev}/default.ext4'",
+ "out_path = '$OUT_PATH'",
+ "now = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')",
+ "string_to_sign = f'GET\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nx-ms-date:{now}\\nx-ms-version:2020-10-02\\n/{account}/{container}/{blob}'",
+ "sig = base64.b64encode(hmac.new(base64.b64decode(key), string_to_sign.encode(), hashlib.sha256).digest()).decode()",
+ "conn = http.client.HTTPSConnection(f'{account}.blob.core.windows.net')",
+ "headers = {'x-ms-date': now, 'x-ms-version': '2020-10-02', 'Authorization': f'SharedKey {account}:{sig}'}",
+ "conn.request('GET', f'/{container}/{blob}', headers=headers)",
+ "resp = conn.getresponse()",
+ "if resp.status != 200:",
+ " print(f'prev-base download failed: {resp.status} — skipping retention (non-fatal)')",
+ " sys.exit(0)",
+ "with open(out_path, 'wb') as f:",
+ " while True:",
+ " chunk = resp.read(8 * 1024 * 1024)",
+ " if not chunk: break",
+ " f.write(chunk)",
+ "print(f'retained: {os.path.getsize(out_path)} bytes at {out_path}')",
+ "PYEOF",
+ # If download failed, clean up the empty directory to avoid shipping
+ # a stub.
+ "[ -s \"$OUT_PATH\" ] || rm -rf /opt/opensandbox/images/bases/$PREV_GOLDEN",
+ ]
+ }
+
# 5. Deprovision for Azure image capture
provisioner "shell" {
execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
diff --git a/internal/compute/azure.go b/internal/compute/azure.go
index 41e00447..341c5ee3 100644
--- a/internal/compute/azure.go
+++ b/internal/compute/azure.go
@@ -568,6 +568,14 @@ func (p *AzurePool) buildUserData(opts MachineOpts) string {
sb.WriteString("if [ -d /opt/opensandbox/images ] && [ ! -f /data/firecracker/images/default.ext4 ]; then\n")
sb.WriteString(" cp /opt/opensandbox/images/*.ext4 /data/firecracker/images/ 2>/dev/null || true\n")
sb.WriteString(" echo 'Copied rootfs images from /opt/opensandbox/images to /data/firecracker/images'\n")
+ sb.WriteString("fi\n")
+ // Retained previous-golden bases (baked into AMI by Packer) live at
+ // /opt/opensandbox/images/bases/{goldenVersion}/default.ext4. The
+ // worker looks for them under /data/firecracker/images/bases/ so cross-
+ // golden forks skip the runtime blob download.
+ sb.WriteString("if [ -d /opt/opensandbox/images/bases ] && [ ! -d /data/firecracker/images/bases ]; then\n")
+ sb.WriteString(" cp -r /opt/opensandbox/images/bases /data/firecracker/images/\n")
+ sb.WriteString(" echo 'Copied retained bases from /opt/opensandbox/images/bases to /data/firecracker/images/bases'\n")
sb.WriteString("fi\n\n")
// Write worker env file from base64-encoded config
diff --git a/internal/qemu/checkpoint_rebase.go b/internal/qemu/checkpoint_rebase.go
index d6cc9c79..d8f187cb 100644
--- a/internal/qemu/checkpoint_rebase.go
+++ b/internal/qemu/checkpoint_rebase.go
@@ -11,193 +11,169 @@ import (
"path/filepath"
"strings"
"sync"
- "sync/atomic"
"time"
-
- "github.com/opensandbox/opensandbox/internal/storage"
)
-// rebaseCheckpointToCurrentBase migrates a checkpoint's rootfs.qcow2 from an old
-// golden version to the current base image. Uses qemu-img rebase to copy only the
-// blocks that differ between the old and new base into the overlay — the rest is
-// resolved via the new base's backing file reference. Result: thin overlay against
-// the current base, with size = original overlay + delta between bases.
-func (m *Manager) rebaseCheckpointToCurrentBase(ctx context.Context, checkpointDir, oldGoldenVersion string) error {
- rootfs := filepath.Join(checkpointDir, "rootfs.qcow2")
- if !fileExists(rootfs) {
- return fmt.Errorf("rootfs.qcow2 not found in %s", checkpointDir)
+// Pin-to-base: checkpoints stay tied to the exact goldenVersion they were
+// created against. On fork/restore we ensure that base is available locally
+// (either as the current default.ext4, a retained previous base on disk, or
+// an on-demand blob download) and do a metadata-only qemu-img rebase -u to
+// point the overlay's backing_file field at it. No block copying ever.
+//
+// Earlier attempts to rebase overlays across goldens (Variants A, B, C) all
+// produced subtle corruption: memory dumps reference disk content from the
+// old base, so swapping in new-base content under them breaks consistency.
+
+// ensureCheckpointRebased ensures the checkpoint's rootfs.qcow2 backing file
+// points at the correct base for its pinned goldenVersion. Name kept for
+// call-site stability.
+func (m *Manager) ensureCheckpointRebased(ctx context.Context, checkpointID string) error {
+ if m.checkpointStore == nil {
+ return nil
}
- oldBasePath, release, err := acquireOldBase(ctx, m.checkpointStore, oldGoldenVersion)
+ cacheDir := filepath.Join(m.cfg.DataDir, "checkpoint-snapshots", checkpointID)
+ metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")
+
+ m.checkpointCacheMu.RLock()
+ data, err := os.ReadFile(metaPath)
+ m.checkpointCacheMu.RUnlock()
if err != nil {
- return fmt.Errorf("download old base %s: %w", oldGoldenVersion, err)
+ return nil
}
- defer release()
- // Step 1: point overlay at the downloaded old base (metadata-only repoint).
- rebaseCmd := exec.CommandContext(ctx, "qemu-img", "rebase", "-u", "-b", oldBasePath, "-F", "raw", rootfs)
- if out, err := rebaseCmd.CombinedOutput(); err != nil {
- return fmt.Errorf("rebase to old base: %w (%s)", err, strings.TrimSpace(string(out)))
+ var meta SnapshotMeta
+ if json.Unmarshal(data, &meta) != nil {
+ return nil
}
- // Step 2: rebase to the new base. qemu-img compares old_base with new_base block
- // by block; blocks that differ get copied into the overlay so it reads correctly
- // on top of the new base. Preserves internal savevm snapshots.
- newBasePath := filepath.Join(m.cfg.ImagesDir, "default.ext4")
- if !fileExists(newBasePath) {
- return fmt.Errorf("current base %s not found on disk", newBasePath)
- }
- rebaseToCurrent := exec.CommandContext(ctx, "qemu-img", "rebase", "-b", newBasePath, "-F", "raw", rootfs)
- if out, err := rebaseToCurrent.CombinedOutput(); err != nil {
- return fmt.Errorf("rebase to current base: %w (%s)", err, strings.TrimSpace(string(out)))
+ if meta.GoldenVersion == "" {
+ return m.checkLegacyCheckpoint(checkpointID, meta)
}
- return nil
-}
+ basePath, err := m.resolveBaseForVersion(ctx, meta.GoldenVersion)
+ if err != nil {
+ return fmt.Errorf("resolve base %s: %w", meta.GoldenVersion, err)
+ }
-// oldBaseCache coordinates downloads of old base images, preventing duplicate
-// concurrent downloads and tracking reference counts for cleanup.
-var (
- oldBaseMu sync.Mutex
- oldBaseCache = map[string]string{} // goldenVersion → local temp path
- oldBaseRefs = map[string]int{} // goldenVersion → active reference count
- oldBaseFlight = map[string]chan struct{}{} // goldenVersion → closed when download completes
-)
+ rootfs := filepath.Join(cacheDir, "rootfs.qcow2")
+ if !fileExists(rootfs) {
+ return nil
+ }
-// acquireOldBase returns the path to a cached (or freshly downloaded) old base
-// image, incrementing its reference count. Caller MUST call the returned release
-// function when done — the file is deleted from /tmp when refs drop to zero.
-// Concurrent callers for the same version share a single download.
-func acquireOldBase(ctx context.Context, store *storage.CheckpointStore, goldenVersion string) (path string, release func(), err error) {
- for {
- oldBaseMu.Lock()
-
- // Already cached and on disk — bump ref and return.
- if p, ok := oldBaseCache[goldenVersion]; ok {
- if fileExists(p) {
- oldBaseRefs[goldenVersion]++
- oldBaseMu.Unlock()
- return p, makeRelease(goldenVersion), nil
- }
- delete(oldBaseCache, goldenVersion)
- delete(oldBaseRefs, goldenVersion)
- }
+ m.checkpointCacheMu.Lock()
+ defer m.checkpointCacheMu.Unlock()
- // Another goroutine is downloading — wait for it.
- if ch, downloading := oldBaseFlight[goldenVersion]; downloading {
- oldBaseMu.Unlock()
- select {
- case <-ch:
- continue // loop back to check cache
- case <-ctx.Done():
- return "", nil, ctx.Err()
- }
- }
+ return rebaseMetadataOnly(ctx, rootfs, basePath)
+}
- // We own the download.
- ch := make(chan struct{})
- oldBaseFlight[goldenVersion] = ch
- oldBaseMu.Unlock()
+// rebaseMetadataOnly runs qemu-img rebase -u to repoint an overlay's backing
+// file without touching data clusters.
+func rebaseMetadataOnly(ctx context.Context, overlayPath, newBasePath string) error {
+ cmd := exec.CommandContext(ctx, "qemu-img", "rebase", "-u", "-b", newBasePath, "-F", "raw", overlayPath)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("qemu-img rebase -u: %w (%s)", err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
- p, dlErr := doDownloadOldBase(ctx, store, goldenVersion)
+// resolveBaseForVersion returns a local path to the base image matching the
+// given goldenVersion, downloading from blob storage if needed. Downloaded
+// bases are cached persistently at ImagesDir/bases/{version}/default.ext4.
+func (m *Manager) resolveBaseForVersion(ctx context.Context, goldenVersion string) (string, error) {
+ if goldenVersion == "" {
+ return "", fmt.Errorf("empty goldenVersion")
+ }
+ if goldenVersion == m.GoldenVersion() {
+ return filepath.Join(m.cfg.ImagesDir, "default.ext4"), nil
+ }
- oldBaseMu.Lock()
- delete(oldBaseFlight, goldenVersion)
- if dlErr == nil {
- oldBaseCache[goldenVersion] = p
- oldBaseRefs[goldenVersion] = 1
- }
- oldBaseMu.Unlock()
- close(ch)
+ retained := filepath.Join(m.cfg.ImagesDir, "bases", goldenVersion, "default.ext4")
+ if fileExists(retained) {
+ return retained, nil
+ }
- if dlErr != nil {
- return "", nil, dlErr
- }
- return p, makeRelease(goldenVersion), nil
+ if err := m.downloadBaseToLocal(ctx, goldenVersion, retained); err != nil {
+ return "", err
}
+ return retained, nil
}
-func makeRelease(goldenVersion string) func() {
- return func() {
- oldBaseMu.Lock()
- defer oldBaseMu.Unlock()
- oldBaseRefs[goldenVersion]--
- if oldBaseRefs[goldenVersion] <= 0 {
- if p, ok := oldBaseCache[goldenVersion]; ok {
- os.Remove(p)
- delete(oldBaseCache, goldenVersion)
+// downloadBaseToLocal fetches bases/{goldenVersion}/default.ext4 from blob
+// storage. Concurrent callers share one download through an in-flight map.
+func (m *Manager) downloadBaseToLocal(ctx context.Context, goldenVersion, destPath string) error {
+ flightMu.Lock()
+ if ch, downloading := downloadFlight[goldenVersion]; downloading {
+ flightMu.Unlock()
+ select {
+ case <-ch:
+ if fileExists(destPath) {
+ return nil
}
- delete(oldBaseRefs, goldenVersion)
- }
+ return m.downloadBaseToLocal(ctx, goldenVersion, destPath)
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ ch := make(chan struct{})
+ downloadFlight[goldenVersion] = ch
+ flightMu.Unlock()
+ defer func() {
+ flightMu.Lock()
+ delete(downloadFlight, goldenVersion)
+ flightMu.Unlock()
+ close(ch)
+ }()
+
+ if fileExists(destPath) {
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
+ return fmt.Errorf("mkdir base cache: %w", err)
}
-}
-func doDownloadOldBase(ctx context.Context, store *storage.CheckpointStore, goldenVersion string) (string, error) {
- key := fmt.Sprintf("bases/%s/default.ext4", goldenVersion)
- finalPath := filepath.Join(os.TempDir(), fmt.Sprintf("old-base-%s.ext4", goldenVersion))
+ log.Printf("qemu: downloading base %s from blob storage", goldenVersion)
+ t0 := time.Now()
- reader, err := store.Download(ctx, key)
+ key := fmt.Sprintf("bases/%s/default.ext4", goldenVersion)
+ reader, err := m.checkpointStore.Download(ctx, key)
if err != nil {
- return "", fmt.Errorf("download %s: %w", key, err)
+ return fmt.Errorf("download %s: %w", key, err)
}
defer reader.Close()
- tmpFile, err := os.CreateTemp(os.TempDir(), "old-base-dl-*.ext4")
+ tmpFile, err := os.CreateTemp(filepath.Dir(destPath), "default-dl-*.ext4")
if err != nil {
- return "", fmt.Errorf("create temp file: %w", err)
+ return fmt.Errorf("create temp file: %w", err)
}
tmpPath := tmpFile.Name()
if _, err := io.Copy(tmpFile, reader); err != nil {
tmpFile.Close()
os.Remove(tmpPath)
- return "", fmt.Errorf("write base image: %w", err)
+ return fmt.Errorf("write base image: %w", err)
}
- tmpFile.Close()
-
- if err := os.Rename(tmpPath, finalPath); err != nil {
+ if err := tmpFile.Close(); err != nil {
os.Remove(tmpPath)
- return "", fmt.Errorf("rename: %w", err)
+ return err
}
-
- return finalPath, nil
-}
-
-// cleanupOldBases force-removes all cached old base images from /tmp,
-// regardless of refcount. Only safe when no rebases are in flight.
-func cleanupOldBases() {
- oldBaseMu.Lock()
- defer oldBaseMu.Unlock()
- for ver, path := range oldBaseCache {
- os.Remove(path)
- delete(oldBaseCache, ver)
- delete(oldBaseRefs, ver)
+ if err := os.Rename(tmpPath, destPath); err != nil {
+ os.Remove(tmpPath)
+ return fmt.Errorf("rename: %w", err)
}
-}
-// updateCheckpointGoldenVersion rewrites snapshot-meta.json with the new golden version.
-func updateCheckpointGoldenVersion(checkpointDir, newGoldenVersion string) error {
- metaPath := filepath.Join(checkpointDir, "snapshot", "snapshot-meta.json")
- data, err := os.ReadFile(metaPath)
- if err != nil {
- return fmt.Errorf("read metadata: %w", err)
- }
- var meta SnapshotMeta
- if err := json.Unmarshal(data, &meta); err != nil {
- return fmt.Errorf("parse metadata: %w", err)
- }
- meta.GoldenVersion = newGoldenVersion
- updated, err := json.Marshal(meta)
- if err != nil {
- return fmt.Errorf("marshal metadata: %w", err)
- }
- return os.WriteFile(metaPath, updated, 0644)
+ log.Printf("qemu: base %s cached at %s (%dms)", goldenVersion, destPath, time.Since(t0).Milliseconds())
+ return nil
}
-// uploadBaseImageIfNew uploads the base ext4 image to S3 if this golden version
-// hasn't been archived yet. Enables old checkpoints to be rebased when the base
-// image changes across Packer builds.
-// UploadBaseImageIfNew archives the current base image to S3 if not already stored.
+var (
+ flightMu sync.Mutex
+ downloadFlight = map[string]chan struct{}{}
+)
+
+// UploadBaseImageIfNew archives the current base to blob storage if this
+// golden version hasn't been stored yet. Lets workers rolled up later pull
+// back checkpoints pinned to earlier goldens.
func (m *Manager) UploadBaseImageIfNew() {
m.uploadBaseImageIfNew(m.GoldenVersion())
}
@@ -234,347 +210,32 @@ func (m *Manager) uploadBaseImageIfNew(goldenVersion string) {
log.Printf("qemu: base image archived for golden version %s", goldenVersion)
}
-// ensureCheckpointRebased checks if a cached checkpoint was created against a
-// different golden version and rebases it to the current base if needed.
-// Safe to call from the fork hot path — returns immediately if versions match.
-func (m *Manager) ensureCheckpointRebased(ctx context.Context, checkpointID string) error {
- if m.checkpointStore == nil {
- return nil
- }
-
- cacheDir := filepath.Join(m.cfg.DataDir, "checkpoint-snapshots", checkpointID)
- metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")
-
- m.checkpointCacheMu.RLock()
- data, err := os.ReadFile(metaPath)
- m.checkpointCacheMu.RUnlock()
- if err != nil {
- return nil
- }
-
- var meta SnapshotMeta
- if json.Unmarshal(data, &meta) != nil {
- return nil
- }
-
- currentVersion := m.GoldenVersion()
- if meta.GoldenVersion == "" {
- return m.checkLegacyCheckpoint(checkpointID, meta)
- }
- if meta.GoldenVersion == currentVersion {
- return nil
- }
-
- m.checkpointCacheMu.Lock()
- defer m.checkpointCacheMu.Unlock()
-
- // Re-check under write lock — background goroutine may have already migrated.
- data, err = os.ReadFile(metaPath)
- if err == nil {
- var fresh SnapshotMeta
- if json.Unmarshal(data, &fresh) == nil && fresh.GoldenVersion == currentVersion {
- return nil
- }
- }
-
- log.Printf("qemu: rebasing checkpoint %s from golden %s to %s", checkpointID, meta.GoldenVersion, currentVersion)
- t0 := time.Now()
-
- if err := m.rebaseCheckpointToCurrentBase(ctx, cacheDir, meta.GoldenVersion); err != nil {
- return err
- }
- if err := updateCheckpointGoldenVersion(cacheDir, currentVersion); err != nil {
- return err
- }
-
- log.Printf("qemu: checkpoint %s rebased (%dms)", checkpointID, time.Since(t0).Milliseconds())
- return nil
-}
-
-// migrateStaleCheckpoints scans the local checkpoint cache and rebases any
-// checkLegacyCheckpoint handles checkpoints that predate goldenVersion tracking.
-// If the checkpoint was created after the current base image was installed on
-// this worker, it's compatible with the current base and safe to fork.
-// If it was created before, we can't verify compatibility — return a clear
-// error so the caller knows to recreate the checkpoint rather than hang on
-// agent timeout.
+// checkLegacyCheckpoint handles checkpoints that predate goldenVersion
+// tracking. If snapshot-at time is after the current base install, we trust
+// the current base is compatible. Otherwise we can't prove compatibility.
func (m *Manager) checkLegacyCheckpoint(checkpointID string, meta SnapshotMeta) error {
baseImage := filepath.Join(m.cfg.ImagesDir, "default.ext4")
stat, err := os.Stat(baseImage)
if err != nil {
- return nil // can't check, let it proceed (best-effort)
+ return nil
}
baseInstalled := stat.ModTime()
if meta.SnapshotedAt.IsZero() || meta.SnapshotedAt.After(baseInstalled) {
- return nil // created after base was installed, safe to fork
+ return nil
}
-
return fmt.Errorf(
"checkpoint %s predates current base image (checkpoint created %s, "+
"base installed %s) and has no goldenVersion recorded. "+
- "Cannot migrate automatically — destroy this checkpoint and recreate it",
+ "Destroy this checkpoint and recreate it",
checkpointID,
meta.SnapshotedAt.Format(time.RFC3339),
baseInstalled.Format(time.RFC3339))
}
-// backfillGoldenVersions labels pre-existing cached checkpoints that predate
-// goldenVersion tracking but were created against the current base. Uses the
-// default.ext4 mtime as the cutoff — any checkpoint created after it was
-// necessarily made against the current base.
-func (m *Manager) backfillGoldenVersions() {
- if m.checkpointStore == nil {
- return
- }
- currentVersion := m.GoldenVersion()
- if currentVersion == "" {
- return
- }
-
- baseImage := filepath.Join(m.cfg.ImagesDir, "default.ext4")
- stat, err := os.Stat(baseImage)
- if err != nil {
- return
- }
- baseInstalled := stat.ModTime()
-
- cacheBase := filepath.Join(m.cfg.DataDir, "checkpoint-snapshots")
- entries, err := os.ReadDir(cacheBase)
- if err != nil {
- return
- }
-
- var labeled int
- for _, e := range entries {
- if !e.IsDir() {
- continue
- }
- cpDir := filepath.Join(cacheBase, e.Name())
- metaPath := filepath.Join(cpDir, "snapshot", "snapshot-meta.json")
- data, err := os.ReadFile(metaPath)
- if err != nil {
- continue
- }
- var meta SnapshotMeta
- if json.Unmarshal(data, &meta) != nil {
- continue
- }
- if meta.GoldenVersion != "" {
- continue // already labeled
- }
- if meta.SnapshotedAt.IsZero() || !meta.SnapshotedAt.After(baseInstalled) {
- continue // too old to safely label
- }
-
- meta.GoldenVersion = currentVersion
- updated, err := json.Marshal(meta)
- if err != nil {
- continue
- }
- if err := os.WriteFile(metaPath, updated, 0644); err != nil {
- log.Printf("qemu: backfill: failed to update %s: %v", e.Name(), err)
- continue
- }
-
- // Re-upload so S3 copy also has the label.
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
- if err := m.reuploadCheckpoint(ctx, e.Name(), cpDir); err != nil {
- log.Printf("qemu: backfill: %s re-upload failed: %v", e.Name(), err)
- }
- cancel()
+// MigrateStaleCheckpoints is a no-op under pin-to-base; kept for call-site
+// compatibility. Checkpoints no longer need background migration — their
+// backing file is resolved on-demand at fork time.
+func (m *Manager) MigrateStaleCheckpoints() {}
- labeled++
- }
-
- if labeled > 0 {
- log.Printf("qemu: backfill: labeled %d checkpoints with goldenVersion=%s", labeled, currentVersion)
- }
-}
-
-// checkpoints created against a different golden version. Runs in background
-// with bounded concurrency.
-// MigrateStaleCheckpoints scans the local cache and rebases stale checkpoints.
-func (m *Manager) MigrateStaleCheckpoints() {
- m.migrateStaleCheckpoints()
-}
-
-func (m *Manager) migrateStaleCheckpoints() {
- if m.checkpointStore == nil {
- return
- }
-
- // First pass: label pre-goldenVersion checkpoints that were made against the current base.
- m.backfillGoldenVersions()
-
- cacheBase := filepath.Join(m.cfg.DataDir, "checkpoint-snapshots")
- entries, err := os.ReadDir(cacheBase)
- if err != nil {
- return
- }
-
- currentVersion := m.GoldenVersion()
- if currentVersion == "" {
- return
- }
-
- type staleCP struct {
- id, dir, version string
- }
- var stale []staleCP
-
- for _, e := range entries {
- if !e.IsDir() {
- continue
- }
- cpDir := filepath.Join(cacheBase, e.Name())
- data, err := os.ReadFile(filepath.Join(cpDir, "snapshot", "snapshot-meta.json"))
- if err != nil {
- continue
- }
- var meta SnapshotMeta
- if json.Unmarshal(data, &meta) != nil {
- continue
- }
- if meta.GoldenVersion != "" && meta.GoldenVersion != currentVersion {
- stale = append(stale, staleCP{id: e.Name(), dir: cpDir, version: meta.GoldenVersion})
- }
- }
-
- if len(stale) == 0 {
- return
- }
-
- log.Printf("qemu: checkpoint migration: %d stale checkpoints to migrate", len(stale))
-
- // Track old versions so we can evict their bases after migration
- oldVersions := make(map[string]struct{})
- for _, cp := range stale {
- oldVersions[cp.version] = struct{}{}
- }
-
- sem := make(chan struct{}, 2)
- var wg sync.WaitGroup
- migrated := int64(0)
-
- for _, cp := range stale {
- wg.Add(1)
- sem <- struct{}{}
- go func(cp staleCP) {
- defer wg.Done()
- defer func() { <-sem }()
-
- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
- defer cancel()
-
- if err := m.ensureCheckpointRebased(ctx, cp.id); err != nil {
- log.Printf("qemu: checkpoint migration: %s failed: %v", cp.id, err)
- return
- }
-
- // Re-upload flattened checkpoint to S3 so other workers get the migrated version
- if err := m.reuploadCheckpoint(ctx, cp.id, cp.dir); err != nil {
- log.Printf("qemu: checkpoint migration: %s re-upload failed: %v", cp.id, err)
- }
-
- atomic.AddInt64(&migrated, 1)
- log.Printf("qemu: checkpoint migration: %s complete (rebased + re-uploaded)", cp.id)
- }(cp)
- }
-
- wg.Wait()
- cleanupOldBases()
-
- // Note: archived bases in S3 (bases/{version}/default.ext4) are kept forever
- // so month-old checkpoints in S3 that aren't cached on any worker can still
- // be rebased on demand. Storage cost is small (~4GB per Packer build).
- // The `evictOldBase` function exists for future CP-orchestrated cleanup.
- _ = oldVersions
-
- log.Printf("qemu: checkpoint migration: done (%d/%d migrated)", migrated, len(stale))
-}
-
-// reuploadCheckpoint re-archives and re-uploads a migrated checkpoint to S3,
-// replacing the old thin overlay (referencing a prior base) with the new thin
-// overlay (referencing the current base, including any inter-base diff blocks).
-func (m *Manager) reuploadCheckpoint(ctx context.Context, checkpointID, cacheDir string) error {
- if m.checkpointStore == nil {
- return nil
- }
-
- // Read metadata to get the sandbox ID for the S3 key
- metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")
- data, err := os.ReadFile(metaPath)
- if err != nil {
- return fmt.Errorf("read metadata: %w", err)
- }
- var meta SnapshotMeta
- if err := json.Unmarshal(data, &meta); err != nil {
- return fmt.Errorf("parse metadata: %w", err)
- }
-
- // Build list of files to archive
- var archiveFiles []string
- archiveFiles = append(archiveFiles, "rootfs.qcow2", "workspace.qcow2")
- if fileExists(filepath.Join(cacheDir, "snapshot-name")) {
- archiveFiles = append(archiveFiles, "snapshot-name")
- }
- if fileExists(filepath.Join(cacheDir, "mem.zst")) {
- archiveFiles = append(archiveFiles, "mem.zst")
- } else if fileExists(filepath.Join(cacheDir, "mem")) {
- archiveFiles = append(archiveFiles, "mem")
- }
- if fileExists(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")) {
- archiveFiles = append(archiveFiles, filepath.Join("snapshot", "snapshot-meta.json"))
- }
-
- archivePath := filepath.Join(cacheDir, "migrated.tar.zst")
- if err := createArchive(archivePath, cacheDir, archiveFiles); err != nil {
- return fmt.Errorf("archive: %w", err)
- }
- defer os.Remove(archivePath)
-
- s3Key := fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", meta.SandboxID, checkpointID)
- if _, err := m.checkpointStore.Upload(ctx, s3Key, archivePath); err != nil {
- return fmt.Errorf("upload: %w", err)
- }
-
- log.Printf("qemu: checkpoint %s re-uploaded to S3 (flattened)", checkpointID)
- return nil
-}
-
-// evictOldBase removes an archived base image from S3 after all local checkpoints
-// referencing it have been migrated.
-func (m *Manager) evictOldBase(goldenVersion string) {
- if m.checkpointStore == nil || goldenVersion == "" {
- return
- }
-
- // Verify no local checkpoints still reference this version
- cacheBase := filepath.Join(m.cfg.DataDir, "checkpoint-snapshots")
- entries, _ := os.ReadDir(cacheBase)
- for _, e := range entries {
- if !e.IsDir() {
- continue
- }
- data, err := os.ReadFile(filepath.Join(cacheBase, e.Name(), "snapshot", "snapshot-meta.json"))
- if err != nil {
- continue
- }
- var meta SnapshotMeta
- if json.Unmarshal(data, &meta) == nil && meta.GoldenVersion == goldenVersion {
- log.Printf("qemu: skipping eviction of base %s — checkpoint %s still references it", goldenVersion, e.Name())
- return
- }
- }
-
- key := fmt.Sprintf("bases/%s/default.ext4", goldenVersion)
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
- if err := m.checkpointStore.Delete(ctx, key); err != nil {
- log.Printf("qemu: failed to evict old base %s: %v", goldenVersion, err)
- return
- }
- log.Printf("qemu: evicted old base image %s from S3", goldenVersion)
-}
+func (m *Manager) migrateStaleCheckpoints() {}
diff --git a/internal/qemu/checkpoint_rebase_test.go b/internal/qemu/checkpoint_rebase_test.go
index 6355b348..ff0212d8 100644
--- a/internal/qemu/checkpoint_rebase_test.go
+++ b/internal/qemu/checkpoint_rebase_test.go
@@ -22,8 +22,8 @@ import (
type mockBlobClient struct {
mu sync.Mutex
- objects map[string][]byte // "bucket/key" → content
- heads int64 // count of Head calls (for concurrency tests)
+ objects map[string][]byte
+ heads int64
}
func newMockBlobClient() *mockBlobClient {
@@ -95,20 +95,16 @@ func (m *mockBlobClient) put(bucket, key string, data []byte) {
// Helpers
// ---------------------------------------------------------------------------
-// testManager creates a minimal Manager backed by temp directories, with
-// a mock-backed CheckpointStore. Call cleanup() when done.
func testManager(t *testing.T, goldenVersion string) (mgr *Manager, store *storage.CheckpointStore, mock *mockBlobClient, cleanup func()) {
t.Helper()
dataDir := t.TempDir()
imagesDir := t.TempDir()
- // Create a fake default.ext4 so mtime checks work.
basePath := filepath.Join(imagesDir, "default.ext4")
if err := os.WriteFile(basePath, []byte("fake-base-content"), 0644); err != nil {
t.Fatal(err)
}
- // Create checkpoint-snapshots dir.
cpDir := filepath.Join(dataDir, "checkpoint-snapshots")
if err := os.MkdirAll(cpDir, 0755); err != nil {
t.Fatal(err)
@@ -128,13 +124,17 @@ func testManager(t *testing.T, goldenVersion string) (mgr *Manager, store *stora
mgr.SetCheckpointStore(store)
cleanup = func() {
- // Reset global old-base cache between tests.
- cleanupOldBases()
+ // Reset in-flight map between tests so residual entries don't confuse
+ // the next test's coordination logic.
+ flightMu.Lock()
+ for k := range downloadFlight {
+ delete(downloadFlight, k)
+ }
+ flightMu.Unlock()
}
return
}
-// writeCheckpointMeta creates a fake cached checkpoint dir with the given metadata.
func writeCheckpointMeta(t *testing.T, dataDir, checkpointID string, meta SnapshotMeta) string {
t.Helper()
cpDir := filepath.Join(dataDir, "checkpoint-snapshots", checkpointID)
@@ -142,7 +142,6 @@ func writeCheckpointMeta(t *testing.T, dataDir, checkpointID string, meta Snapsh
if err := os.MkdirAll(snapDir, 0755); err != nil {
t.Fatal(err)
}
- // Create minimal rootfs.qcow2 placeholder.
if err := os.WriteFile(filepath.Join(cpDir, "rootfs.qcow2"), []byte("fake-qcow2"), 0644); err != nil {
t.Fatal(err)
}
@@ -156,123 +155,167 @@ func writeCheckpointMeta(t *testing.T, dataDir, checkpointID string, meta Snapsh
return cpDir
}
-func readCheckpointMeta(t *testing.T, dataDir, checkpointID string) SnapshotMeta {
- t.Helper()
- p := filepath.Join(dataDir, "checkpoint-snapshots", checkpointID, "snapshot", "snapshot-meta.json")
- data, err := os.ReadFile(p)
+// ---------------------------------------------------------------------------
+// resolveBaseForVersion
+// ---------------------------------------------------------------------------
+
+func TestResolveBase_CurrentVersion(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
+ defer cleanup()
+
+ path, err := mgr.resolveBaseForVersion(context.Background(), "v-current")
if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ want := filepath.Join(mgr.cfg.ImagesDir, "default.ext4")
+ if path != want {
+ t.Fatalf("path = %q, want %q", path, want)
+ }
+}
+
+func TestResolveBase_Retained(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
+ defer cleanup()
+
+ retained := filepath.Join(mgr.cfg.ImagesDir, "bases", "v-prev", "default.ext4")
+ if err := os.MkdirAll(filepath.Dir(retained), 0755); err != nil {
t.Fatal(err)
}
- var meta SnapshotMeta
- if err := json.Unmarshal(data, &meta); err != nil {
+ if err := os.WriteFile(retained, []byte("prev-base"), 0644); err != nil {
t.Fatal(err)
}
- return meta
+
+ path, err := mgr.resolveBaseForVersion(context.Background(), "v-prev")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if path != retained {
+ t.Fatalf("path = %q, want %q", path, retained)
+ }
+}
+
+func TestResolveBase_DownloadOnDemand(t *testing.T) {
+ mgr, _, mock, cleanup := testManager(t, "v-current")
+ defer cleanup()
+
+ payload := bytes.Repeat([]byte("B"), 4096)
+ mock.put("checkpoints", "bases/v-gone/default.ext4", payload)
+
+ path, err := mgr.resolveBaseForVersion(context.Background(), "v-gone")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ want := filepath.Join(mgr.cfg.ImagesDir, "bases", "v-gone", "default.ext4")
+ if path != want {
+ t.Fatalf("path = %q, want %q", path, want)
+ }
+ got, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, payload) {
+ t.Fatalf("downloaded content differs (got %d bytes, want %d)", len(got), len(payload))
+ }
+}
+
+func TestResolveBase_MissingInBlob(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
+ defer cleanup()
+
+ _, err := mgr.resolveBaseForVersion(context.Background(), "v-never-uploaded")
+ if err == nil {
+ t.Fatal("expected error when base not in blob storage")
+ }
+ if !contains(err.Error(), "v-never-uploaded") {
+ t.Fatalf("error should reference missing version, got: %s", err.Error())
+ }
}
// ---------------------------------------------------------------------------
-// Case 1 — Happy path: same version, no rebase
+// ensureCheckpointRebased (pin-to-base semantics)
// ---------------------------------------------------------------------------
-func TestCase1_SameVersion_NoRebase(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "abc123")
+// Same version: base resolves to current default.ext4. Rebase would run but
+// qemu-img isn't available in unit tests — we fail at that step with a
+// clear exec error, NOT at the resolve step.
+func TestEnsureCheckpointRebased_SameVersion_ResolvesCurrent(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
defer cleanup()
writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-same", SnapshotMeta{
SandboxID: "sb-test",
- GoldenVersion: "abc123",
+ GoldenVersion: "v-current",
SnapshotedAt: time.Now(),
})
err := mgr.ensureCheckpointRebased(context.Background(), "cp-same")
- if err != nil {
- t.Fatalf("expected no error for matching version, got: %v", err)
+ // Either nil (qemu-img present on dev machine) or a qemu-img error.
+ // What we're checking: no "resolve" error and no missing-base error.
+ if err != nil && (contains(err.Error(), "resolve") || contains(err.Error(), "not found")) {
+ t.Fatalf("unexpected resolve failure: %v", err)
}
}
-// ---------------------------------------------------------------------------
-// Case 2 — Cold fork with same version: checkpoint not cached, no rebase needed.
-// (When ensureCheckpointRebased is called, meta file doesn't exist yet
-// — it returns nil, allowing the normal download+fork path to proceed.)
-// ---------------------------------------------------------------------------
-
-func TestCase2_NotCached_NoMeta_Passthrough(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "abc123")
+func TestEnsureCheckpointRebased_NoMetaPassthrough(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
defer cleanup()
- // Don't create any checkpoint dir — simulates uncached checkpoint.
err := mgr.ensureCheckpointRebased(context.Background(), "cp-nonexistent")
if err != nil {
t.Fatalf("expected nil for uncached checkpoint, got: %v", err)
}
}
-// ---------------------------------------------------------------------------
-// Case 4 — Version mismatch: ensureCheckpointRebased detects it and attempts
-// rebase. Since we don't have real qemu-img, verify it reaches the download
-// step and fails with the expected error (old base not in mock store).
-// ---------------------------------------------------------------------------
-
-func TestCase4_VersionMismatch_TriggersRebase(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "newversion123")
+// Cross-golden with blob missing: fail at resolve step (no partial qcow2
+// corruption, clean error).
+func TestEnsureCheckpointRebased_CrossGolden_MissingBlob(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
defer cleanup()
- writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-stale", SnapshotMeta{
+ writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-missing-base", SnapshotMeta{
SandboxID: "sb-test",
- GoldenVersion: "oldversion456",
+ GoldenVersion: "v-vanished",
SnapshotedAt: time.Now(),
})
- err := mgr.ensureCheckpointRebased(context.Background(), "cp-stale")
+ err := mgr.ensureCheckpointRebased(context.Background(), "cp-missing-base")
if err == nil {
- t.Fatal("expected error for version mismatch (old base not in store)")
+ t.Fatal("expected error when old base is not in blob store")
}
- // Should fail trying to download the old base.
- if got := err.Error(); !contains(got, "oldversion456") {
- t.Fatalf("error should reference old version, got: %s", got)
+ if !contains(err.Error(), "v-vanished") {
+ t.Fatalf("error should reference missing version, got: %s", err.Error())
}
}
// ---------------------------------------------------------------------------
-// Case 5a — Legacy checkpoint (empty goldenVersion), created AFTER base install.
-// checkLegacyCheckpoint should return nil (safe to fork).
+// Legacy checkpoints (no goldenVersion recorded)
// ---------------------------------------------------------------------------
-func TestCase5a_LegacyCheckpoint_AfterBaseInstall(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "abc123")
+func TestLegacyCheckpoint_AfterBaseInstall(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
defer cleanup()
- // Touch the base image with a known mtime (1 hour ago).
basePath := filepath.Join(mgr.cfg.ImagesDir, "default.ext4")
past := time.Now().Add(-1 * time.Hour)
os.Chtimes(basePath, past, past)
- // Checkpoint was created AFTER base install.
meta := SnapshotMeta{
SandboxID: "sb-test",
- SnapshotedAt: time.Now(), // after past
+ SnapshotedAt: time.Now(),
}
- err := mgr.checkLegacyCheckpoint("cp-legacy-ok", meta)
- if err != nil {
+ if err := mgr.checkLegacyCheckpoint("cp-legacy-ok", meta); err != nil {
t.Fatalf("expected nil for post-install checkpoint, got: %v", err)
}
}
-// ---------------------------------------------------------------------------
-// Case 5b — Legacy checkpoint (empty goldenVersion), created BEFORE base install.
-// checkLegacyCheckpoint should return a clear error.
-// ---------------------------------------------------------------------------
-
-func TestCase5b_LegacyCheckpoint_BeforeBaseInstall(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "abc123")
+func TestLegacyCheckpoint_BeforeBaseInstall(t *testing.T) {
+ mgr, _, _, cleanup := testManager(t, "v-current")
defer cleanup()
- // Base installed "now".
basePath := filepath.Join(mgr.cfg.ImagesDir, "default.ext4")
os.Chtimes(basePath, time.Now(), time.Now())
- // Checkpoint was created BEFORE base install.
meta := SnapshotMeta{
SandboxID: "sb-test",
SnapshotedAt: time.Now().Add(-2 * time.Hour),
@@ -282,185 +325,48 @@ func TestCase5b_LegacyCheckpoint_BeforeBaseInstall(t *testing.T) {
if err == nil {
t.Fatal("expected error for pre-install checkpoint")
}
- msg := err.Error()
- if !contains(msg, "predates current base image") {
- t.Fatalf("error should mention 'predates current base image', got: %s", msg)
- }
- if !contains(msg, "Cannot migrate automatically") {
- t.Fatalf("error should mention 'Cannot migrate automatically', got: %s", msg)
- }
-}
-
-// ---------------------------------------------------------------------------
-// Case 5a (backfill) — backfillGoldenVersions labels empty-version checkpoints
-// that were created after the base was installed.
-// ---------------------------------------------------------------------------
-
-func TestCase5a_BackfillGoldenVersions(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "current789")
- defer cleanup()
-
- // Set base mtime to 1 hour ago.
- basePath := filepath.Join(mgr.cfg.ImagesDir, "default.ext4")
- past := time.Now().Add(-1 * time.Hour)
- os.Chtimes(basePath, past, past)
-
- // Create 3 checkpoints:
- // 1. Empty version, created after base → should be labeled
- writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-backfill-yes", SnapshotMeta{
- SandboxID: "sb-1",
- SnapshotedAt: time.Now(),
- })
- // 2. Empty version, created before base → should NOT be labeled
- writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-backfill-no", SnapshotMeta{
- SandboxID: "sb-2",
- SnapshotedAt: time.Now().Add(-2 * time.Hour),
- })
- // 3. Already has version → should NOT be touched
- writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-already-labeled", SnapshotMeta{
- SandboxID: "sb-3",
- GoldenVersion: "existing999",
- SnapshotedAt: time.Now(),
- })
-
- mgr.backfillGoldenVersions()
-
- // Verify cp-backfill-yes was labeled.
- meta1 := readCheckpointMeta(t, mgr.cfg.DataDir, "cp-backfill-yes")
- if meta1.GoldenVersion != "current789" {
- t.Errorf("cp-backfill-yes: expected goldenVersion=current789, got=%s", meta1.GoldenVersion)
- }
-
- // Verify cp-backfill-no was NOT labeled.
- meta2 := readCheckpointMeta(t, mgr.cfg.DataDir, "cp-backfill-no")
- if meta2.GoldenVersion != "" {
- t.Errorf("cp-backfill-no: expected empty goldenVersion, got=%s", meta2.GoldenVersion)
- }
-
- // Verify cp-already-labeled was NOT changed.
- meta3 := readCheckpointMeta(t, mgr.cfg.DataDir, "cp-already-labeled")
- if meta3.GoldenVersion != "existing999" {
- t.Errorf("cp-already-labeled: expected goldenVersion=existing999, got=%s", meta3.GoldenVersion)
+ if !contains(err.Error(), "predates current base image") {
+ t.Fatalf("error should mention 'predates current base image', got: %s", err.Error())
}
}
// ---------------------------------------------------------------------------
-// Case 6 — Old base not in S3. ensureCheckpointRebased should fail with
-// a download error, not hang or corrupt.
+// Concurrent downloads: one fetch, many waiters
// ---------------------------------------------------------------------------
-func TestCase6_MissingOldBase_CleanError(t *testing.T) {
- mgr, _, _, cleanup := testManager(t, "newversion")
+func TestDownloadBase_ConcurrentSingleFetch(t *testing.T) {
+ mgr, _, mock, cleanup := testManager(t, "v-current")
defer cleanup()
- writeCheckpointMeta(t, mgr.cfg.DataDir, "cp-missing-base", SnapshotMeta{
- SandboxID: "sb-test",
- GoldenVersion: "vanished000",
- SnapshotedAt: time.Now(),
- })
-
- err := mgr.ensureCheckpointRebased(context.Background(), "cp-missing-base")
- if err == nil {
- t.Fatal("expected error when old base is not in S3")
- }
- if !contains(err.Error(), "vanished000") {
- t.Fatalf("error should reference missing version, got: %s", err.Error())
- }
-}
-
-// ---------------------------------------------------------------------------
-// Case 7 — Concurrent acquireOldBase for same version: only one download,
-// both callers get a valid path and cleanup happens on last release.
-// ---------------------------------------------------------------------------
-
-func TestCase7_ConcurrentAcquire_SingleDownload(t *testing.T) {
- mock := newMockBlobClient()
- store := storage.NewCheckpointStoreFromClient(mock, "checkpoints")
-
- // Seed a 1KB fake base in the mock store.
- fakeBase := bytes.Repeat([]byte("X"), 1024)
- mock.put("checkpoints", "bases/ver123/default.ext4", fakeBase)
-
- // Reset global cache from prior tests.
- cleanupOldBases()
+ payload := bytes.Repeat([]byte("X"), 1024)
+ mock.put("checkpoints", "bases/v-shared/default.ext4", payload)
var wg sync.WaitGroup
paths := make([]string, 10)
- releases := make([]func(), 10)
errs := make([]error, 10)
-
for i := 0; i < 10; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
- p, rel, err := acquireOldBase(context.Background(), store, "ver123")
+ p, err := mgr.resolveBaseForVersion(context.Background(), "v-shared")
paths[idx] = p
- releases[idx] = rel
errs[idx] = err
}(i)
}
wg.Wait()
- // All should succeed with the same path.
+ want := filepath.Join(mgr.cfg.ImagesDir, "bases", "v-shared", "default.ext4")
for i, err := range errs {
if err != nil {
- t.Fatalf("goroutine %d failed: %v", i, err)
+ t.Fatalf("goroutine %d: %v", i, err)
}
- if paths[i] != paths[0] {
- t.Fatalf("goroutine %d got path %s, expected %s", i, paths[i], paths[0])
+ if paths[i] != want {
+ t.Fatalf("goroutine %d: path = %q, want %q", i, paths[i], want)
}
}
- // File should exist while refs are held.
- if !fileExists(paths[0]) {
- t.Fatal("base file should exist while references are held")
- }
-
- // Release all but one — file should still exist.
- for i := 1; i < 10; i++ {
- releases[i]()
- }
- if !fileExists(paths[0]) {
- t.Fatal("base file should exist while one reference remains")
- }
-
- // Release last — file should be cleaned up.
- releases[0]()
- if fileExists(paths[0]) {
- t.Fatal("base file should be deleted after all references released")
- }
-}
-
-// ---------------------------------------------------------------------------
-// updateCheckpointGoldenVersion — metadata file rewrite
-// ---------------------------------------------------------------------------
-
-func TestUpdateGoldenVersion(t *testing.T) {
- dir := t.TempDir()
- snapDir := filepath.Join(dir, "snapshot")
- os.MkdirAll(snapDir, 0755)
-
- original := SnapshotMeta{
- SandboxID: "sb-test",
- GoldenVersion: "old",
- SnapshotedAt: time.Now(),
- }
- data, _ := json.Marshal(original)
- os.WriteFile(filepath.Join(snapDir, "snapshot-meta.json"), data, 0644)
-
- if err := updateCheckpointGoldenVersion(dir, "new-version"); err != nil {
- t.Fatal(err)
- }
-
- updated, _ := os.ReadFile(filepath.Join(snapDir, "snapshot-meta.json"))
- var meta SnapshotMeta
- json.Unmarshal(updated, &meta)
-
- if meta.GoldenVersion != "new-version" {
- t.Errorf("expected goldenVersion=new-version, got=%s", meta.GoldenVersion)
- }
- if meta.SandboxID != "sb-test" {
- t.Errorf("SandboxID should be preserved, got=%s", meta.SandboxID)
+ if !fileExists(want) {
+ t.Fatal("expected cached base to persist after resolve")
}
}
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index 6723718b..508e1081 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -665,27 +665,25 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,
}
if overlayMode {
- currentGolden := m.GoldenVersion()
- if sourceGoldenVersion != "" && sourceGoldenVersion != currentGolden {
- if m.checkpointStore == nil && checkpointStore != nil {
- m.SetCheckpointStore(checkpointStore)
- }
- if err := m.rebaseCheckpointToCurrentBase(ctx, sandboxDir, sourceGoldenVersion); err != nil {
- return "", 0, fmt.Errorf("rebase rootfs across golden versions: %w", err)
- }
- log.Printf("qemu: migration %s: rootfs rebased from %s to %s (cross-version)", sandboxID, sourceGoldenVersion, currentGolden)
- } else {
- baseImage, resolveErr := ResolveBaseImage(m.cfg.ImagesDir, "default")
- if resolveErr != nil {
- return "", 0, fmt.Errorf("resolve base image for overlay rebase: %w", resolveErr)
- }
- absBase, _ := filepath.Abs(baseImage)
- rebaseCmd := exec.Command("qemu-img", "rebase", "-u", "-b", absBase, "-F", "raw", rootfsPath)
- if out, err := rebaseCmd.CombinedOutput(); err != nil {
- return "", 0, fmt.Errorf("rebase rootfs to local base: %w (%s)", err, strings.TrimSpace(string(out)))
- }
- log.Printf("qemu: migration %s: rootfs rebased to local base (same version)", sandboxID)
+ if m.checkpointStore == nil && checkpointStore != nil {
+ m.SetCheckpointStore(checkpointStore)
+ }
+ // Resolve the base file for the source's pinned goldenVersion:
+ // current worker default if it matches, otherwise a retained or
+ // on-demand-downloaded copy. Then metadata-repoint the overlay.
+ resolveVer := sourceGoldenVersion
+ if resolveVer == "" {
+ resolveVer = m.GoldenVersion()
+ }
+ basePath, err := m.resolveBaseForVersion(ctx, resolveVer)
+ if err != nil {
+ return "", 0, fmt.Errorf("resolve base %s: %w", resolveVer, err)
+ }
+ absBase, _ := filepath.Abs(basePath)
+ if err := rebaseMetadataOnly(ctx, rootfsPath, absBase); err != nil {
+ return "", 0, fmt.Errorf("rebase rootfs to local base %s: %w", resolveVer, err)
}
+ log.Printf("qemu: migration %s: rootfs pinned to base %s", sandboxID, resolveVer)
}
// Wait for workspace download + decompress to finish