An open-source, faster Devin alternative
TypeScript
freeze the guest rootfs through a redialed agent channel before savevm so paused→deep hibernations stop capturing a torn ext4 (the prod wake-corruption root cause), add a control-plane reconciler plus worker retry to recover stuck hibernation-upload rows, and key scaler disk-pressure off the /data mount instead of the OS root
Brian Reardon48657ab5f2a8
diff --git a/cmd/server/main.go b/cmd/server/main.goindex eaf3f0d9..25a09501 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -815,6 +815,28 @@ func main() {}}+ // Hibernation-upload reconciler — safety net for lost upload-completion+ // bookkeeping. The worker records uploaded_at / upload_error from an async+ // goroutine after the S3 upload finishes; if that write is lost (transient DB+ // error, or the worker torn down mid-drain before it lands) the row is stuck+ // with NEITHER set, which both strands the box (un-wakeable despite the blob+ // being in S3) and wedges worker teardown (the scaler gates drain on+ // CountPendingHibernationUploads == 0). Every 2m this resolves stuck rows+ // against the checkpoint store: present -> uploaded_at, absent -> upload_error.+ if opts.Store != nil && opts.CheckpointStore != nil {+ hibRec := controlplane.NewHibernationUploadReconciler(controlplane.HibernationUploadReconcilerConfig{+ Store: opts.Store,+ Blobs: opts.CheckpointStore,+ })+ hibRec.Start(ctx)+ defer func() {+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer stopCancel()+ _ = hibRec.Stop(stopCtx)+ }()+ log.Printf("opensandbox: hibernation-upload reconciler started (period=2m, grace=15m)")+ }+// Usage-parity checker — shadow-parity gate for the Pro-billing edge// cutover. Hourly, compares edge-measured GB-seconds (tick samples) against// cell sandbox_scale_events and logs per-org drift. Read-only; never bills.diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 8c0b899a..dc4880c3 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -523,17 +523,27 @@ func main() {if qemuMgr != nil {st := store // capture for closureqemuMgr.SetHibernationUploadCallback(func(sandboxID, hibernationKey string, sizeBytes int64, uploadErr error) {- ctx2, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- if uploadErr != nil {- if err := st.MarkHibernationUploadFailed(ctx2, hibernationKey, uploadErr.Error()); err != nil {- log.Printf("opensandbox-worker: failed to record hibernation upload error for %s: %v", sandboxID, err)+ // Retry the terminal-state write: losing it strands the box+ // (un-wakeable) AND wedges worker teardown, so it's worth a few+ // attempts. The CP-side hibernation-upload reconciler is the+ // durable backstop if the worker dies before this lands.+ write := func() error {+ ctx2, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if uploadErr != nil {+ return st.MarkHibernationUploadFailed(ctx2, hibernationKey, uploadErr.Error())}- return+ return st.MarkHibernationUploaded(ctx2, hibernationKey, sizeBytes)}- if err := st.MarkHibernationUploaded(ctx2, hibernationKey, sizeBytes); err != nil {- log.Printf("opensandbox-worker: failed to mark hibernation uploaded for %s: %v", sandboxID, err)+ var werr error+ for attempt := 1; attempt <= 4; attempt++ {+ if werr = write(); werr == nil {+ return+ }+ log.Printf("opensandbox-worker: hibernation upload-status write for %s failed (attempt %d/4): %v", sandboxID, attempt, werr)+ time.Sleep(time.Duration(attempt) * time.Second)}+ log.Printf("opensandbox-worker: CRITICAL: hibernation upload-status write for %s abandoned after retries: %v (CP reconciler will resolve)", sandboxID, werr)})}}@@ -726,7 +736,11 @@ func main() {} else {count, _ = mgr.Count(context.Background())}- cpuPct, memPct, diskPct := worker.SystemStats()+ // Disk pressure keys off the DATA mount (cfg.DataDir → /data),+ // NOT the OS root: the root's static ~70% install footprint would+ // otherwise trip perpetual scale-up / eviction / routing exclusion+ // while /data sits nearly empty.+ cpuPct, memPct, diskPct := worker.SystemStats(cfg.DataDir)return cfg.MaxCapacity, count, cpuPct, memPct, diskPct})if qemuMgr != nil {diff --git a/internal/controlplane/hibernation_upload_reconciler.go b/internal/controlplane/hibernation_upload_reconciler.gonew file mode 100644index 00000000..51a3a192--- /dev/null+++ b/internal/controlplane/hibernation_upload_reconciler.go@@ -0,0 +1,185 @@+package controlplane++import (+ "context"+ "log"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+)++// hibUploadReconcilerStore is the DB surface the reconciler needs.+type hibUploadReconcilerStore interface {+ ListStuckHibernationUploads(ctx context.Context, olderThan time.Time, limit int) ([]db.StuckHibernationUpload, error)+ MarkHibernationUploaded(ctx context.Context, hibernationKey string, sizeBytes int64) error+ MarkHibernationUploadFailed(ctx context.Context, hibernationKey, errMsg string) error+}++// hibUploadBlobStat checks the checkpoint store for a blob's presence + size.+type hibUploadBlobStat interface {+ Stat(ctx context.Context, key string) (size int64, exists bool, err error)+}++// HibernationUploadReconciler is the safety net for hibernation-upload bookkeeping.+//+// The worker records uploaded_at / upload_error from an async goroutine after the+// S3 archive upload finishes (qemu/snapshot.go -> the worker callback). If that+// write is lost — a transient DB error, or the worker being torn down mid-drain+// before the write lands — the sandbox_hibernations row is left stuck with+// NEITHER field set. Two bad consequences:+//+// - The box is silently un-wakeable even though its blob is safely in S3.+// - Worker teardown wedges forever: the scaler gates draining a worker on+// CountPendingHibernationUploads == 0, so one stuck row can freeze the whole+// fleet's rolling replace.+//+// Every period this reconciler finds rows with no terminal upload state, older+// than a grace window (well past the upload timeout so it never races an+// in-flight upload), and resolves each against the checkpoint store:+//+// blob present -> MarkHibernationUploaded (recover — the write was just lost)+// blob absent -> MarkHibernationUploadFailed (record the loss so the drain proceeds)+//+// Idempotent and self-healing; it also mops up historical orphans left by the+// same class of lost write on workers that are long gone.+type HibernationUploadReconciler struct {+ store hibUploadReconcilerStore+ blobs hibUploadBlobStat+ period time.Duration+ grace time.Duration+ batch int++ stopCh chan struct{}+ doneCh chan struct{}+ once sync.Once+}++// HibernationUploadReconcilerConfig configures the reconciler.+type HibernationUploadReconcilerConfig struct {+ Store hibUploadReconcilerStore+ Blobs hibUploadBlobStat+ Period time.Duration // default 2m+ Grace time.Duration // default 15m (well past the ~5m upload timeout)+ Batch int // max rows resolved per tick, default 200+}++// NewHibernationUploadReconciler returns nil if Store or Blobs is missing, so the+// caller can safely `.Start()` the result unconditionally.+func NewHibernationUploadReconciler(cfg HibernationUploadReconcilerConfig) *HibernationUploadReconciler {+ if cfg.Store == nil || cfg.Blobs == nil {+ return nil+ }+ if cfg.Period == 0 {+ cfg.Period = 2 * time.Minute+ }+ if cfg.Grace == 0 {+ cfg.Grace = 15 * time.Minute+ }+ if cfg.Batch == 0 {+ cfg.Batch = 200+ }+ return &HibernationUploadReconciler{+ store: cfg.Store,+ blobs: cfg.Blobs,+ period: cfg.Period,+ grace: cfg.Grace,+ batch: cfg.Batch,+ stopCh: make(chan struct{}),+ doneCh: make(chan struct{}),+ }+}++// Start begins the reconcile loop. No-op on a nil receiver.+func (r *HibernationUploadReconciler) Start(ctx context.Context) {+ if r == nil {+ return+ }+ go r.run(ctx)+}++// Stop gracefully shuts down.+func (r *HibernationUploadReconciler) Stop(ctx context.Context) error {+ if r == nil {+ return nil+ }+ r.once.Do(func() { close(r.stopCh) })+ select {+ case <-r.doneCh:+ case <-ctx.Done():+ return ctx.Err()+ }+ return nil+}++func (r *HibernationUploadReconciler) run(ctx context.Context) {+ defer close(r.doneCh)+ ticker := time.NewTicker(r.period)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-r.stopCh:+ return+ case <-ticker.C:+ r.tick(ctx)+ }+ }+}++// tick performs one reconciliation pass.+func (r *HibernationUploadReconciler) tick(ctx context.Context) {+ cutoff := time.Now().Add(-r.grace)+ stuck, err := r.store.ListStuckHibernationUploads(ctx, cutoff, r.batch)+ if err != nil {+ log.Printf("hib_upload_reconciler: list stuck uploads failed: %v", err)+ return+ }+ if len(stuck) == 0 {+ return+ }++ var recovered, lost, errs int+ for _, h := range stuck {+ select {+ case <-ctx.Done():+ return+ case <-r.stopCh:+ return+ default:+ }++ sCtx, cancel := context.WithTimeout(ctx, 15*time.Second)+ size, exists, serr := r.blobs.Stat(sCtx, h.HibernationKey)+ cancel()+ if serr != nil {+ // Transient (network/S3) — leave the row for the next tick.+ errs+++ log.Printf("hib_upload_reconciler: stat %s failed: %v (retry next tick)", h.HibernationKey, serr)+ continue+ }++ mCtx, mcancel := context.WithTimeout(ctx, 10*time.Second)+ if exists {+ if err := r.store.MarkHibernationUploaded(mCtx, h.HibernationKey, size); err != nil {+ errs+++ log.Printf("hib_upload_reconciler: mark uploaded %s failed: %v", h.HibernationKey, err)+ } else {+ recovered+++ }+ } else {+ if err := r.store.MarkHibernationUploadFailed(mCtx, h.HibernationKey,+ "reconciler: checkpoint blob absent after grace window; upload never completed"); err != nil {+ errs+++ log.Printf("hib_upload_reconciler: mark failed %s failed: %v", h.HibernationKey, err)+ } else {+ lost+++ }+ }+ mcancel()+ }++ log.Printf("hib_upload_reconciler: resolved %d stuck hibernation uploads (recovered=%d lost=%d errors=%d considered=%d)",+ recovered+lost, recovered, lost, errs, len(stuck))+}diff --git a/internal/controlplane/hibernation_upload_reconciler_test.go b/internal/controlplane/hibernation_upload_reconciler_test.gonew file mode 100644index 00000000..3018158c--- /dev/null+++ b/internal/controlplane/hibernation_upload_reconciler_test.go@@ -0,0 +1,183 @@+package controlplane++import (+ "context"+ "errors"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+)++// --- Mocks ---++type fakeHibStore struct {+ stuck []db.StuckHibernationUpload+ uploaded map[string]int64 // key -> size recorded via MarkHibernationUploaded+ failed map[string]string // key -> errMsg recorded via MarkHibernationUploadFailed+ listErr error+ markErr error+}++func newFakeHibStore(stuck ...db.StuckHibernationUpload) *fakeHibStore {+ return &fakeHibStore{stuck: stuck, uploaded: map[string]int64{}, failed: map[string]string{}}+}++func (f *fakeHibStore) ListStuckHibernationUploads(_ context.Context, _ time.Time, _ int) ([]db.StuckHibernationUpload, error) {+ if f.listErr != nil {+ return nil, f.listErr+ }+ return f.stuck, nil+}++func (f *fakeHibStore) MarkHibernationUploaded(_ context.Context, key string, size int64) error {+ if f.markErr != nil {+ return f.markErr+ }+ f.uploaded[key] = size+ return nil+}++func (f *fakeHibStore) MarkHibernationUploadFailed(_ context.Context, key, msg string) error {+ if f.markErr != nil {+ return f.markErr+ }+ f.failed[key] = msg+ return nil+}++type fakeBlobStat struct {+ present map[string]int64 // key -> size (blob exists)+ statErr map[string]error // key -> transient stat error+}++func (f *fakeBlobStat) Stat(_ context.Context, key string) (int64, bool, error) {+ if e := f.statErr[key]; e != nil {+ return 0, false, e+ }+ if sz, ok := f.present[key]; ok {+ return sz, true, nil+ }+ return 0, false, nil+}++func stuckRow(key string) db.StuckHibernationUpload {+ return db.StuckHibernationUpload{SandboxID: "sb-" + key, HibernationKey: "checkpoints/sb-" + key + "/1.tar.zst", HibernatedAt: time.Unix(1, 0)}+}++func newRec(store hibUploadReconcilerStore, blobs hibUploadBlobStat) *HibernationUploadReconciler {+ return NewHibernationUploadReconciler(HibernationUploadReconcilerConfig{Store: store, Blobs: blobs})+}++// --- Tests ---++// Blob present -> the lost write is recovered by stamping uploaded_at with the real size.+func TestHibReconciler_RecoversWhenBlobPresent(t *testing.T) {+ row := stuckRow("aaa")+ store := newFakeHibStore(row)+ blobs := &fakeBlobStat{present: map[string]int64{row.HibernationKey: 4096}}++ newRec(store, blobs).tick(context.Background())++ if got, ok := store.uploaded[row.HibernationKey]; !ok || got != 4096 {+ t.Fatalf("expected MarkHibernationUploaded(%s, 4096), got size=%d ok=%v", row.HibernationKey, got, ok)+ }+ if _, ok := store.failed[row.HibernationKey]; ok {+ t.Fatalf("a present blob must not be marked failed")+ }+}++// Blob absent after the grace window -> record the loss so the drain proceeds.+func TestHibReconciler_MarksFailedWhenBlobAbsent(t *testing.T) {+ row := stuckRow("bbb")+ store := newFakeHibStore(row)+ blobs := &fakeBlobStat{} // nothing present++ newRec(store, blobs).tick(context.Background())++ if msg, ok := store.failed[row.HibernationKey]; !ok || msg == "" {+ t.Fatalf("expected MarkHibernationUploadFailed for absent blob, ok=%v msg=%q", ok, msg)+ }+ if _, ok := store.uploaded[row.HibernationKey]; ok {+ t.Fatalf("an absent blob must not be marked uploaded")+ }+}++// A transient Stat error must leave the row untouched for the next tick — never+// mark a row failed just because S3 hiccuped (that would strand a recoverable box).+func TestHibReconciler_LeavesRowOnStatError(t *testing.T) {+ row := stuckRow("ccc")+ store := newFakeHibStore(row)+ blobs := &fakeBlobStat{statErr: map[string]error{row.HibernationKey: errors.New("s3 timeout")}}++ newRec(store, blobs).tick(context.Background())++ if _, ok := store.uploaded[row.HibernationKey]; ok {+ t.Fatalf("stat error must not mark uploaded")+ }+ if _, ok := store.failed[row.HibernationKey]; ok {+ t.Fatalf("stat error must not mark failed — row is left for retry")+ }+}++// A mixed batch routes each row independently: present->uploaded, absent->failed,+// error->untouched.+func TestHibReconciler_MixedBatch(t *testing.T) {+ ok, gone, flaky := stuckRow("ok"), stuckRow("gone"), stuckRow("flaky")+ store := newFakeHibStore(ok, gone, flaky)+ blobs := &fakeBlobStat{+ present: map[string]int64{ok.HibernationKey: 123},+ statErr: map[string]error{flaky.HibernationKey: errors.New("net")},+ }++ newRec(store, blobs).tick(context.Background())++ if store.uploaded[ok.HibernationKey] != 123 {+ t.Errorf("present row not recovered: %v", store.uploaded)+ }+ if _, ok := store.failed[gone.HibernationKey]; !ok {+ t.Errorf("absent row not marked failed: %v", store.failed)+ }+ if _, up := store.uploaded[flaky.HibernationKey]; up {+ t.Errorf("flaky row should be untouched")+ }+ if _, fl := store.failed[flaky.HibernationKey]; fl {+ t.Errorf("flaky row should be untouched")+ }+}++// Empty stuck list is a clean no-op (no store writes).+func TestHibReconciler_EmptyListNoOp(t *testing.T) {+ store := newFakeHibStore()+ newRec(store, &fakeBlobStat{}).tick(context.Background())+ if len(store.uploaded)+len(store.failed) != 0 {+ t.Fatalf("empty list must not write to store")+ }+}++// A list error is swallowed (logged) — the tick returns without touching the store.+func TestHibReconciler_ListErrorNoOp(t *testing.T) {+ store := newFakeHibStore(stuckRow("x"))+ store.listErr = errors.New("db down")+ newRec(store, &fakeBlobStat{}).tick(context.Background())+ if len(store.uploaded)+len(store.failed) != 0 {+ t.Fatalf("list error must not write to store")+ }+}++// Constructor returns nil when a dependency is missing, so callers can Start() it+// unconditionally (nil receiver is a no-op).+func TestHibReconciler_NilWhenDepsMissing(t *testing.T) {+ if NewHibernationUploadReconciler(HibernationUploadReconcilerConfig{Blobs: &fakeBlobStat{}}) != nil {+ t.Error("expected nil reconciler when Store is nil")+ }+ if NewHibernationUploadReconciler(HibernationUploadReconcilerConfig{Store: newFakeHibStore()}) != nil {+ t.Error("expected nil reconciler when Blobs is nil")+ }+ // nil receiver Start/Stop must not panic.+ var r *HibernationUploadReconciler+ r.Start(context.Background())+ if err := r.Stop(context.Background()); err != nil {+ t.Errorf("nil Stop returned %v", err)+ }+}diff --git a/internal/db/store.go b/internal/db/store.goindex b9d76732..03d5b9d2 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -1855,6 +1855,44 @@ func (s *Store) CountPendingHibernationUploads(ctx context.Context, workerID strreturn n, err}+// StuckHibernationUpload identifies an active hibernation whose async S3 upload+// has NO terminal state (neither uploaded_at nor upload_error) — the worker's+// completion callback was lost (transient DB error, or the worker was torn down+// during a drain before the write landed). The upload usually SUCCEEDED; only+// the bookkeeping is missing, and the stale row wedges worker teardown forever.+type StuckHibernationUpload struct {+ SandboxID string+ HibernationKey string+ HibernatedAt time.Time+}++// ListStuckHibernationUploads returns active hibernations with no terminal upload+// state, older than olderThan (a grace window past the normal upload timeout so+// the reconciler never races an in-flight upload). Bounded by limit. Uses the+// idx_hibernations_pending_upload partial index.+func (s *Store) ListStuckHibernationUploads(ctx context.Context, olderThan time.Time, limit int) ([]StuckHibernationUpload, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT sandbox_id, hibernation_key, hibernated_at+ FROM sandbox_hibernations+ WHERE uploaded_at IS NULL AND upload_error IS NULL AND expired_at IS NULL+ AND hibernated_at < $1+ ORDER BY hibernated_at ASC+ LIMIT $2`, olderThan, limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []StuckHibernationUpload+ for rows.Next() {+ var r StuckHibernationUpload+ if err := rows.Scan(&r.SandboxID, &r.HibernationKey, &r.HibernatedAt); err != nil {+ return nil, err+ }+ out = append(out, r)+ }+ return out, rows.Err()+}+// UpdateSandboxSessionForWake changes a hibernated session back to running on a new worker.func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWorkerID string) error {tx, err := s.pool.Begin(ctx)diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex cccd00b1..aa433138 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -75,32 +75,82 @@ func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) error {return nil}- // fsfreeze guest filesystems BEFORE we let the host-side prepare path- // run sync/savevm. Reason: prepareHibernate (or the legacy sync) only- // flushes whatever's already dirty at the moment it runs — customer- // processes are still scheduled and can keep dirtying ext4 metadata- // up until qmp.Stop() (which is ~210ms later: 200ms post-close sleep +- // QMP round-trip). fsfreeze blocks new write syscalls at the VFS- // layer, leaving ext4's in-memory state in a fully quiesced shape with- // no in-flight metadata transactions. Empirically the savevm/loadvm- // ext4 metadata_csum corruption (incident sb-33f8a5b3 2026-05-19)- // surfaces only after high-frequency hibernates of sandboxes with- // heavy concurrent dx_tree churn, so reducing the in-flight metadata- // state before snapshot is the most direct mitigation we can do- // without touching QEMU. Counterpart: agentFsThawAfterWake runs on- // the wake side once the agent reconnects.+ // fsfreeze guest filesystems BEFORE savevm. fsfreeze blocks new write+ // syscalls at the VFS layer, leaving ext4's in-memory state fully quiesced+ // with no in-flight metadata transactions — it's the ONLY thing that closes+ // the ~210ms window between the last sync and qmp.Stop() during which+ // running processes keep dirtying ext4 metadata. Without it, savevm captures+ // a torn ext4 that fails metadata_csum on loadvm (EBADMSG on first read →+ // unrecoverable box). Counterpart: agentFsThawAfterWake on the wake side.//- // Best-effort: tolerates fsfreeze missing (older util-linux), already- // frozen, or any transient error. Never blocks the hibernate.- freezeCtx, freezeCancel := context.WithTimeout(ctx, 5*time.Second)- if _, freezeErr := agent.Exec(freezeCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "fsfreeze --freeze /home/sandbox 2>/dev/null; fsfreeze --freeze / 2>/dev/null; true"},- RunAsRoot: true,- }); freezeErr != nil {- log.Printf("qemu: prepareHibernate: fsfreeze best-effort failed: %v (continuing)", freezeErr)+ // The agent's virtio-serial gRPC channel is frequently STALE here: a box+ // promoted from the paused tier had its vCPUs stopped, which drops the+ // channel ("use of closed network connection"). The previous code's fsfreeze+ // was a single best-effort exec with NO redial, so on a stale channel it+ // failed silently and the hibernate proceeded un-frozen — the dominant cause+ // of prod wake corruption. So: redial to a fresh channel, VERIFY the rootfs+ // actually froze (a sentinel — the shell can't otherwise tell "froze" from+ // "fsfreeze missing"), and treat an unconfirmed freeze as FATAL so the caller+ // refuses savevm. A still-running box (costs RAM) beats a corrupt, lost one.+ // Retry the whole verified freeze a few times before giving up. Attempt 1+ // uses the existing channel; on failure we REDIAL and retry, then back off.+ // This is the exact recovery for the two prod failure modes: a STALE channel+ // (a box promoted from the paused tier had its vCPUs stopped, dropping the+ // virtio-serial gRPC channel — "use of closed network connection"; the redial+ // heals it) and a transient `fsfreeze --freeze /` EBUSY (the backoff+retry+ // heals it). Only after every attempt fails do we refuse — so a transient+ // hiccup never costs the box its hibernation.+ const freezeAttempts = 3+ frozen := false+ var freezeErr error+ for attempt := 1; attempt <= freezeAttempts && !frozen; attempt++ {+ if attempt > 1 {+ // Prior attempt failed — heal a stale channel and let a busy rootfs+ // settle before retrying.+ log.Printf("qemu: prepareHibernate: freeze attempt %d/%d failed (%v) — redialing + retrying", attempt-1, freezeAttempts, freezeErr)+ if rdErr := agent.Redial(); rdErr != nil {+ log.Printf("qemu: prepareHibernate: redial failed: %v", rdErr)+ }+ time.Sleep(time.Duration(attempt-1) * 400 * time.Millisecond) // 0.4s, 0.8s backoff+ }+ fctx, cancel := context.WithTimeout(ctx, 8*time.Second)+ resp, e := agent.Exec(fctx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", strings.Join([]string{+ // Ancient util-linux without fsfreeze: tolerate (legacy behavior).+ "command -v fsfreeze >/dev/null 2>&1 || { echo __NO_FSFREEZE__; exit 0; }",+ "sync",+ // Workspace is a separate mount only in the split layout; in the+ // merged layout it lives on / and freezing / already covers it.+ "if mountpoint -q /home/sandbox 2>/dev/null; then fsfreeze --freeze /home/sandbox 2>/dev/null || true; fi",+ "fsfreeze --freeze / 2>/dev/null && echo __FROZEN_OK__ || echo __FREEZE_FAILED__",+ }, "\n")},+ RunAsRoot: true,+ })+ cancel()+ if e != nil {+ freezeErr = e+ continue+ }+ frozen = strings.Contains(resp.Stdout, "__FROZEN_OK__") || strings.Contains(resp.Stdout, "__NO_FSFREEZE__")+ if !frozen {+ freezeErr = fmt.Errorf("fsfreeze not confirmed (out=%q)", strings.TrimSpace(resp.Stdout))+ }+ }+ if frozen {+ log.Printf("qemu: prepareHibernate: rootfs frozen for consistent savevm (confirmed)")+ } else {+ // Undo any partial freeze (e.g. /home/sandbox froze but / did not) so the+ // still-running box isn't left with a wedged filesystem, then refuse.+ uctx, ucancel := context.WithTimeout(ctx, 5*time.Second)+ _, _ = agent.Exec(uctx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "fsfreeze --unfreeze / 2>/dev/null; fsfreeze --unfreeze /home/sandbox 2>/dev/null; true"},+ RunAsRoot: true,+ })+ ucancel()+ return fmt.Errorf("%w: rootfs fsfreeze not confirmed before savevm (frozen=%v err=%v)", ErrAgentUnresponsive, frozen, freezeErr)}- freezeCancel()prepareOnce := func() error {rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)@@ -108,6 +158,14 @@ func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) error {_, err := agent.PrepareHibernate(rpcCtx, &pb.PrepareHibernateRequest{})return err}+ // PrepareHibernate resets the guest agent's virtio-serial listener so the+ // restored VM does a clean Accept (avoids the post-loadvm slow-agent-ready+ // race). It is now BEST-EFFORT: the rootfs is already confirmed frozen above,+ // so the snapshot is consistent regardless — a failed reset only risks a+ // slower agent-ready on wake, NOT corruption, so it must not block a hibernate+ // that is already safe. (Previously a failed prepare here refused the+ // hibernate, which was the wrong lever — it's the freeze that guards fs+ // consistency, not the listener reset.)err := prepareOnce()if err != nil && IsTransportError(err) {log.Printf("qemu: PrepareHibernate transport error (%v), redialing", err)@@ -122,32 +180,20 @@ func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) error {}if st, ok := status.FromError(err); !ok || st.Code() != codes.Unimplemented {- log.Printf("qemu: PrepareHibernate RPC failed: %v (falling back to legacy path)", err)+ log.Printf("qemu: PrepareHibernate RPC failed: %v (falling back to legacy SIGUSR1)", err)}- execOnce := func() error {- execCtx, cancel := context.WithTimeout(ctx, 10*time.Second)- defer cancel()- _, e := agent.Exec(execCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},- RunAsRoot: true,- })- return e- }- fallbackErr := execOnce()- if fallbackErr != nil && IsTransportError(fallbackErr) {- log.Printf("qemu: prepareHibernate fallback Exec transport error (%v), redialing", fallbackErr)- if rdErr := agent.Redial(); rdErr == nil {- fallbackErr = execOnce()- } else {- log.Printf("qemu: prepareHibernate fallback redial failed: %v", rdErr)- }- }- if fallbackErr != nil {- return fmt.Errorf("%w: PrepareHibernate=%v, fallback Exec=%v", ErrAgentUnresponsive, err, fallbackErr)+ // Legacy listener-reset fallback (also handles agents too old for the RPC).+ // SIGUSR1 to PID 1 is a pure signal — safe even with / frozen.+ execCtx, cancel := context.WithTimeout(ctx, 8*time.Second)+ if _, e := agent.Exec(execCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "kill -USR1 1 2>/dev/null; true"},+ RunAsRoot: true,+ }); e != nil {+ log.Printf("qemu: prepareHibernate: listener-reset fallback failed: %v (proceeding — fs is frozen, snapshot is safe)", e)}- time.Sleep(1 * time.Second)+ cancel()return nil}diff --git a/internal/storage/s3.go b/internal/storage/s3.goindex 628ba214..33ff945d 100644--- a/internal/storage/s3.go+++ b/internal/storage/s3.go@@ -149,6 +149,20 @@ func (s *CheckpointStore) Exists(ctx context.Context, key string) (bool, error)return false, err}+// Stat returns the object's size and whether it exists. Used by the hibernation-+// upload reconciler to resolve rows whose async completion callback was lost+// (upload succeeded to S3 but uploaded_at was never written).+func (s *CheckpointStore) Stat(ctx context.Context, key string) (size int64, exists bool, err error) {+ sz, err := s.blob.Head(ctx, s.bucket, key)+ if err == nil {+ return sz, true, nil+ }+ if errors.Is(err, ErrNotFound) {+ return 0, false, nil+ }+ return 0, false, err+}+func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (int64, error) {f, err := os.Open(localPath)if err != nil {diff --git a/internal/worker/stats.go b/internal/worker/stats.goindex 473ae7a1..467cc248 100644--- a/internal/worker/stats.go+++ b/internal/worker/stats.go@@ -14,12 +14,12 @@ import (// SystemStats returns current CPU, memory, and disk usage percentages.// On Linux, reads from /proc. On other platforms, returns 0.0 gracefully.// Disk usage uses syscall.Statfs which works on both Linux and macOS.-func SystemStats() (cpuPct, memPct, diskPct float64) {+func SystemStats(dataDir string) (cpuPct, memPct, diskPct float64) {if runtime.GOOS == "linux" {memPct = linuxMemoryPercent()cpuPct = linuxCPUPercent()}- diskPct = diskPercent()+ diskPct = diskPercent(dataDir)return cpuPct, memPct, diskPct}@@ -133,19 +133,21 @@ func readProcStat() (total, idle uint64) {return total, idle}-// diskPercent returns the disk usage percentage for the root filesystem.-// Uses syscall.Statfs which works on both Linux and macOS.-func diskPercent() float64 {- var stat syscall.Statfs_t- if err := syscall.Statfs("/", &stat); err != nil {- return 0.0- }- total := stat.Blocks * uint64(stat.Bsize)- free := stat.Bfree * uint64(stat.Bsize)- if total == 0 {+// diskPercent returns the disk usage percentage for the filesystem containing+// dataDir — the worker DATA mount (e.g. /data), where sandbox overlays,+// checkpoints, and swap actually live. It deliberately does NOT measure the OS+// root (/): the root's ~70% install footprint (guest kernels, base images,+// containerd layers) is static and identical on every worker, so keying+// scale-up / eviction / routing off it makes the scaler forever try to add+// workers (quota-blocked) and can drop healthy workers from routing while+// /data sits nearly empty. Reuses DiskBytes so this matches the per-worker+// disk metric exactly.+func diskPercent(dataDir string) float64 {+ total, used, _, err := DiskBytes(dataDir)+ if err != nil || total == 0 {return 0.0}- return float64(total-free) / float64(total) * 100.0+ return float64(used) / float64(total) * 100.0}// DiskBytes returns total / used / available bytes for the filesystemdiff --git a/internal/worker/stats_test.go b/internal/worker/stats_test.gonew file mode 100644index 00000000..326c6181--- /dev/null+++ b/internal/worker/stats_test.go@@ -0,0 +1,38 @@+package worker++import (+ "os"+ "testing"+)++// diskPercent must measure the filesystem containing the given path (the data+// mount), NOT a hardcoded "/". This guards against regressing to the old+// behavior that keyed disk pressure off the OS root's static install footprint.+func TestDiskPercent_MeasuresGivenPath(t *testing.T) {+ // A real, existing path resolves to its filesystem and yields a sane %.+ dir := os.TempDir()+ pct := diskPercent(dir)+ if pct <= 0 || pct > 100 {+ t.Fatalf("diskPercent(%q) = %.2f, want in (0,100]", dir, pct)+ }+}++// A non-existent path can't be statfs'd — return 0 rather than panicking or+// falling back to another filesystem.+func TestDiskPercent_BadPathZero(t *testing.T) {+ if pct := diskPercent("/no/such/path/xyzzy-does-not-exist"); pct != 0 {+ t.Fatalf("diskPercent(bad) = %.2f, want 0", pct)+ }+}++// SystemStats threads the data dir through to the disk metric.+func TestSystemStats_UsesDataDir(t *testing.T) {+ _, _, disk := SystemStats(os.TempDir())+ if disk <= 0 || disk > 100 {+ t.Fatalf("SystemStats disk = %.2f, want in (0,100]", disk)+ }+ // A bad data dir yields 0 disk (never a stale root-fs reading).+ if _, _, disk := SystemStats("/no/such/path/xyzzy"); disk != 0 {+ t.Fatalf("SystemStats(bad) disk = %.2f, want 0", disk)+ }+}