An open-source, faster Devin alternative
TypeScript
fix hibernation upload race, and cross worker race wake
Brian Reardonb41116d3bef5
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex fcb7e6b6..72de4f1b 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -319,6 +319,27 @@ func main() {_ = st.RecordScaleEvent(context.Background(), sandboxID, orgID, memoryMB, cpuPercent, 0)})}++ // Wire hibernation upload completion → DB so silent S3 upload+ // failures stop hiding behind a "hibernated" row that points at a+ // blob that was never written. The callback runs from the async+ // archive goroutine in qemu/snapshot.go after upload finishes.+ if qemuMgr != nil {+ st := store // capture for closure+ qemuMgr.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)+ }+ return+ }+ if err := st.MarkHibernationUploaded(ctx2, hibernationKey, sizeBytes); err != nil {+ log.Printf("opensandbox-worker: failed to mark hibernation uploaded for %s: %v", sandboxID, err)+ }+ })+ }}}diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 5890c087..e93f0ef2 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1725,13 +1725,52 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.Wreturn c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not hibernated"})}- // Pick ANY worker in the same region+ // Prefer the source worker (where hibernation actually happened) so wake+ // can use the local qcow2 files instead of downloading from S3. Two reasons:+ //+ // 1. Same-worker wake is dramatically faster (~300ms vs. 30+s for a 1GB+ // download+extract).+ // 2. Avoids a wake-vs-upload race: hibernate's S3 upload is async and+ // takes tens of seconds for a 4GB sandbox. A wake routed to a+ // different worker that runs before the upload finishes fails with+ // "blob: object not found" because it tries HEAD before the goroutine+ // finished writing. uploaded_at is the canonical signal — if it's+ // NULL, the source worker is the only safe target.+ //+ // Fall back to least-loaded only when source is gone, draining, or under+ // resource pressure. If upload isn't complete yet, prefer source even at+ // the cost of some imbalance — the alternative is a 500 to the user.region := hibernation.Region- worker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)- if err != nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "no workers available in region " + region,- })+ var worker *controlplane.WorkerEntry+ var grpcClient pb.SandboxWorkerClient+ uploadComplete := hibernation.UploadedAt != nil+ if session.WorkerID != "" {+ if src := s.workerRegistry.GetWorker(session.WorkerID); src != nil &&+ !src.Draining && src.CPUPct < 90 && src.MemPct < 90 && src.DiskPct < 90 {+ if cli, cerr := s.workerRegistry.GetWorkerClient(session.WorkerID); cerr == nil {+ worker = src+ grpcClient = cli+ log.Printf("wake %s: routing to source worker %s (upload_complete=%v)",+ sandboxID, session.WorkerID, uploadComplete)+ }+ }+ }+ if worker == nil {+ // Source unavailable. Cross-worker wake will need to download from S3,+ // so refuse if upload hasn't completed — better a clear error than a+ // confusing "blob: object not found" once the worker actually tries.+ if !uploadComplete {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "source worker unavailable and hibernation upload not yet complete; retry shortly",+ })+ }+ var lerr error+ worker, grpcClient, lerr = s.workerRegistry.GetLeastLoadedWorker(region)+ if lerr != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "no workers available in region " + region,+ })+ }}grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 60*time.Second)diff --git a/internal/db/migrations/038_hibernation_upload_status.down.sql b/internal/db/migrations/038_hibernation_upload_status.down.sqlnew file mode 100644index 00000000..e22bc6ea--- /dev/null+++ b/internal/db/migrations/038_hibernation_upload_status.down.sql@@ -0,0 +1,5 @@+DROP INDEX IF EXISTS idx_hibernations_pending_upload;++ALTER TABLE sandbox_hibernations+ DROP COLUMN IF EXISTS uploaded_at,+ DROP COLUMN IF EXISTS upload_error;diff --git a/internal/db/migrations/038_hibernation_upload_status.up.sql b/internal/db/migrations/038_hibernation_upload_status.up.sqlnew file mode 100644index 00000000..144d8632--- /dev/null+++ b/internal/db/migrations/038_hibernation_upload_status.up.sql@@ -0,0 +1,15 @@+-- Track whether a hibernation's S3 upload actually completed.+-- Pre-fix: size_bytes was hardcoded to 0 by qemu hibernate, so the DB had no+-- signal of upload success. Async upload failures were only logged. This made+-- the missing-blob bug invisible — sandboxes appeared hibernated but couldn't+-- be woken cross-worker because the blob was never uploaded.++ALTER TABLE sandbox_hibernations+ ADD COLUMN uploaded_at TIMESTAMPTZ,+ ADD COLUMN upload_error TEXT;++-- Find hibernations that have not finished uploading. Useful for monitoring+-- and for the periodic backstop scan.+CREATE INDEX idx_hibernations_pending_upload+ ON sandbox_hibernations (hibernated_at)+ WHERE uploaded_at IS NULL AND upload_error IS NULL AND expired_at IS NULL;diff --git a/internal/db/store.go b/internal/db/store.goindex 9f984573..4ef4497e 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -128,6 +128,7 @@ func (s *Store) Migrate(ctx context.Context) error {{35, "migrations/035_sandbox_autoscale.up.sql"},{36, "migrations/036_sandbox_scaling_lock.up.sql"},{37, "migrations/037_agent_subscriptions.up.sql"},+ {38, "migrations/038_hibernation_upload_status.up.sql"},}for _, m := range migrations {@@ -1031,6 +1032,8 @@ type SandboxHibernation struct {HibernatedAt time.Time `json:"hibernatedAt"`RestoredAt *time.Time `json:"restoredAt,omitempty"`ExpiredAt *time.Time `json:"expiredAt,omitempty"`+ UploadedAt *time.Time `json:"uploadedAt,omitempty"`+ UploadError *string `json:"uploadError,omitempty"`}// CreateHibernation inserts a new hibernation record, marking any prior active@@ -1079,11 +1082,11 @@ func (s *Store) CreateHibernation(ctx context.Context, sandboxID string, orgID ufunc (s *Store) GetActiveHibernation(ctx context.Context, sandboxID string) (*SandboxHibernation, error) {cp := &SandboxHibernation{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at+ `SELECT id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at, uploaded_at, upload_errorFROM sandbox_hibernationsWHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL`, sandboxID,).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.HibernationKey, &cp.SizeBytes,- &cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt, &cp.RestoredAt, &cp.ExpiredAt)+ &cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt, &cp.RestoredAt, &cp.ExpiredAt, &cp.UploadedAt, &cp.UploadError)if err != nil {return nil, fmt.Errorf("active hibernation not found: %w", err)}@@ -1099,6 +1102,31 @@ func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) ereturn err}+// MarkHibernationUploaded records that the async S3 archive upload completed+// for a specific hibernation_key. Matches by key (not sandbox_id) because a+// sandbox can have multiple hibernation rows in flight when hibernate→wake→+// hibernate cycles run faster than the upload goroutine.+func (s *Store) MarkHibernationUploaded(ctx context.Context, hibernationKey string, sizeBytes int64) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_hibernations+ SET uploaded_at = now(), size_bytes = $2, upload_error = NULL+ WHERE hibernation_key = $1`,+ hibernationKey, sizeBytes)+ return err+}++// MarkHibernationUploadFailed records the failure reason for an upload that+// did not land in S3. Without this, async upload failures were silent and the+// row stayed in a misleading "hibernated, blob present" state.+func (s *Store) MarkHibernationUploadFailed(ctx context.Context, hibernationKey, errMsg string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_hibernations+ SET upload_error = $2+ WHERE hibernation_key = $1`,+ hibernationKey, errMsg)+ return err+}+// UpdateSandboxSessionForWake changes a hibernated session back to running on a new worker.func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWorkerID string) error {_, err := s.pool.Exec(ctx,diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 3cbf3a34..a216ff42 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -186,6 +186,13 @@ type Manager struct {onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)onSandboxDestroy func(sandboxID string)+ // Hibernation upload status callback (set via SetHibernationUploadCallback).+ // Invoked from the async archive+upload goroutine in doHibernate exactly once+ // per hibernation, with err=nil on success or non-nil on archive/upload+ // failure. The worker uses this to write uploaded_at / upload_error in the+ // sandbox_hibernations row so missing-blob failures stop being silent.+ onHibernationUpload func(sandboxID, hibernationKey string, sizeBytes int64, uploadErr error)+secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configuredcheckpointStore *storage.CheckpointStore // for base image archival + checkpoint rebasing (nil until set)@@ -275,6 +282,15 @@ func (m *Manager) SetCheckpointStore(cs *storage.CheckpointStore) {m.checkpointStore = cs}+// SetHibernationUploadCallback registers a callback invoked from the async+// hibernation archive+upload goroutine when it finishes. err is nil on+// success; sizeBytes is the archive size (only meaningful on success). The+// worker uses this to update sandbox_hibernations.uploaded_at / upload_error+// so silent upload failures become visible.+func (m *Manager) SetHibernationUploadCallback(cb func(sandboxID, hibernationKey string, sizeBytes int64, uploadErr error)) {+ m.onHibernationUpload = cb+}+// 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 {diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 81ee343e..947f1fed 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -159,7 +159,16 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoos.Remove(vm.qmpSockPath)}- checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, time.Now().Unix())+ // Per-hibernation unique paths. Pre-fix used a single sandbox-scoped+ // `archive-staging/` and `checkpoint.tar.zst`, so back-to-back+ // hibernate→wake→hibernate cycles raced: the second hibernate's+ // copyFileReflink overwrote the first goroutine's staging files mid-tar,+ // and both goroutines wrote the same checkpoint.tar.zst path. End state:+ // neither blob landed in S3, the DB still showed both rows as hibernated,+ // and cross-worker wake failed with "blob: object not found". Including+ // UnixNano in the staging dir name is enough to make the paths unique.+ epochSec := time.Now().Unix()+ checkpointKey := fmt.Sprintf("checkpoints/%s/%d.tar.zst", vm.ID, epochSec)localElapsed := time.Since(t0)log.Printf("qemu: hibernate %s: local snapshot complete (%dms), starting async S3 upload",vm.ID, localElapsed.Milliseconds())@@ -174,7 +183,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoworkspaceFile := filepath.Base(detectDrivePath(sandboxDir, "workspace"))rootfsFile := filepath.Base(detectDrivePath(sandboxDir, "rootfs"))- archiveDir := filepath.Join(sandboxDir, "archive-staging")+ archiveDir := filepath.Join(sandboxDir, fmt.Sprintf("archive-staging-%d", time.Now().UnixNano()))if err := os.MkdirAll(archiveDir, 0755); err != nil {return nil, fmt.Errorf("mkdir archive-staging: %w", err)}@@ -203,19 +212,31 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStolog.Printf("qemu: hibernate %s: rootfs rebase failed (archive may not be portable): %v (%s)",sandboxID, err, strings.TrimSpace(string(out)))}- log.Printf("qemu: hibernate %s: archive staging ready", sandboxID)+ log.Printf("qemu: hibernate %s: archive staging ready (dir=%s)", sandboxID, filepath.Base(archiveDir))// Signal channel so destroyVM can wait for archive completion before deleting files.archiveDone := make(chan struct{})vm.archiveDone = archiveDone+ uploadCb := m.onHibernationUploadm.uploadWg.Add(1)go func() {defer m.uploadWg.Done()defer close(archiveDone)defer os.RemoveAll(archiveDir) // clean up staging copies when done++ var sizeBytes int64+ var goroutineErr error+ defer func() {+ if uploadCb != nil {+ uploadCb(sandboxID, checkpointKey, sizeBytes, goroutineErr)+ }+ }()+t1 := time.Now()- archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")+ // Tar lives inside the per-hibernation staging dir so concurrent+ // hibernations of the same sandbox don't write to the same path.+ archivePath := filepath.Join(archiveDir, "checkpoint.tar.zst")// Archive from the staging copies — originals are free for wake/QEMU.if err := createArchive(archivePath, archiveDir, []string{@@ -223,29 +244,30 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStorootfsFile,workspaceFile,}); err != nil {+ goroutineErr = fmt.Errorf("archive: %w", err)log.Printf("qemu: async archive failed for %s: %v", sandboxID, err)return}archiveInfo, err := os.Stat(archivePath)if err != nil {+ goroutineErr = fmt.Errorf("stat archive: %w", err)log.Printf("qemu: async archive stat failed for %s: %v", sandboxID, err)return}+ sizeBytes = archiveInfo.Size()log.Printf("qemu: hibernate %s: archive created (%dms, %.1f MB)",- sandboxID, time.Since(t1).Milliseconds(), float64(archiveInfo.Size())/(1024*1024))+ sandboxID, time.Since(t1).Milliseconds(), float64(sizeBytes)/(1024*1024))t2 := time.Now()uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {+ goroutineErr = fmt.Errorf("upload: %w", err)log.Printf("qemu: async S3 upload failed for %s: %v", sandboxID, err)- os.Remove(archivePath) // clean up — local qcow2 files are the source of truth for same-worker wake- return+ return // archiveDir cleanup via defer takes the tar with it}log.Printf("qemu: hibernate %s: S3 upload complete (%dms, key=%s)",sandboxID, time.Since(t2).Milliseconds(), checkpointKey)-- os.Remove(archivePath) // only delete after successful upload}()return &sandbox.HibernateResult{@@ -273,25 +295,11 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, csnapshotDir := filepath.Join(sandboxDir, "snapshot")metaPath := filepath.Join(snapshotDir, "snapshot-meta.json")- // Wait for any in-flight hibernate archive to finish before proceeding.- // Same-worker wake: archive reads from staging copies (safe), but we need- // archive-staging/ cleaned up before starting QEMU to avoid disk waste.- // Cross-worker wake: S3 upload must complete before download can succeed.- archiveStagingDir := filepath.Join(sandboxDir, "archive-staging")- if fileExists(archiveStagingDir) {- log.Printf("qemu: wake %s: waiting for in-flight archive to complete", sandboxID)- for i := 0; i < 60; i++ { // up to 30 seconds- if !fileExists(archiveStagingDir) {- break- }- time.Sleep(500 * time.Millisecond)- }- if fileExists(archiveStagingDir) {- // Don't force-remove — the archive goroutine's defer will clean up.- // Removing while tar is mid-read corrupts the S3 archive.- log.Printf("qemu: wake %s: archive staging still present after 30s, proceeding (goroutine will clean up)", sandboxID)- }- }+ // Per-hibernation archive staging dirs are named `archive-staging-<nano>` and+ // each goroutine cleans up its own dir via defer. Wake doesn't need the+ // archive (same-worker uses local qcow2; cross-worker downloads from S3),+ // so there is nothing to wait for here. Pre-fix this loop watched a single+ // fixed `archive-staging/` path — irrelevant under the new scheme.// Step 1: Ensure qcow2 files are localt0 := time.Now()