An open-source, faster Devin alternative
TypeScript
handle stale incoming, reverse reconcile, add terminated status
Brian Reardon219101f16e9e
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex deec7790..6710cfc3 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -375,15 +375,15 @@ export default {VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)ON CONFLICT(id) DO NOTHING`,);- // Worker-validation guard. Drop a usage_tick if the emitting worker is NOT- // the sandbox's current owner in sandboxes_index, or the sandbox is already- // terminal there. This stops a zombie / migration-source / deregistered- // worker from billing a sandbox it no longer owns — the leak that silently- // 3×'d an org's edge usage when a stuck `-incoming` migration shell kept- // ticking after the sandbox had moved away. The cell never had this bug- // (scale_events are per-sandbox), but the edge inserted every tick blindly.- // Lookup failure → allow (degraded, no worse than before). A sandbox with no- // index row yet (create race) is allowed.+ // Worker-validation guard. Edge usage is counted per-tick (one usage_sample+ // per emitted tick), so a worker that is no longer the sandbox's owner — a+ // migration source, a deregistered worker, or an abandoned `-incoming`+ // receiver — must not contribute usage. Drop a usage_tick when the emitting+ // worker is not the sandbox's current owner in sandboxes_index, or the+ // sandbox is already terminal there. (The cell side needs no equivalent: its+ // scale_events are keyed per-sandbox, not per-tick.) Lookup failure → allow+ // (degraded, never blocks billing). A sandbox with no index row yet (create+ // race) is allowed.const tickSandboxIds = [...new Set(fresh.filter((e) => e.type === "usage_tick" && e.sandbox_id).map((e) => e.sandbox_id as string)),];diff --git a/cmd/server/main.go b/cmd/server/main.goindex 62168e7e..7cad69e3 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -587,9 +587,9 @@ func main() {// Stale-pending reaper: a create stuck in 'pending' past the// threshold (even on a still-live worker, which MarkOrphanedSandboxes- // below can't catch) is closed → 'failed', ending the open- // scale_event that would otherwise bill 1 GB forever. Publishes- // 'stopped' to the edge so D1 / usage_samples stop too.+ // below does not cover) is closed → 'failed', ending the open+ // scale_event that would otherwise keep billing. Publishes 'stopped'+ // to the edge so D1 / usage_samples stop too.if stale, err := opts.Store.ReapStalePendingSessions(ctx, 15*time.Minute); err != nil {log.Printf("maintenance: stale-pending reap error: %v", err)observability.CaptureError(err, "area", "maintenance", "op", "reap_stale_pending")@@ -625,6 +625,28 @@ func main() {})}+ // Periodic reverse-reconcile. The rejoin-triggered ReconcileRunningOnWorker+ // only fires when a worker reconnects; a worker that is deleted and never+ // rejoins would leave its sandboxes 'running' (cell + edge sandboxes_index)+ // with no event ever correcting them. Sweep every live worker every few+ // minutes and close any sandbox the cell thinks is running that the worker no+ // longer actually has (confirmed via the worker's ListSandboxes RPC, which+ // publishes 'stopped' to the edge). This keeps the edge index — the post-+ // cutover billing authority — accurate even when no 'stopped' event fired.+ if opts.Store != nil && redisRegistry != nil {+ observability.Go("periodic-running-reconcile", func() {+ ticker := time.NewTicker(3 * time.Minute)+ defer ticker.Stop()+ for range ticker.C {+ for _, w := range redisRegistry.GetAllWorkers() {+ rctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ controlplane.ReconcileRunningOnWorker(rctx, redisRegistry, opts.Store, cfg.CellID, w.ID)+ cancel()+ }+ }+ })+ }+// Initialize control plane subdomain proxy (server mode only).// Routes *.workers.opensandbox.ai requests to the correct worker// by looking up sandbox → worker mapping in PG + Redis registry.diff --git a/internal/db/store.go b/internal/db/store.goindex a655004f..e86c2235 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -52,7 +52,10 @@ type TerminalHook func(sandboxID string, orgID uuid.UUID, status, reason string)// terminal status without classifying it here is the easy regression.func isTerminalSessionStatus(status string) bool {switch status {- case "stopped", "error", "failed":+ // `terminated` is a legacy status no current path writes, but classify it as+ // terminal anyway: it keeps the cell consistent with the edge guard (which+ // treats it as terminal) and ensures any future writer stops billing.+ case "stopped", "error", "failed", "terminated":return truedefault:return false@@ -1015,11 +1018,11 @@ func (s *Store) RecoverStaleMigrations(ctx context.Context, maxAge time.Duration// loop's PG sweep would never reach D1 sandboxes_index, which is exactly// the post-cutover ghost-row bug.func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[string]bool) ([]OrphanedSandbox, error) {- // Include 'pending' as well as 'running': a sandbox whose create never- // reached running (stuck pending) on a worker that then disappeared used to- // slip through here — its scale_event stayed open and billed forever (the- // orphaned-pending leak). 'pending' on a *live* worker is left alone (it may- // still be mid-create); only pending rows on a dead worker are reaped.+ // Include 'pending' as well as 'running': a create that never reached+ // running (still 'pending') on a worker that has since disappeared must also+ // be closed, since its scale_event is open and would keep billing. 'pending'+ // on a *live* worker is left alone (it may still be mid-create); only pending+ // rows on a dead worker are reaped.rows, err := s.pool.Query(ctx,`SELECT DISTINCT worker_id FROM sandbox_sessions WHERE status IN ('running', 'pending')`)if err != nil {@@ -1083,12 +1086,12 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin}// ReapStalePendingSessions terminates sandbox sessions stuck in 'pending' past-// olderThan, closing their open scale_events. This is the backstop for the-// orphaned-pending billing leak that MarkOrphanedSandboxes can't catch: a create-// that hangs in 'pending' on a worker that is STILL alive (so it's never an-// orphan) — without this it bills 1 GB forever. Returns the reaped rows so the-// caller can publish 'stopped' to the edge. Marked 'failed' (the create never-// succeeded) rather than 'error'; both are terminal and stop billing.+// olderThan, closing their open scale_events. It complements MarkOrphanedSandboxes,+// which only reaps sandboxes on dead workers: a create that hangs in 'pending' on+// a worker that is STILL alive is never an orphan, so its open scale_event needs+// this age-based backstop to stop billing. Returns the reaped rows so the caller+// can publish 'stopped' to the edge. Marked 'failed' (the create never+// succeeded), which is terminal and closes billing.func (s *Store) ReapStalePendingSessions(ctx context.Context, olderThan time.Duration) ([]OrphanedSandbox, error) {tx, err := s.pool.Begin(ctx)if err != nil {diff --git a/internal/db/terminal_status_test.go b/internal/db/terminal_status_test.goindex e842c9e7..497ed68b 100644--- a/internal/db/terminal_status_test.go+++ b/internal/db/terminal_status_test.go@@ -9,7 +9,7 @@ import "testing"// "killed") without listing it here is the easy regression that would silently// leave it billing on the edge.func TestIsTerminalSessionStatus(t *testing.T) {- terminal := []string{"stopped", "error", "failed"}+ terminal := []string{"stopped", "error", "failed", "terminated"}notTerminal := []string{"running", "pending", "migrating", "hibernated", "woke", "", "unknown"}for _, s := range terminal {diff --git a/internal/qemu/ghost_reaper.go b/internal/qemu/ghost_reaper.goindex c1f35833..702bc625 100644--- a/internal/qemu/ghost_reaper.go+++ b/internal/qemu/ghost_reaper.go@@ -37,9 +37,9 @@ const reaperInterval = 30 * time.Second// and the ghost-reaper can't drain the m.vms entry.//// Three checks in order:-// 1. ProcessState — if cmd.Wait() returned, definitively dead.-// 2. /proc/<pid>/stat — if state is Z (zombie) or X (dying), treat as dead.-// 3. Signal(0) — fallback liveness probe; ESRCH means PID gone.+// 1. ProcessState — if cmd.Wait() returned, definitively dead.+// 2. /proc/<pid>/stat — if state is Z (zombie) or X (dying), treat as dead.+// 3. Signal(0) — fallback liveness probe; ESRCH means PID gone.//// Returns false for: nil cmd, nil cmd.Process, reaped process, zombie, or// "no such process".@@ -138,6 +138,37 @@ func (m *Manager) runGhostReaper() {returncase <-t.C:m.reapDeadVMs(context.Background())+ m.reapStaleIncomingMigrations(context.Background())+ }+ }+}++// staleIncomingTimeout bounds how long a migration receiver may sit paused+// (-incoming) before the reaper tears it down. A live migration loads in+// seconds-to-minutes; anything still un-resumed past this never received its+// source and is abandoned. Generous so a slow-but-real load is never killed.+const staleIncomingTimeout = 10 * time.Minute++// reapStaleIncomingMigrations destroys migration receivers whose migration never+// completed. Such a receiver is a paused QEMU that passes vmAlive (the process+// is up) but is not a running sandbox on this worker, so without this it would+// be ticked indefinitely. The control-plane aborts receivers on an explicit+// migration failure; this covers the abandoned case where no abort ever fires.+// Identify under the lock (cheap timestamp check), tear down outside it.+func (m *Manager) reapStaleIncomingMigrations(ctx context.Context) {+ now := time.Now()+ m.mu.Lock()+ var stale []string+ for id, vm := range m.vms {+ if !vm.incomingMigrationAt.IsZero() && now.Sub(vm.incomingMigrationAt) > staleIncomingTimeout {+ stale = append(stale, id)+ }+ }+ m.mu.Unlock()+ for _, id := range stale {+ log.Printf("qemu: stale-incoming-reaper: destroying %s — migration receiver never resumed within %s", id, staleIncomingTimeout)+ if err := m.Kill(ctx, id); err != nil {+ log.Printf("qemu: stale-incoming-reaper: Kill %s failed: %v", id, err)}}}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 18c6b1b7..562af547 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -242,6 +242,12 @@ type VMInstance struct {baseMemoryMB int // initial memory passed to -m (before virtio-mem)virtioMemRequestedMB int // additional memory via virtio-mem (beyond base)goldenVersion string // golden version this sandbox was created from (empty if cold-booted)+ // Set when this VM is started as a migration receiver (paused, -incoming) and+ // cleared once CompleteIncomingMigration resumes it. While set, the VM is a+ // not-yet-completed receiver: it's alive (so it passes vmAlive and would be+ // ticked) but doesn't represent a running sandbox here. The stale-incoming+ // reaper destroys any whose migration never completes within the timeout.+ incomingMigrationAt time.Time}// SandboxMeta is persisted to sandbox-meta.json for recovery after hard kills.diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex 0bc9c6c6..a380e260 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -284,7 +284,7 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco// Set migration parameters for fast cutover_ = vm.qmp.Execute("migrate-set-parameters", map[string]interface{}{"max-bandwidth": int64(1024 * 1024 * 1024), // 1 GB/s- "downtime-limit": int64(100), // 100ms max downtime+ "downtime-limit": int64(100), // 100ms max downtime})// Start live migration@@ -470,12 +470,16 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfcmd.Stderr = logFileif err := cmd.Start(); err != nil {logFile.Close()- if devNull != nil { devNull.Close() }+ if devNull != nil {+ devNull.Close()+ }m.cleanupVM(netCfg, sandboxDir)return "", 0, fmt.Errorf("start qemu: %w", err)}logFile.Close()- if devNull != nil { devNull.Close() }+ if devNull != nil {+ devNull.Close()+ }log.Printf("qemu: migration-prepare %s: QEMU started (pid=%d), waiting for QMP", sandboxID, cmd.Process.Pid)// Connect QMP — allow up to 60s for large-memory VMs (virtio-mem init takes time)@@ -524,6 +528,11 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfguestCID: guestCID,bootArgs: bootArgs,goldenVersion: m.GoldenVersion(),+ // Marks this as an in-flight migration receiver until CompleteIncoming-+ // Migration clears it. The reaper uses this to tear down receivers whose+ // migration is abandoned (never completed), which otherwise stay alive+ // and get ticked despite never becoming a running sandbox here.+ incomingMigrationAt: time.Now(),}m.mu.Lock()@@ -622,6 +631,13 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strinm.onSandboxReady(sandboxID, vm.network.GuestIP, vm.Template, vm.StartedAt)}+ // Migration completed and the VM is resumed + agent-connected: it's now a+ // normal running sandbox, so clear the receiver marker (the reaper must not+ // touch it). Under the lock to pair with the reaper's read.+ m.mu.Lock()+ vm.incomingMigrationAt = time.Time{}+ m.mu.Unlock()+log.Printf("qemu: incoming migration %s complete (port=%d, tap=%s)",sandboxID, vm.HostPort, vm.network.TAPName)return nil