Skip to content

An open-source, faster Devin alternative

TypeScript

pin forks to the checkpoint's golden, not the workers

Brian Reardonbc300b5222ea
diff --git a/internal/qemu/checkpoint_rebase.go b/internal/qemu/checkpoint_rebase.go
index 50ee260e..f17f199c 100644
--- a/internal/qemu/checkpoint_rebase.go
+++ b/internal/qemu/checkpoint_rebase.go
@@ -72,7 +72,42 @@ func (m *Manager) ensureCheckpointRebased(ctx context.Context, checkpointID stri
// rebaseMetadataOnly runs qemu-img rebase -u to repoint an overlay's backing
// file without touching data clusters.
+//
+// rebase -u is UNSAFE: it trusts that newBasePath holds exactly the content the
+// overlay was built against and only rewrites the backing pointer. Handing it
+// the wrong base silently corrupts the guest filesystem (the overlay's clusters
+// index the old base's block layout). Two cheap guards before we pull that
+// trigger:
+// - Refuse if newBasePath's size != the overlay's virtual size. A size
+// mismatch is an unambiguously wrong base (different template / corrupt
+// golden); rebasing would guarantee corruption, so fail loud instead.
+// - Skip entirely if the overlay already backs onto newBasePath — no need to
+// re-run an unsafe op that would be a no-op.
+//
+// This does NOT catch a same-size, different-content base (golden skew); that is
+// prevented upstream by pinning the overlay to the golden it was actually built
+// on (see ForkFromCheckpoint stamping meta.GoldenVersion). This guard is
+// defense-in-depth for the grossly-wrong-base case and a safety net if a pin is
+// ever wrong again.
func rebaseMetadataOnly(ctx context.Context, overlayPath, newBasePath string) error {
+ // Best-effort guard: if we can read BOTH the target base's size and the
+ // overlay's virtual size and they disagree, the base is unambiguously wrong
+ // (different template / corrupt golden) — refuse rather than corrupt. If
+ // introspection is unavailable (qemu-img missing, unreadable overlay), fall
+ // through to the rebase; that's no worse than the pre-guard behavior. Also
+ // skip a rebase that would be a no-op (overlay already on newBasePath).
+ if baseInfo, statErr := os.Stat(newBasePath); statErr == nil {
+ if overlayVSize, verr := qcowVirtualSize(ctx, overlayPath); verr == nil {
+ if overlayVSize != baseInfo.Size() {
+ return fmt.Errorf(
+ "refusing unsafe rebase of %s onto %s: base size %d != overlay virtual size %d (wrong base image — recreate the checkpoint)",
+ filepath.Base(overlayPath), newBasePath, baseInfo.Size(), overlayVSize)
+ }
+ if cur, berr := qcowBackingFile(ctx, overlayPath); berr == nil && cur == newBasePath {
+ return nil // already correctly based
+ }
+ }
+ }
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)))
@@ -80,6 +115,37 @@ func rebaseMetadataOnly(ctx context.Context, overlayPath, newBasePath string) er
return nil
}
+// qcowVirtualSize returns a qcow2 image's virtual (guest-visible) size in bytes,
+// which must equal its backing file's size for the overlay to be valid.
+func qcowVirtualSize(ctx context.Context, path string) (int64, error) {
+ out, err := exec.CommandContext(ctx, "qemu-img", "info", "--output=json", path).Output()
+ if err != nil {
+ return 0, err
+ }
+ var info struct {
+ VirtualSize int64 `json:"virtual-size"`
+ }
+ if err := json.Unmarshal(out, &info); err != nil {
+ return 0, err
+ }
+ return info.VirtualSize, nil
+}
+
+// qcowBackingFile returns an overlay's current backing-file path ("" if none).
+func qcowBackingFile(ctx context.Context, path string) (string, error) {
+ out, err := exec.CommandContext(ctx, "qemu-img", "info", "--output=json", path).Output()
+ if err != nil {
+ return "", err
+ }
+ var info struct {
+ BackingFilename string `json:"backing-filename"`
+ }
+ if err := json.Unmarshal(out, &info); err != nil {
+ return "", err
+ }
+ return info.BackingFilename, nil
+}
+
// 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.
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 588d0ec1..363d275f 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -4110,6 +4110,23 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
qmpClient.Close()
cmd.Process.Kill()
cmd.Wait()
+ // Only fail-fast on DETERMINISTIC boot failure: the guest never
+ // reached userspace AND printed an explicit kernel/init panic — the
+ // fingerprint of a checkpoint rebased onto the wrong base golden,
+ // where retrying the same boot is pointless. A booted-but-slow guest
+ // (agent flake) or an ambiguous slow boot keeps the normal "agent
+ // connect" retry path. Log the serial tail whenever the guest didn't
+ // boot so operators can diagnose either way.
+ booted, sig, tail := classifyGuestBoot(sandboxDir)
+ if !booted && tail != "" {
+ log.Printf("qemu: ForkFromCheckpoint %s → %s: guest did not reach init-ready (sig=%q). serial tail:\n%s",
+ checkpointID, id, sig, tail)
+ }
+ if sig != "" {
+ return nil, nil, nil, fmt.Errorf(
+ "guest failed to boot (%s): checkpoint %s is likely pinned to the wrong base golden — recreate the checkpoint/template",
+ sig, checkpointID)
+ }
return nil, nil, nil, fmt.Errorf("agent connect: %w", err)
}
return cmd, qmpClient, agent, nil
@@ -4202,6 +4219,20 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
}
virtioMemAddedMB := alignVirtioMemBlock(desiredMemMB - memMB)
+ // A fork's disk sits on the CHECKPOINT's golden base, not necessarily this
+ // worker's current golden: ensureCheckpointRebased repointed the overlay to
+ // the base for meta.GoldenVersion (downloading an older base if the golden
+ // has since rolled). Stamping m.goldenVersion here is a latent corruption
+ // bug — a later disk_only checkpoint of this fork would inherit the wrong
+ // golden, and forking THAT would rebase the overlay (built on the old base)
+ // onto the new base, producing an inconsistent rootfs the guest can't mount
+ // ("agent not ready" on custom-template forks after a golden roll). Record
+ // the golden the disk actually rests on; fall back to the worker golden only
+ // for legacy checkpoints that never recorded one.
+ forkGolden := meta.GoldenVersion
+ if forkGolden == "" {
+ forkGolden = m.goldenVersion
+ }
vm := &VMInstance{
ID: id,
Template: meta.Template,
@@ -4225,7 +4256,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
guestCID: guestCID,
bootArgs: bootArgs,
agent: agent,
- goldenVersion: m.goldenVersion, // set on wake — VM uses the current base image
+ goldenVersion: forkGolden,
}
m.mu.Lock()
diff --git a/internal/qemu/rootfs_mount_hint_test.go b/internal/qemu/rootfs_mount_hint_test.go
new file mode 100644
index 00000000..29a07f25
--- /dev/null
+++ b/internal/qemu/rootfs_mount_hint_test.go
@@ -0,0 +1,77 @@
+package qemu
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestClassifyGuestBoot(t *testing.T) {
+ readyLine := "init: cgroup sandbox ready (pids=4096, mem=846261043, cpu=80000/100000)\n"
+
+ cases := []struct {
+ name string
+ log string
+ wantBooted bool
+ wantSig bool // whether an explicit failure signature is expected
+ }{
+ {
+ name: "healthy boot → booted, no failure",
+ log: "Run /sbin/init as init process\ninit: workspace mounted\n" + readyLine,
+ wantBooted: true,
+ wantSig: false,
+ },
+ {
+ // Regression guard: a guest that BOOTED but logged a survivable
+ // kernel message must NOT be flagged — else we'd suppress the
+ // legitimate agent-flake retry.
+ name: "booted despite an earlier survived EXT4-fs error → not flagged",
+ log: "EXT4-fs error (device vda): ext4_lookup: deleted inode referenced\n[recovered]\n" + readyLine,
+ wantBooted: true,
+ wantSig: false,
+ },
+ {
+ name: "rootfs mount failure, never booted → explicit signature",
+ log: "VFS: Cannot open root device or unknown-block\nunable to read superblock\n",
+ wantBooted: false,
+ wantSig: true,
+ },
+ {
+ name: "init-exec kernel panic, never booted → explicit signature",
+ log: "Run /sbin/init as init process\nKernel panic - not syncing: Attempted to kill init!\n",
+ wantBooted: false,
+ wantSig: true,
+ },
+ {
+ // Ambiguous: didn't reach the marker but no panic (e.g. a slow cold
+ // boot). Must stay retriable (sig empty) — no misleading fail-fast.
+ name: "slow boot, no marker, no panic → ambiguous, retriable",
+ log: "Booting the kernel\nEXT4-fs (vda): mounted filesystem\nRun /sbin/init as init process\n",
+ wantBooted: false,
+ wantSig: false,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "qemu.log"), []byte(tc.log), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ booted, sig, tail := classifyGuestBoot(dir)
+ if booted != tc.wantBooted {
+ t.Fatalf("booted=%v want %v (sig=%q)", booted, tc.wantBooted, sig)
+ }
+ if (sig != "") != tc.wantSig {
+ t.Fatalf("sig=%q, wanted signature present=%v", sig, tc.wantSig)
+ }
+ if tail == "" {
+ t.Fatalf("expected a non-empty serial tail")
+ }
+ })
+ }
+
+ // Missing log: no failure, no panic (nothing to diagnose).
+ if booted, sig, _ := classifyGuestBoot(t.TempDir()); booted || sig != "" {
+ t.Fatalf("expected booted=false, sig=empty for absent qemu.log; got booted=%v sig=%q", booted, sig)
+ }
+}
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index b722f7b8..fdf423e8 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -770,6 +770,75 @@ func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout i
return sb, err
}
+// guestBootMarker is the last line the in-guest init prints before the agent
+// starts accepting. Its presence means the guest reached a healthy userspace;
+// its ABSENCE after an agent timeout means the guest never finished booting.
+const guestBootMarker = "cgroup sandbox ready"
+
+// classifyGuestBoot inspects a VM's qemu serial log after an agent-connect
+// timeout to tell apart three cases, so the caller can retry safely and only
+// fail-fast on deterministic corruption:
+//
+// - booted=true: the guest reached healthy userspace (guestBootMarker present).
+// The agent socket just wasn't ready in time — a transient virtio-serial
+// flake. Caller should RETRY. Precedence matters: a booted guest is never
+// flagged as a failure even if an earlier, survived kernel message matches a
+// signature (else we'd suppress a legitimate retry).
+// - booted=false, sig!="": the guest did NOT boot AND an explicit kernel/init
+// failure signature is present — deterministic (a rootfs rebased onto the
+// wrong base golden can't mount root or exec init). Caller should FAIL FAST
+// with an actionable error; retrying the same boot is pointless.
+// - booted=false, sig=="": the guest didn't reach the marker but printed no
+// explicit failure — ambiguous (e.g. an unusually slow cold boot). Caller
+// should keep the normal RETRY path; we only log the tail for diagnosis.
+//
+// tail is the last serial lines, for the worker log.
+func classifyGuestBoot(sandboxDir string) (booted bool, sig, tail string) {
+ data, err := os.ReadFile(filepath.Join(sandboxDir, "qemu.log"))
+ if err != nil {
+ return false, "", ""
+ }
+ s := string(data)
+ tail = lastLines(s, 12)
+
+ // Reaching the in-guest init's ready marker means userspace came up healthy,
+ // whatever transient messages appeared earlier — treat as a bootable guest.
+ if strings.Contains(s, guestBootMarker) {
+ return true, "", tail
+ }
+ // Guest did not finish booting — look for an explicit failure signature
+ // (rootfs mount failure from metadata corruption, or an init-exec failure
+ // from corrupt base binaries) to classify it as deterministic.
+ for _, m := range []string{
+ "Unable to mount root fs",
+ "Cannot open root device",
+ "unable to read superblock",
+ "EXT4-fs error",
+ "Attempted to kill init",
+ "No working init found",
+ "Failed to execute",
+ "Kernel panic",
+ "segfault",
+ } {
+ if strings.Contains(s, m) {
+ return false, m, tail
+ }
+ }
+ return false, "", tail
+}
+
+// lastLines returns up to n trailing non-empty lines of s.
+func lastLines(s string, n int) string {
+ lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
+ out := make([]string, 0, n)
+ for i := len(lines) - 1; i >= 0 && len(out) < n; i-- {
+ if strings.TrimSpace(lines[i]) != "" {
+ out = append([]string{lines[i]}, out...)
+ }
+ }
+ return strings.Join(out, "\n")
+}
+
func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, timeout int) (*types.Sandbox, error) {
sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
workspacePath := detectDrivePath(sandboxDir, "workspace")