An open-source, faster Devin alternative
TypeScript
ensure wake eventing
Brian Reardon7012c7b30c75
diff --git a/cmd/server/main.go b/cmd/server/main.goindex e7fcd9ee..66797c80 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -184,6 +184,21 @@ func main() {if err != nil {log.Fatalf("failed to connect to Redis: %v", err)}+ // Reconcile-on-reconnect: when a worker rejoins after being pruned+ // for missed heartbeats, sweep the cell's view of "stopped sandboxes+ // on this worker" and re-issue Destroy. Closes the gap where the+ // cell-side fallback at internal/api/sandbox.go's destroy handler+ // published "stopped" while the worker was unreachable but qemu+ // kept running. See internal/controlplane/reconcile.go.+ //+ // Captured opts.Store (set above) directly — the closure reads it+ // at call time so any later mutations are picked up.+ redisRegistry.OnWorkerRejoined(func(workerID string) {+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()+ controlplane.ReconcileStoppedOnWorker(ctx, redisRegistry, opts.Store, workerID)+ })+redisRegistry.Start()defer redisRegistry.Stop()opts.WorkerRegistry = redisRegistrydiff --git a/internal/controlplane/reconcile.go b/internal/controlplane/reconcile.gonew file mode 100644index 00000000..495552ac--- /dev/null+++ b/internal/controlplane/reconcile.go@@ -0,0 +1,97 @@+package controlplane++import (+ "context"+ "log"+ "strings"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+ pb "github.com/opensandbox/opensandbox/proto/worker"+)++// ReconcileStoppedOnWorker re-issues DestroySandbox for any sandbox the cell+// believes is stopped on this worker but the worker may still be hosting.+//+// Why this exists:+// When the worker is unreachable, the customer's DELETE goes through the+// cell-side fallback at internal/api/sandbox.go's destroy handler — the+// cell marks the session stopped in PG and publishes a `stopped` lifecycle+// event "to close the drift" with D1. Worker never receives the gRPC+// Destroy. When the worker becomes reachable again, the cell already+// thinks the sandbox is dead, but the worker still has m.vms[id] alive,+// qemu still running, usage_ticker still emitting `usage_tick` events.+// That window has run for 74h+ in the wild before a worker restart finally+// cleared the m.vms map.+//+// This reconcile closes that gap: on worker rejoin (RedisWorkerRegistry's+// OnWorkerRejoined callback), the cell sweeps every sandbox it has marked+// stopped on that worker within the last 24h and re-issues DestroySandbox.+// The RPC is idempotent — manager.Kill returns "sandbox not found" cleanly+// for entries the worker doesn't have, so genuine first-seen workers (empty+// m.vms) are a cheap no-op.+//+// Paired with: Fix A/B/C in internal/qemu/ghost_reaper.go which catches the+// case where qemu died but m.vms wasn't cleaned. This function catches the+// symmetric case where the cell already declared the sandbox dead but the+// worker (with live qemu) doesn't know.+func ReconcileStoppedOnWorker(ctx context.Context, registry *RedisWorkerRegistry, store *db.Store, workerID string) {+ if store == nil || registry == nil {+ return+ }++ ids, err := store.ListSandboxIDsByWorkerStatus(ctx, workerID, "stopped")+ if err != nil {+ log.Printf("controlplane: reconcile %s: list stopped sessions failed: %v", workerID, err)+ return+ }+ if len(ids) == 0 {+ return+ }++ client, err := registry.GetWorkerClient(workerID)+ if err != nil {+ // Worker was just added to the registry by handleHeartbeat; if the+ // gRPC dial is still in flight (or just failed) we'll catch the+ // next rejoin. Don't retry inline — that'd block other rejoins.+ log.Printf("controlplane: reconcile %s: GetWorkerClient failed: %v", workerID, err)+ return+ }++ log.Printf("controlplane: reconcile %s: sweeping %d cell-stopped sandboxes", workerID, len(ids))++ var killed, notFound, errored int+ for _, id := range ids {+ rpcCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ _, err := client.DestroySandbox(rpcCtx, &pb.DestroySandboxRequest{SandboxId: id})+ cancel()+ if err != nil {+ // "sandbox not found" is the success-case: the worker didn't+ // have it (either a genuine new worker or the entry was cleaned+ // up another way). Only log+count non-not-found errors.+ if isSandboxNotFound(err) {+ notFound+++ } else {+ log.Printf("controlplane: reconcile %s: DestroySandbox %s failed: %v", workerID, id, err)+ errored+++ }+ continue+ }+ killed+++ }+ log.Printf("controlplane: reconcile %s: done — killed=%d not_found=%d errored=%d (of %d cell-stopped within 24h)",+ workerID, killed, notFound, errored, len(ids))+}++// isSandboxNotFound is a heuristic for the worker's "sandbox not found" error+// surface — the qemu/firecracker managers both return `fmt.Errorf("sandbox %s+// not found", id)` from Kill on unknown IDs, which propagates through the+// gRPC layer as an Unknown error containing that string. We treat that as the+// success case for reconcile: nothing to clean up.+func isSandboxNotFound(err error) bool {+ if err == nil {+ return false+ }+ return strings.Contains(err.Error(), "sandbox not found") ||+ strings.Contains(err.Error(), "not found")+}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex c028bc74..745fd765 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -96,6 +96,15 @@ type RedisWorkerRegistry struct {rrCounter uint64 // round-robin counter for tie-breakingstop chan struct{}+ // onWorkerRejoined fires when a worker registers — both genuinely new and+ // after being pruned for missed heartbeats. Used by the reconcile-on-+ // reconnect sweep to re-issue Destroy for sandboxes the cell already+ // believes are stopped on this worker but the worker may still be hosting+ // (e.g., the cell ran the "publish stopped fallback" path in+ // internal/api/sandbox.go while this worker was unreachable). Fired in a+ // goroutine; callback should be idempotent.+ onWorkerRejoined func(workerID string)+// Per-sandbox stats indexed by sandboxID for O(1) autoscaler lookup. Updated// from each worker heartbeat. Lock-protected separately from workers so the// autoscaler doesn't contend with the routing path (which holds workersMu).@@ -109,6 +118,17 @@ func (r *RedisWorkerRegistry) RedisClient() *redis.Client {return r.rdb}+// OnWorkerRejoined registers a callback fired when a worker enters the+// registry — both genuine first-seen and a rejoin after the worker was pruned+// for missed heartbeats. Used by the reconcile-on-reconnect sweep (see+// internal/controlplane/reconcile.go). Set this before Start(); callback runs+// in its own goroutine.+func (r *RedisWorkerRegistry) OnWorkerRejoined(fn func(workerID string)) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.onWorkerRejoined = fn+}+// GetSandboxStats returns the latest cached stats for a sandbox along with// its host worker, or ok=false if no recent heartbeat has carried that// sandbox. The autoscaler's per-tick fetchMemPct uses this — replaces the@@ -334,10 +354,22 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {existing.MachineID = entry.MachineID}} else {- // New worker+ // New worker (genuine first-seen OR a rejoin after the worker was+ // pruned for missing heartbeats). Both cases want reconcile-on-reconnect+ // to fire: for genuine new workers the cell PG has no stopped sandboxes+ // on that ID so it's a cheap no-op; for rejoins, this is where we+ // re-issue Destroy for sandboxes the cell published "stopped" for+ // during the unreachable window. See internal/controlplane/reconcile.go.entry.Draining = drainOverrider.workers[entry.ID] = &entrylog.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s, draining=%v)", entry.ID, entry.Region, entry.GRPCAddr, drainOverride)+ if r.onWorkerRejoined != nil {+ // Fire in a goroutine — reconcile may take a few seconds (DB query+ // + a DestroySandbox RPC per stale entry) and we don't want+ // subsequent heartbeats (which need r.mu) blocking on it.+ workerID := entry.ID+ go r.onWorkerRejoined(workerID)+ }}// Per-sandbox stats indexing. Update fresh entries; prune sandboxes thatdiff --git a/internal/db/store.go b/internal/db/store.goindex a10ccfe5..5050d9b2 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -974,6 +974,41 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, statusreturn sessions, nil}+// ListSandboxIDsByWorkerStatus returns sandbox IDs (the public sb-... form,+// not the row UUID) for sessions on a specific worker with a specific status.+// Used by the reconcile-on-reconnect sweep: when a worker rejoins after being+// pruned for missed heartbeats, the cell may have published "stopped"+// lifecycle events during the unreachable window (internal/api/sandbox.go's+// worker_unreachable fallback). This query identifies those entries so the+// reconcile can re-issue Destroy and clean the worker's m.vms.+//+// Bounded to sessions whose stopped_at is within the last 24h — older entries+// have presumably been cleaned by worker restarts or the ghost reaper, and+// scanning them just wastes RPC round-trips.+func (s *Store) ListSandboxIDsByWorkerStatus(ctx context.Context, workerID, status string) ([]string, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT sandbox_id FROM sandbox_sessions+ WHERE worker_id = $1 AND status = $2+ AND stopped_at IS NOT NULL+ AND stopped_at > NOW() - INTERVAL '24 hours'+ ORDER BY stopped_at DESC+ LIMIT 1000`,+ workerID, status)+ if err != nil {+ return nil, fmt.Errorf("list sandboxes by worker+status: %w", err)+ }+ defer rows.Close()+ var ids []string+ for rows.Next() {+ var id string+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ ids = append(ids, id)+ }+ return ids, rows.Err()+}+func (s *Store) CountActiveSandboxes(ctx context.Context, orgID uuid.UUID) (int, error) {var count interr := s.pool.QueryRow(ctx,diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex d6e36cfb..87bbfeaf 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -756,13 +756,28 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequests.router.Register(sb.ID, time.Duration(timeout)*time.Second)}- // Re-initialize per-sandbox SQLite+ // Re-initialize the per-sandbox SQLite and emit a `woke` lifecycle event.+ // The hibernate path called sandboxDBs.Remove(id) which deleted the+ // on-disk SQLite + dir; Get() here recreates it via OpenSandboxDB →+ // MkdirAll + schema apply. The fresh DB has no history (the previous+ // "hibernated" event was already flushed by Hibernate's Remove hook), but+ // new events (including this `woke`) flow normally through the event+ // publisher poll loop.+ //+ // Previously this Get/LogEvent pair silently swallowed both errors, which+ // hid the fact that `woke` events were getting lost in the wild — D1+ // `events` shows ~10× more `hibernated` than `woke` across prod, and the+ // missing transitions broke the phantom-tick auditor's post-hibernate+ // classification (looked like post-hibernate phantoms instead of legit+ // post-wake billing). Log loudly now.if s.sandboxDBs != nil {- sdb, err := s.sandboxDBs.Get(sb.ID)- if err == nil {- _ = sdb.LogEvent("woke", map[string]string{- "sandbox_id": sb.ID,- })+ sdb, getErr := s.sandboxDBs.Get(sb.ID)+ if getErr != nil {+ log.Printf("grpc: WakeSandbox %s: sandboxDBs.Get failed (woke event will not be emitted, downstream timeline will miss the wake transition): %v", sb.ID, getErr)+ } else if logErr := sdb.LogEvent("woke", map[string]string{+ "sandbox_id": sb.ID,+ }); logErr != nil {+ log.Printf("grpc: WakeSandbox %s: LogEvent(woke) failed: %v", sb.ID, logErr)}}