An open-source, faster Devin alternative
TypeScript
check rows.Err() in reconcilers, share redis client via helper, bound reconnect emit with timeout, log GetSandboxSession failures in post-QMP path
Brian Reardon23757e4d362d
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex d4093999..aed3e79b 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -441,20 +441,8 @@ func main() {// Mirror PG state changes to D1 via the cell events stream.// Without these XADDs, the dashboard keeps the rows at the// pre-restart state ("running" on a worker that just rebooted).- // Brief redis client just for the emit; heartbeat + event- // publisher create their own later in startup.- if cfg.RedisURL != "" && cfg.CellID != "" && (len(hibernated) > 0 || len(stopped) > 0) {- if opts, optErr := redis.ParseURL(cfg.RedisURL); optErr == nil {- emitRDB := redis.NewClient(opts)- for _, o := range hibernated {- cellevents.PublishLifecycle(ctx, emitRDB, cfg.CellID, "hibernated", o.SandboxID, o.WorkerID, o.OrgID, "worker_restart")- }- for _, o := range stopped {- cellevents.PublishLifecycle(ctx, emitRDB, cfg.CellID, "stopped", o.SandboxID, o.WorkerID, o.OrgID, "worker_restart")- }- _ = emitRDB.Close()- }- }+ emitReconcileEvents(ctx, cfg, "hibernated", "worker_restart", hibernated)+ emitReconcileEvents(ctx, cfg, "stopped", "worker_restart", stopped)}// Wire up metadata server billing callback@@ -707,15 +695,15 @@ func main() {// `error` status from the maintenance loop's previous// sweep — customer sees their sandbox as broken until// the next state-changing event.- if cfg.RedisURL != "" && cfg.CellID != "" {- if opts, optErr := redis.ParseURL(cfg.RedisURL); optErr == nil {- emitRDB := redis.NewClient(opts)- for _, o := range fixed {- cellevents.PublishLifecycle(context.Background(), emitRDB, cfg.CellID, "running", o.SandboxID, o.WorkerID, o.OrgID, "worker_reconnect")- }- _ = emitRDB.Close()- }- }+ //+ // Bounded context so a redis stall during shutdown can't+ // block this callback forever. Budget: 10s per event+ // (3s XADD × up to 3 retries) × len(fixed), capped at+ // 60s overall. Reconnect storms rarely produce more+ // than a handful of fixed rows.+ emitCtx, emitCancel := context.WithTimeout(context.Background(), 60*time.Second)+ emitReconcileEvents(emitCtx, cfg, "running", "worker_reconnect", fixed)+ emitCancel()}})}@@ -1184,6 +1172,30 @@ func processHibernateResults(results interface{}, store *db.Store, checkpointSto}}+// emitReconcileEvents XADDs a `cellevents.PublishLifecycle` per orphan to the+// cell's events stream. Used by the worker-startup and worker-reconnect+// reconcilers — both run rarely (boot, network blip) and need a redis client+// just for the emit. Keeping the construction here means one URL parse + one+// pool init + one Close per call site, instead of inlining the same dance+// twice in main(). ctx must be bounded by the caller; the function does not+// add its own timeout (cellevents.PublishLifecycle has a 3s XADD timeout per+// attempt with up to 3 retries, so worst case ~10s per event).+func emitReconcileEvents(ctx context.Context, cfg *config.Config, eventType, reason string, orphans []db.OrphanedSandbox) {+ if len(orphans) == 0 || cfg.RedisURL == "" || cfg.CellID == "" {+ return+ }+ opts, err := redis.ParseURL(cfg.RedisURL)+ if err != nil {+ log.Printf("opensandbox-worker: reconcile emit (%s): redis URL parse failed: %v — events skipped", eventType, err)+ return+ }+ rdb := redis.NewClient(opts)+ defer rdb.Close()+ for _, o := range orphans {+ cellevents.PublishLifecycle(ctx, rdb, cfg.CellID, eventType, o.SandboxID, o.WorkerID, o.OrgID, reason)+ }+}+// recoverLocalQEMU handles local disk recovery for QEMU backend.func recoverLocalQEMU(ctx context.Context, qmMgr *qm.Manager, store *db.Store, cfg *config.Config) {recoveries := qmMgr.RecoverLocalSandboxes()diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex d5bea10e..863b0150 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -1516,9 +1516,14 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker// Source VM is gone, target failed. Emit a `stopped` event so// D1 reflects the unreachable state — otherwise the dashboard// keeps showing the sandbox as running on the dead source.+ // Log the org-id lookup miss so a uuid.Nil org_id on a+ // `stopped` event is traceable to this exact spot rather+ // than left as a mystery in the audit log.var failOrgID uuid.UUIDif sess, err := s.store.GetSandboxSession(context.Background(), sandboxID); err == nil && sess != nil {failOrgID = sess.OrgID+ } else {+ log.Printf("scaler: migrate %s: GetSandboxSession failed during failure-emit (%v) — `stopped` event will carry uuid.Nil org_id", sandboxID, err)}s.publishStopped(context.Background(), sandboxID, sourceWorkerID, failOrgID, "migration_post_qmp_failed")} else {diff --git a/internal/db/store.go b/internal/db/store.goindex 448dba39..c2d133e4 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -1341,6 +1341,14 @@ func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hhibernated = append(hibernated, o)}}+ // Surface mid-iteration failures (conn drop, decode error). Without this,+ // a truncated rows would yield a partial slice; the caller then emits+ // events only for the rows it saw and the rest become D1 ghosts — exactly+ // the bug this reconciler is meant to fix.+ if rowsErr := hibernatedRows.Err(); rowsErr != nil {+ hibernatedRows.Close()+ return nil, nil, fmt.Errorf("iterating hibernated reconcile rows: %w", rowsErr)+ }hibernatedRows.Close()// Second: mark remaining "running" sessions as "stopped"@@ -1358,6 +1366,10 @@ func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hstopped = append(stopped, o)}}+ if rowsErr := stoppedRows.Err(); rowsErr != nil {+ stoppedRows.Close()+ return hibernated, nil, fmt.Errorf("iterating stopped reconcile rows: %w", rowsErr)+ }stoppedRows.Close()// Close any open scale_events for sessions we just transitioned off running@@ -1403,7 +1415,7 @@ func (s *Store) ReconcileWorkerReconnect(ctx context.Context, workerID string, rfixed = append(fixed, o)}}- return fixed, nil+ return fixed, rows.Err()}// UpsertWorkspaceBackup creates or updates a workspace-only backup record for a sandbox.