Skip to content

An open-source, faster Devin alternative

TypeScript

ecover corrupt wakes cross worker, single-flight wake, longer recovery boot timeout, and wake failure/recovery metrics

Brian Reardon5850e3d9c7f5
diff --git a/go.mod b/go.mod
index 283ba91f..7659c2d7 100644
--- a/go.mod
+++ b/go.mod
@@ -32,6 +32,7 @@ require (
github.com/spf13/cobra v1.10.2
github.com/stripe/stripe-go/v82 v82.5.1
github.com/workos/workos-go/v4 v4.46.1
+ golang.org/x/sync v0.20.0
golang.org/x/sys v0.42.0
golang.org/x/term v0.40.0
google.golang.org/grpc v1.69.4
@@ -89,7 +90,6 @@ require (
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.47.0 // indirect
golang.org/x/net v0.49.0 // indirect
- golang.org/x/sync v0.20.0 // indirect
golang.org/x/text v0.33.0 // indirect
golang.org/x/time v0.8.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go
index 54a78aea..330c4bd0 100644
--- a/internal/metrics/metrics.go
+++ b/internal/metrics/metrics.go
@@ -60,6 +60,29 @@ var (
[]string{"region", "template", "status"},
)
+ // WakeFailuresTotal counts wakes that ultimately failed (after any
+ // corruption-recovery attempt), classified by reason. reason values:
+ // corruption, recovery_failed, agent_timeout, checkpoint_missing,
+ // s3_download, rebase, other.
+ WakeFailuresTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "opensandbox_wake_failures_total",
+ Help: "Hibernate-wake failures by classified reason",
+ },
+ []string{"region", "template", "reason"},
+ )
+
+ // WakeRecoveryTotal counts corrupt-wake recovery outcomes so latent
+ // savevm corruption is visible even when recovery succeeds. outcome
+ // values: detected, recovered_stage1, recovered_stage2, failed.
+ WakeRecoveryTotal = prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "opensandbox_wake_recovery_total",
+ Help: "Corrupt-wake recovery outcomes (savevm corruption fallback path)",
+ },
+ []string{"region", "outcome"},
+ )
+
// source=warm_cache: local snapshot reused. source=s3: downloaded archive.
WakeDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
@@ -218,6 +241,8 @@ func init() {
CheckpointFailuresTotal,
HibernateDuration,
WakeDuration,
+ WakeFailuresTotal,
+ WakeRecoveryTotal,
ExecDuration,
PTYSessionsActive,
WorkerUtilization,
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 2132243d..a2fce4a6 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -20,6 +20,8 @@ import (
"time"
"github.com/google/uuid"
+ "golang.org/x/sync/singleflight"
+
"github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/sandbox"
@@ -327,6 +329,13 @@ type Manager struct {
nextCID uint32
uploadWg sync.WaitGroup
+ // wakeSF collapses concurrent Wake calls for the same sandbox into a
+ // single doWake execution (all callers share its result). Without this,
+ // a control-plane wake retry that fires while the first wake is still
+ // running spawns a second QEMU + a second corrupt-wake recovery on the
+ // same sandbox dir — racing on rootfs.qcow2 and contending for the host.
+ wakeSF singleflight.Group
+
// Checkpoint cache mutex: write-locked during cache creation, read-locked during fork
checkpointCacheMu sync.RWMutex
@@ -2818,10 +2827,19 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey stri
metrics.WakeDuration.WithLabelValues(m.cfg.Region, template, "s3", status).Observe(time.Since(t0).Seconds())
}()
- sb, err := m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
+ // Single-flight: concurrent wakes for the same sandbox (e.g. a control-plane
+ // retry firing before the first completes) collapse into one doWake; all
+ // callers share its result instead of racing a second recovery.
+ res, err, _ := m.wakeSF.Do(sandboxID, func() (interface{}, error) {
+ return m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)
+ })
if err != nil {
+ reason := classifyWakeFailure(err)
+ metrics.WakeFailuresTotal.WithLabelValues(m.cfg.Region, "unknown", reason).Inc()
+ log.Printf("wake-metric: outcome=failure sandbox=%s source=s3 reason=%s err=%q", sandboxID, reason, err.Error())
return nil, err
}
+ sb, _ = res.(*types.Sandbox)
// Notify billing observer AFTER wake succeeds so it resets per-sandbox
// state. Hibernation time should not be billed as compute — the next
// periodic tick will attribute from the wake-fresh start, not from the
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index f780b7be..4e996268 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -13,6 +13,7 @@ import (
"syscall"
"time"
+ "github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
@@ -565,6 +566,8 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
// their workspace files but loses running process state.
if err := m.verifyWakeIntegrity(context.Background(), sandboxID, agentClient); err != nil {
log.Printf("qemu: wake %s: %v — falling back to cold boot", sandboxID, err)
+ metrics.WakeRecoveryTotal.WithLabelValues(m.cfg.Region, "detected").Inc()
+ log.Printf("wake-metric: outcome=corruption-detected sandbox=%s", sandboxID)
_ = agentClient.Close()
qmpClient.Close()
cmd.Process.Kill()
@@ -699,6 +702,8 @@ func (m *Manager) recoverCorruptWake(ctx context.Context, sandboxID string, time
}
if verr := m.verifyWakeIntegrity(ctx, sandboxID, agent); verr == nil {
log.Printf("qemu: recover %s: stage 1 succeeded (memory-only corruption; rootfs kept)", sandboxID)
+ metrics.WakeRecoveryTotal.WithLabelValues(m.cfg.Region, "recovered_stage1").Inc()
+ log.Printf("wake-metric: outcome=recovered stage=1 sandbox=%s", sandboxID)
return sb, nil
}
log.Printf("qemu: recover %s: cold boot from existing rootfs still fails integrity — rootfs is corrupt on disk", sandboxID)
@@ -715,15 +720,21 @@ func (m *Manager) recoverCorruptWake(ctx context.Context, sandboxID string, time
rootfsPath := detectDrivePath(sandboxDir, "rootfs")
if fileExists(rootfsPath) {
if rerr := os.Remove(rootfsPath); rerr != nil {
+ metrics.WakeRecoveryTotal.WithLabelValues(m.cfg.Region, "failed").Inc()
+ log.Printf("wake-metric: outcome=recovery-failed sandbox=%s err=%q", sandboxID, rerr.Error())
return nil, fmt.Errorf("recover %s: remove corrupt rootfs: %w", sandboxID, rerr)
}
log.Printf("qemu: recover %s: stage 2 — discarded corrupt rootfs %s (workspace kept; installed packages lost)", sandboxID, rootfsPath)
}
sb, err = m.coldBootLocal(ctx, sandboxID, timeout)
if err != nil {
+ metrics.WakeRecoveryTotal.WithLabelValues(m.cfg.Region, "failed").Inc()
+ log.Printf("wake-metric: outcome=recovery-failed sandbox=%s err=%q", sandboxID, err.Error())
return nil, fmt.Errorf("recover %s: cold boot after rootfs rebuild: %w", sandboxID, err)
}
log.Printf("qemu: recover %s: stage 2 succeeded — rootfs rebuilt from template, workspace intact", sandboxID)
+ metrics.WakeRecoveryTotal.WithLabelValues(m.cfg.Region, "recovered_stage2").Inc()
+ log.Printf("wake-metric: outcome=recovered stage=2 sandbox=%s", sandboxID)
return sb, nil
}
@@ -732,6 +743,12 @@ func (m *Manager) recoverCorruptWake(ctx context.Context, sandboxID string, time
// start and any failure must be visible in the journal — a silent error here
// previously left wake failures looping with no trace of why the fallback
// never produced a VM.
+// recoveryColdBootAgentWait is how long a recovery cold boot waits for the
+// in-VM agent before giving up. Deliberately longer than the normal 30s boot
+// wait: every coldBootLocal caller is a recovery/fallback path, and a
+// premature timeout here escalates to a destructive rootfs rebuild.
+const recoveryColdBootAgentWait = 90 * time.Second
+
func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout int) (*types.Sandbox, error) {
log.Printf("qemu: cold-boot-local %s: starting", sandboxID)
sb, err := m.coldBootLocalInner(ctx, sandboxID, timeout)
@@ -788,6 +805,13 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, time
}
if !fileExists(rootfsPath) {
+ // PrepareRootfs emits a qcow2 overlay, so the rebuilt rootfs must land
+ // at rootfs.qcow2 — otherwise detectDrivePath's .ext4 fallback (which
+ // fires once stage-2 recovery has discarded rootfs.qcow2) names the
+ // qcow2 file rootfs.ext4, and buildQEMUArgs then attaches it as raw.
+ // The guest kernel reads the qcow2 header as the filesystem, fails to
+ // mount root, and the agent never comes up (30s socket timeout).
+ rootfsPath = filepath.Join(sandboxDir, "rootfs.qcow2")
baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, meta.Template)
if err != nil {
return nil, fmt.Errorf("resolve base image: %w", err)
@@ -914,7 +938,13 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, time
goldenVersion: m.goldenVersion, // cold boot: VM runs on the current worker's base
}
- agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)
+ // Generous agent wait: coldBootLocalInner is only reached on the
+ // corrupt-wake / loadvm-failure recovery paths, where the alternative to
+ // waiting is escalating to a destructive rootfs rebuild (stage 2, which
+ // discards the customer's installed packages). A few extra seconds on a
+ // rare path is far cheaper than that escalation, and a healthy worker
+ // still connects in ~1.5s — the longer ceiling only bites under load.
+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, recoveryColdBootAgentWait)
if err != nil {
cmd.Process.Kill()
cmd.Wait()
@@ -1067,3 +1097,30 @@ func waitForQMP(socketPath string, timeout time.Duration) (*QMPClient, error) {
}
return nil, fmt.Errorf("QMP socket %s not ready after %v", socketPath, timeout)
}
+
+// classifyWakeFailure maps a wake error to a stable reason label for the
+// WakeFailuresTotal metric and the wake-metric log event. Mirrors the
+// worker-side classifier (internal/worker) intentionally; kept package-local
+// to avoid a cross-package import just for a label string.
+func classifyWakeFailure(err error) string {
+ if err == nil {
+ return "other"
+ }
+ s := strings.ToLower(err.Error())
+ switch {
+ case strings.Contains(s, "bad message"), strings.Contains(s, "metadata_csum"), strings.Contains(s, "corrupt"):
+ return "corruption"
+ case strings.Contains(s, "snapshot-meta"), strings.Contains(s, "sandbox-meta"), strings.Contains(s, "rebuild"):
+ return "recovery_failed"
+ case strings.Contains(s, "agent not ready"), strings.Contains(s, "agent.sock"):
+ return "agent_timeout"
+ case strings.Contains(s, "no s3 key"), strings.Contains(s, "not in local cache"), strings.Contains(s, "not found in cache"), strings.Contains(s, "object not found"):
+ return "checkpoint_missing"
+ case strings.Contains(s, "download"):
+ return "s3_download"
+ case strings.Contains(s, "rebase"):
+ return "rebase"
+ default:
+ return "other"
+ }
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 91d023cc..40110034 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -231,6 +231,16 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
observeWake := func(source, status string) {
metrics.WakeDuration.WithLabelValues(s.region, cfg.Template, source, status).Observe(time.Since(tWake).Seconds())
}
+ // failWake records a wake failure: the duration observation, the
+ // classified failure counter, and a single structured "wake-metric"
+ // log line that the Axiom dashboard aggregates on.
+ failWake := func(source string, err error) {
+ observeWake(source, "failure")
+ reason := classifyWakeFailure(err)
+ metrics.WakeFailuresTotal.WithLabelValues(s.region, cfg.Template, reason).Inc()
+ log.Printf("wake-metric: outcome=failure sandbox=%s template=%s source=%s reason=%s err=%q",
+ req.SandboxId, cfg.Template, source, reason, err.Error())
+ }
sb, err := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)
if err == nil {
@@ -261,8 +271,9 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
// Some other error (rebase failure, agent reconnect, etc.).
// Don't try to mask it — return the real reason. Attribute as
// warm_cache failure since we never got to the S3 path.
- observeWake("warm_cache", "failure")
- return nil, fmt.Errorf("fork from checkpoint %s: %w", req.CheckpointId, err)
+ e := fmt.Errorf("fork from checkpoint %s: %w", req.CheckpointId, err)
+ failWake("warm_cache", e)
+ return nil, e
}
if req.TemplateRootfsKey == "" || s.checkpointStore == nil {
// We can't recover this fork — the controlplane gave us a
@@ -273,18 +284,21 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
// symptom Oliviero hit on a checkpoint whose DB row had
// empty rootfs_s3_key. Fail loud instead so the customer (and
// us) sees an actionable error rather than a corrupt sandbox.
- observeWake("s3", "failure")
- return nil, fmt.Errorf("fork from checkpoint %s: not in local cache and no S3 key to recover from (DB row may be missing rootfs_s3_key)", req.CheckpointId)
+ e := fmt.Errorf("fork from checkpoint %s: not in local cache and no S3 key to recover from (DB row may be missing rootfs_s3_key)", req.CheckpointId)
+ failWake("s3", e)
+ return nil, e
}
log.Printf("grpc: warm fork %s: not in local cache, downloading from S3", req.CheckpointId)
if dlErr := s.downloadFullCheckpoint(ctx, req.CheckpointId, req.TemplateRootfsKey); dlErr != nil {
- observeWake("s3", "failure")
- return nil, fmt.Errorf("fork from checkpoint %s: cache miss + S3 download failed: %w", req.CheckpointId, dlErr)
+ e := fmt.Errorf("fork from checkpoint %s: cache miss + S3 download failed: %w", req.CheckpointId, dlErr)
+ failWake("s3", e)
+ return nil, e
}
sb, retryErr := s.manager.ForkFromCheckpoint(ctx, req.CheckpointId, cfg)
if retryErr != nil {
- observeWake("s3", "failure")
- return nil, fmt.Errorf("fork from checkpoint %s: retry after S3 download failed: %w", req.CheckpointId, retryErr)
+ e := fmt.Errorf("fork from checkpoint %s: retry after S3 download failed: %w", req.CheckpointId, retryErr)
+ failWake("s3", e)
+ return nil, e
}
observeWake("s3", "success")
if s.router != nil {
@@ -1331,3 +1345,29 @@ func (s *GRPCServer) GetSandboxStats(ctx context.Context, req *pb.GetSandboxStat
Pids: int32(stats.PIDs),
}, nil
}
+
+// classifyWakeFailure maps a wake error to a stable reason label for the
+// WakeFailuresTotal metric and the wake-metric log event. Order matters:
+// more specific signatures are checked first.
+func classifyWakeFailure(err error) string {
+ if err == nil {
+ return "other"
+ }
+ s := strings.ToLower(err.Error())
+ switch {
+ case strings.Contains(s, "bad message"), strings.Contains(s, "metadata_csum"), strings.Contains(s, "corrupt"):
+ return "corruption"
+ case strings.Contains(s, "snapshot-meta"), strings.Contains(s, "sandbox-meta"), strings.Contains(s, "rebuild"):
+ return "recovery_failed"
+ case strings.Contains(s, "agent not ready"), strings.Contains(s, "agent.sock"):
+ return "agent_timeout"
+ case strings.Contains(s, "no s3 key"), strings.Contains(s, "not in local cache"), strings.Contains(s, "not found in cache"):
+ return "checkpoint_missing"
+ case strings.Contains(s, "download"):
+ return "s3_download"
+ case strings.Contains(s, "rebase"):
+ return "rebase"
+ default:
+ return "other"
+ }
+}