Skip to content

An open-source, faster Devin alternative

TypeScript

ensure checkpoints are failsafe

Brian Reardona2426d07a3a0
diff --git a/.github/workflows/build-worker-ami.yml b/.github/workflows/build-worker-ami.yml
index b498dd8c..dc1beafd 100644
--- a/.github/workflows/build-worker-ami.yml
+++ b/.github/workflows/build-worker-ami.yml
@@ -3,13 +3,34 @@ 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:
- 'cmd/worker/**'
- 'cmd/agent/**'
- - 'internal/**'
- - 'proto/**'
+ - '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/**'
+ - 'pkg/**'
+ - 'proto/agent/**'
+ - 'proto/worker/**'
- 'deploy/firecracker/rootfs/**'
- - 'deploy/azure/**'
+ - 'deploy/azure/setup-azure-host.sh'
- 'deploy/ec2/build-rootfs-docker.sh'
- 'deploy/packer/**'
- 'scripts/claude-agent-wrapper/**'
@@ -84,6 +105,8 @@ jobs:
-var "location=$AZURE_LOCATION" \
-var "gallery_name=$AZURE_GALLERY_NAME" \
-var "image_version_patch=$PATCH" \
+ -var "base_archive_account=${{ secrets.AZURE_STORAGE_ACCOUNT }}" \
+ -var "base_archive_key=${{ secrets.AZURE_STORAGE_KEY }}" \
deploy/packer/worker-ami.pkr.hcl | tee /tmp/packer-output.txt
# Use the gallery image ID (NVMe-compatible for v7 VMs)
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 196dccd7..37f4e8e4 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -8,6 +8,7 @@ import (
"os"
"os/signal"
"path/filepath"
+ "strings"
"sync"
"syscall"
"time"
@@ -162,7 +163,7 @@ func main() {
log.Printf("opensandbox-worker: %d VMs failed to hibernate: %v", len(failed), failed)
}
- processHibernateResults(results, store, func(r interface{}) (string, string, error) {
+ processHibernateResults(results, store, checkpointStore, func(r interface{}) (string, string, error) {
hr := r.(qm.HibernateAllResult)
return hr.SandboxID, hr.HibernationKey, hr.Err
})
@@ -224,6 +225,13 @@ func main() {
}
}
+ // Wire checkpoint store into QEMU manager for base image archival + checkpoint rebasing
+ if checkpointStore != nil && qemuMgr != nil {
+ qemuMgr.SetCheckpointStore(checkpointStore)
+ go qemuMgr.UploadBaseImageIfNew()
+ go qemuMgr.MigrateStaleCheckpoints()
+ }
+
// PostgreSQL store
var store *db.Store
dbURL := getDBURL(cfg)
@@ -271,8 +279,9 @@ func main() {
if store != nil {
session, err := store.GetSandboxSession(context.Background(), sandboxID)
if err == nil {
- _, _ = store.CreateHibernation(context.Background(), sandboxID, session.OrgID,
+ _, superseded, _ := store.CreateHibernation(context.Background(), sandboxID, session.OrgID,
result.HibernationKey, result.SizeBytes, session.Region, session.Template, session.Config)
+ deleteOldHibernation(checkpointStore, superseded)
}
_ = store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)
}
@@ -686,8 +695,22 @@ func createPTYSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.PTY
}, nil
}
+// deleteOldHibernation best-effort removes a superseded hibernation archive from S3.
+// Called after a new hibernation replaces a prior one for the same sandbox.
+// We only keep one hibernation per sandbox to bound storage growth.
+func deleteOldHibernation(store *storage.CheckpointStore, key string) {
+ if store == nil || key == "" || strings.HasPrefix(key, "local://") {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := store.Delete(ctx, key); err != nil {
+ log.Printf("opensandbox-worker: failed to delete superseded hibernation %s: %v", key, err)
+ }
+}
+
// processHibernateResults handles results from HibernateAll for both backends.
-func processHibernateResults(results interface{}, store *db.Store, extract func(interface{}) (string, string, error)) {
+func processHibernateResults(results interface{}, store *db.Store, checkpointStore *storage.CheckpointStore, extract func(interface{}) (string, string, error)) {
switch rs := results.(type) {
case []qm.HibernateAllResult:
for _, r := range rs {
@@ -703,8 +726,9 @@ func processHibernateResults(results interface{}, store *db.Store, extract func(
if store != nil {
session, err := store.GetSandboxSession(context.Background(), r.SandboxID)
if err == nil {
- _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,
+ _, superseded, _ := store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,
r.HibernationKey, 0, session.Region, session.Template, session.Config)
+ deleteOldHibernation(checkpointStore, superseded)
_ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)
}
}
@@ -725,7 +749,9 @@ func recoverLocalQEMU(ctx context.Context, qmMgr *qm.Manager, store *db.Store, c
log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)
continue
}
- _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,
+ // local:// hibernations are recovery markers, not S3 archives —
+ // no superseded blob to delete.
+ _, _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,
"local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)
_ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)
if r.HasSnapshot {
diff --git a/deploy/packer/worker-ami.pkr.hcl b/deploy/packer/worker-ami.pkr.hcl
index 2795155d..47a26317 100644
--- a/deploy/packer/worker-ami.pkr.hcl
+++ b/deploy/packer/worker-ami.pkr.hcl
@@ -90,6 +90,25 @@ variable "agent_binary" {
description = "Path to the pre-built agent binary (amd64 Linux)."
}
+variable "base_archive_account" {
+ type = string
+ default = ""
+ description = "Azure storage account for archiving default.ext4 by goldenVersion hash. Empty to skip archival."
+}
+
+variable "base_archive_key" {
+ type = string
+ default = ""
+ sensitive = true
+ description = "Storage account key for the base archive. Paired with base_archive_account."
+}
+
+variable "base_archive_container" {
+ type = string
+ default = "checkpoints"
+ description = "Container name for the base archive."
+}
+
# ---------------------------------------------------------------------
# Source: Ubuntu 24.04 x86_64 on Azure
# ---------------------------------------------------------------------
@@ -205,6 +224,78 @@ build {
]
}
+ # 4b. Archive base image to blob storage keyed by goldenVersion so that old
+ # checkpoints referencing this base can be rebased even after workers roll.
+ 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}",
+ ]
+ inline = [
+ "if [ -z \"$ARCHIVE_ACCOUNT\" ] || [ -z \"$ARCHIVE_KEY\" ]; then",
+ " echo 'Base archive account/key not set — skipping archival'",
+ " exit 0",
+ "fi",
+ "if [ ! -f /opt/opensandbox/images/default.ext4 ]; then",
+ " echo 'default.ext4 not found — skipping archival'",
+ " exit 0",
+ "fi",
+ "GOLDEN_VER=$(head -c 1048576 /opt/opensandbox/images/default.ext4 | sha256sum | cut -c1-16)",
+ "echo \"Base image golden version: $GOLDEN_VER\"",
+ "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']",
+ "golden_ver = '$GOLDEN_VER'",
+ "blob = f'bases/{golden_ver}/default.ext4'",
+ "path = '/opt/opensandbox/images/default.ext4'",
+ "",
+ "# Check if already archived",
+ "now = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')",
+ "string_to_sign = f'HEAD\\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}'",
+ "signature = 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}:{signature}'}",
+ "conn.request('HEAD', f'/{container}/{blob}', headers=headers)",
+ "resp = conn.getresponse()",
+ "resp.read()",
+ "conn.close()",
+ "if resp.status == 200:",
+ " print(f'Base {golden_ver} already archived')",
+ " sys.exit(0)",
+ "if resp.status not in (404, 200):",
+ " print(f'HEAD check failed: {resp.status}')",
+ " sys.exit(1)",
+ "",
+ "# Upload",
+ "size = os.path.getsize(path)",
+ "print(f'Uploading {size} bytes to bases/{golden_ver}/default.ext4')",
+ "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}'",
+ "signature = 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}:{signature}',",
+ "}",
+ "with open(path, 'rb') as f:",
+ " conn.request('PUT', f'/{container}/{blob}', body=f, headers=headers)",
+ " resp = conn.getresponse()",
+ " print(f'Upload: {resp.status} {resp.reason}')",
+ " if resp.status >= 400:",
+ " print(resp.read().decode())",
+ " sys.exit(1)",
+ "PYEOF",
+ ]
+ }
+
# 5. Deprovision for Azure image capture
provisioner "shell" {
execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 8f5f0ae3..63c22075 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -1380,7 +1380,8 @@ func (s *Server) hibernateSandbox(c echo.Context) error {
template = session.Template
region = session.Region
}
- _, _ = s.store.CreateHibernation(ctx, id, orgID, result.HibernationKey, result.SizeBytes, region, template, cfg)
+ _, superseded, _ := s.store.CreateHibernation(ctx, id, orgID, result.HibernationKey, result.SizeBytes, region, template, cfg)
+ s.deleteSupersededHibernation(superseded)
_ = s.store.UpdateSandboxSessionStatus(ctx, id, "hibernated", nil)
}
@@ -1396,6 +1397,20 @@ func (s *Server) hibernateSandbox(c echo.Context) error {
})
}
+// deleteSupersededHibernation best-effort removes a prior hibernation archive
+// from S3 when it's been replaced by a new hibernation for the same sandbox.
+// We only keep one hibernation per sandbox to bound storage growth.
+func (s *Server) deleteSupersededHibernation(key string) {
+ if s.checkpointStore == nil || key == "" || strings.HasPrefix(key, "local://") {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := s.checkpointStore.Delete(ctx, key); err != nil {
+ log.Printf("api: failed to delete superseded hibernation %s: %v", key, err)
+ }
+}
+
func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error {
if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
@@ -1430,9 +1445,10 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error
// Record hibernation in PG
orgID, _ := auth.GetOrgID(c)
- _, _ = s.store.CreateHibernation(c.Request().Context(), sandboxID, orgID,
+ _, superseded, _ := s.store.CreateHibernation(c.Request().Context(), sandboxID, orgID,
grpcResp.CheckpointKey, grpcResp.SizeBytes,
session.Region, session.Template, session.Config)
+ s.deleteSupersededHibernation(superseded)
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)
// Invalidate the proxy route cache: wake may land the sandbox on a
diff --git a/internal/db/store.go b/internal/db/store.go
index 6120eeff..a081812a 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -879,10 +879,32 @@ type SandboxHibernation struct {
ExpiredAt *time.Time `json:"expiredAt,omitempty"`
}
-// CreateHibernation inserts a new hibernation record.
-func (s *Store) CreateHibernation(ctx context.Context, sandboxID string, orgID uuid.UUID, hibernationKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) (*SandboxHibernation, error) {
+// CreateHibernation inserts a new hibernation record, marking any prior active
+// hibernation for the same sandbox as expired. Returns the new record plus the
+// superseded hibernation key (if any) so the caller can delete the old S3 blob
+// — we only keep one hibernation per sandbox to bound storage growth.
+func (s *Store) CreateHibernation(ctx context.Context, sandboxID string, orgID uuid.UUID, hibernationKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) (*SandboxHibernation, string, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, "", fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+
+ // Find + expire any prior active hibernation for this sandbox
+ var supersededKey string
+ err = tx.QueryRow(ctx,
+ `UPDATE sandbox_hibernations SET expired_at = now()
+ WHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL
+ RETURNING hibernation_key`,
+ sandboxID,
+ ).Scan(&supersededKey)
+ if err != nil && err.Error() != "no rows in result set" {
+ // Real DB error (not just "no prior hibernation") — log and continue
+ supersededKey = ""
+ }
+
cp := &SandboxHibernation{}
- err := s.pool.QueryRow(ctx,
+ err = tx.QueryRow(ctx,
`INSERT INTO sandbox_hibernations (sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at`,
@@ -890,9 +912,14 @@ func (s *Store) CreateHibernation(ctx context.Context, sandboxID string, orgID u
).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.HibernationKey, &cp.SizeBytes,
&cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt)
if err != nil {
- return nil, fmt.Errorf("failed to create hibernation: %w", err)
+ return nil, "", fmt.Errorf("failed to create hibernation: %w", err)
}
- return cp, nil
+
+ if err := tx.Commit(ctx); err != nil {
+ return nil, "", fmt.Errorf("commit tx: %w", err)
+ }
+
+ return cp, supersededKey, nil
}
// GetActiveHibernation returns the active (not restored, not expired) hibernation for a sandbox.
diff --git a/internal/qemu/checkpoint_rebase.go b/internal/qemu/checkpoint_rebase.go
new file mode 100644
index 00000000..160d49ae
--- /dev/null
+++ b/internal/qemu/checkpoint_rebase.go
@@ -0,0 +1,514 @@
+package qemu
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "os/exec"
+ "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)
+ }
+
+ oldBasePath, err := downloadOldBase(ctx, m.checkpointStore, oldGoldenVersion)
+ if err != nil {
+ return fmt.Errorf("download old base %s: %w", oldGoldenVersion, err)
+ }
+
+ // 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)))
+ }
+
+ // 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)))
+ }
+
+ return nil
+}
+
+// oldBaseCache prevents duplicate downloads of the same old base version.
+var (
+ oldBaseMu sync.Mutex
+ oldBaseCache = map[string]string{} // goldenVersion → local temp path
+)
+
+// downloadOldBase downloads an old base image from S3, caching in /tmp.
+// Multiple concurrent callers for the same version share one download.
+func downloadOldBase(ctx context.Context, store *storage.CheckpointStore, goldenVersion string) (string, error) {
+ oldBaseMu.Lock()
+ if path, ok := oldBaseCache[goldenVersion]; ok {
+ oldBaseMu.Unlock()
+ if fileExists(path) {
+ return path, nil
+ }
+ }
+ oldBaseMu.Unlock()
+
+ key := fmt.Sprintf("bases/%s/default.ext4", goldenVersion)
+ localPath := filepath.Join(os.TempDir(), fmt.Sprintf("old-base-%s.ext4", goldenVersion))
+
+ reader, err := store.Download(ctx, key)
+ if err != nil {
+ return "", fmt.Errorf("download %s: %w", key, err)
+ }
+ defer reader.Close()
+
+ f, err := os.Create(localPath)
+ if err != nil {
+ return "", fmt.Errorf("create temp file: %w", err)
+ }
+ if _, err := io.Copy(f, reader); err != nil {
+ f.Close()
+ os.Remove(localPath)
+ return "", fmt.Errorf("write base image: %w", err)
+ }
+ f.Close()
+
+ oldBaseMu.Lock()
+ oldBaseCache[goldenVersion] = localPath
+ oldBaseMu.Unlock()
+
+ return localPath, nil
+}
+
+// cleanupOldBases removes cached old base images from /tmp.
+func cleanupOldBases() {
+ oldBaseMu.Lock()
+ defer oldBaseMu.Unlock()
+ for ver, path := range oldBaseCache {
+ os.Remove(path)
+ delete(oldBaseCache, ver)
+ }
+}
+
+// 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)
+}
+
+// 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.
+func (m *Manager) UploadBaseImageIfNew() {
+ m.uploadBaseImageIfNew(m.GoldenVersion())
+}
+
+func (m *Manager) uploadBaseImageIfNew(goldenVersion string) {
+ if m.checkpointStore == nil || goldenVersion == "" {
+ return
+ }
+ baseImage := filepath.Join(m.cfg.ImagesDir, "default.ext4")
+ if !fileExists(baseImage) {
+ log.Printf("qemu: base image archival skipped: %s not found", baseImage)
+ return
+ }
+
+ key := fmt.Sprintf("bases/%s/default.ext4", goldenVersion)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ exists, err := m.checkpointStore.Exists(ctx, key)
+ if err != nil {
+ log.Printf("qemu: base image existence check failed: %v", err)
+ return
+ }
+ if exists {
+ return
+ }
+
+ uploadCtx, uploadCancel := context.WithTimeout(context.Background(), 10*time.Minute)
+ defer uploadCancel()
+ if _, err := m.checkpointStore.Upload(uploadCtx, key, baseImage); err != nil {
+ log.Printf("qemu: base image upload failed for version %s: %v", goldenVersion, err)
+ return
+ }
+ 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.
+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)
+ }
+ baseInstalled := stat.ModTime()
+
+ if meta.SnapshotedAt.IsZero() || meta.SnapshotedAt.After(baseInstalled) {
+ return nil // created after base was installed, safe to fork
+ }
+
+ 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",
+ 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()
+
+ 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)
+}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 0dd2153f..82fcc978 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -134,7 +134,8 @@ type Manager struct {
onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)
onSandboxDestroy func(sandboxID string)
- secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configured
+ secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configured
+ checkpointStore *storage.CheckpointStore // for base image archival + checkpoint rebasing (nil until set)
}
// NewManager creates a new QEMU-backed sandbox manager.
@@ -212,6 +213,12 @@ func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {
m.secretsProxy = sp
}
+// SetCheckpointStore sets the S3 checkpoint store for base image archival and
+// on-demand checkpoint rebasing across golden versions.
+func (m *Manager) SetCheckpointStore(cs *storage.CheckpointStore) {
+ m.checkpointStore = cs
+}
+
// GoldenVersion returns the hash identifying this worker's golden snapshot base image.
// Empty string means no golden snapshot is available.
func (m *Manager) GoldenVersion() string {
@@ -308,6 +315,8 @@ func (m *Manager) PrepareGoldenSnapshot() error {
}
}
log.Printf("qemu: golden snapshot already exists at %s (CID=%d, guestIP=%s, version=%s)", goldenDir, m.goldenCID, m.goldenGuestIP, m.goldenVersion)
+ go m.uploadBaseImageIfNew(m.goldenVersion)
+ go m.migrateStaleCheckpoints()
return nil
}
@@ -541,6 +550,8 @@ func (m *Manager) PrepareGoldenSnapshot() error {
_ = os.WriteFile(filepath.Join(goldenDir, "host_ip"), []byte(netCfg.HostIP), 0644)
log.Printf("qemu: golden snapshot ready (%dms total, mem=%s, CID=%d, guestIP=%s, version=%s)",
time.Since(t0).Milliseconds(), memFile, goldenCID, netCfg.GuestIP, m.goldenVersion)
+ go m.uploadBaseImageIfNew(m.goldenVersion)
+ go m.migrateStaleCheckpoints()
return nil
}
@@ -2136,17 +2147,18 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)
meta := &SnapshotMeta{
- SandboxID: vm.ID,
- Network: vm.network,
- GuestCID: vm.guestCID,
- GuestMAC: vm.guestMAC,
- BootArgs: vm.bootArgs,
- CpuCount: vm.CpuCount,
- MemoryMB: vm.MemoryMB,
- BaseMemoryMB: vm.baseMemoryMB,
- Template: vm.Template,
- GuestPort: vm.GuestPort,
- SnapshotedAt: time.Now(),
+ SandboxID: vm.ID,
+ Network: vm.network,
+ GuestCID: vm.guestCID,
+ GuestMAC: vm.guestMAC,
+ BootArgs: vm.bootArgs,
+ CpuCount: vm.CpuCount,
+ MemoryMB: vm.MemoryMB,
+ BaseMemoryMB: vm.baseMemoryMB,
+ Template: vm.Template,
+ GuestPort: vm.GuestPort,
+ GoldenVersion: vm.goldenVersion,
+ SnapshotedAt: time.Now(),
}
// Persist secrets proxy state so RestoreFromCheckpoint can re-register the session.
if m.secretsProxy != nil && vm.network != nil {
@@ -2227,6 +2239,11 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
}
defer vm.opMu.Unlock()
+ // Ensure checkpoint is compatible with current base image — rebases inline if needed.
+ if err := m.ensureCheckpointRebased(ctx, checkpointID); err != nil {
+ return fmt.Errorf("checkpoint %s: rebase failed: %w", checkpointID, err)
+ }
+
t0 := time.Now()
// Step 1: Kill the current VM
@@ -2498,6 +2515,12 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {
t0 := time.Now()
+ // Ensure checkpoint is compatible with current base image — rebases inline if needed.
+ // Return the error so we don't silently fork a stale checkpoint against the wrong base.
+ if err := m.ensureCheckpointRebased(ctx, checkpointID); err != nil {
+ return nil, fmt.Errorf("checkpoint %s: base migration failed: %w", checkpointID, err)
+ }
+
// Lock checkpoint cache for reading — prevents race with CreateCheckpoint writing cache
m.checkpointCacheMu.RLock()
cacheDir := m.checkpointCacheDir(checkpointID)