An open-source, faster Devin alternative
TypeScript
prevent drift on batch creates
Brian Reardon48dc33a4156b
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 3536c449..7487790c 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -150,10 +150,32 @@ export default {SET status = 'hibernated', last_event_at = ?1WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,);+ // INSERT ON CONFLICT, not plain UPDATE — the previous UPDATE-only shape+ // relied on the api-edge's `ctx.waitUntil` POST /api/sandboxes write to+ // have already created the row. When that waitUntil dropped (CF Worker+ // eviction mid-request, common under batch-create load), the row never+ // existed, this UPDATE no-op'd, and the sandbox stayed invisible in D1+ // until the next lifecycle event also no-op'd. The empirical fingerprint+ // was 34 of 50 still-running sandboxes for one large org being absent+ // from sandboxes_index despite having `created` events in D1 events.+ //+ // With INSERT ON CONFLICT, events-ingest is self-sufficient: every+ // `created` / `running` / `woke` event guarantees the row.+ //+ // Monotonic guard applies only to the UPDATE branch — a newer event+ // wins; an out-of-order older event is ignored. On INSERT (no conflict)+ // the row is created with this event's ts as the high-water mark.+ //+ // Binding order: ?1=tsSec, ?2=sandbox_id, ?3=org_id, ?4=cell_id, ?5=worker_idconst lifecycleRunning = env.OPENCOMPUTER_DB.prepare(- `UPDATE sandboxes_index- SET status = 'running', stopped_at = NULL, last_event_at = ?1- WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,+ `INSERT INTO sandboxes_index (id, org_id, cell_id, worker_id, status, created_at, last_event_at)+ VALUES (?2, ?3, ?4, ?5, 'running', ?1, ?1)+ ON CONFLICT(id) DO UPDATE SET+ status = 'running',+ worker_id = COALESCE(excluded.worker_id, sandboxes_index.worker_id),+ stopped_at = NULL,+ last_event_at = ?1+ WHERE sandboxes_index.last_event_at IS NULL OR sandboxes_index.last_event_at < ?1`,);// Migration: sandbox moved to a new worker. Update worker_id alongside// status so proxyToCellSDK + dashboard reflect the new home immediately@@ -198,10 +220,17 @@ export default {// worker_id field rather than payload for these events.return lifecycleMigrated.bind(e.worker_id ?? "", tsSec, e.sandbox_id);}- // "running", "created" set the row to running (created is handled- // by the edge on POST, but accept here for redundancy in case of- // replay against a future cell-only create path).- return lifecycleRunning.bind(tsSec, e.sandbox_id);+ // "running", "created", "woke" set the row to running. Since the+ // INSERT-ON-CONFLICT upgrade, this path also creates the row if the+ // edge's waitUntil dropped on POST /api/sandboxes — events-ingest no+ // longer depends on the edge having written first.+ return lifecycleRunning.bind(+ tsSec,+ e.sandbox_id,+ e.org_id ?? "",+ e.cell_id ?? "",+ e.worker_id ?? null,+ );});// Checkpoint lifecycle: keep D1 checkpoints_index in sync with cell PGdiff --git a/cmd/server/main.go b/cmd/server/main.goindex 66797c80..efc2d557 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -185,17 +185,25 @@ func main() {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.+ // for missed heartbeats, run both directions of the cell-vs-worker+ // state reconcile. See internal/controlplane/reconcile.go for the+ // full rationale on each. Captured opts.Store + cfg.CellID directly;+ // the closure reads them at call time.//- // Captured opts.Store (set above) directly — the closure reads it- // at call time so any later mutations are picked up.+ // reverse first: cell-running but worker-doesn't-have-it →+ // close on cell side (UpdateSessionStatus + EndScaleEvent ++ // publish stopped event). Stops the billing leak immediately.+ //+ // forward second: cell-stopped but worker-still-hosting →+ // re-issue Destroy via RPC. Cleans the worker side.+ //+ // Reverse runs first because the more urgent dollars-on-fire case is+ // the still-open scale event accruing minute-by-minute, not a stray+ // qemu the worker still has.redisRegistry.OnWorkerRejoined(func(workerID string) {- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)defer cancel()+ controlplane.ReconcileRunningOnWorker(ctx, redisRegistry, opts.Store, cfg.CellID, workerID)controlplane.ReconcileStoppedOnWorker(ctx, redisRegistry, opts.Store, workerID)})diff --git a/internal/controlplane/reconcile.go b/internal/controlplane/reconcile.goindex 495552ac..c6d265ad 100644--- a/internal/controlplane/reconcile.go+++ b/internal/controlplane/reconcile.go@@ -2,10 +2,14 @@ package controlplaneimport ("context"+ "encoding/json""log""strings""time"+ "github.com/google/uuid"+ "github.com/redis/go-redis/v9"+"github.com/opensandbox/opensandbox/internal/db"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -95,3 +99,130 @@ func isSandboxNotFound(err error) bool {return strings.Contains(err.Error(), "sandbox not found") ||strings.Contains(err.Error(), "not found")}++// ReconcileRunningOnWorker is the symmetric direction of ReconcileStoppedOnWorker:+//+// forward — cell says STOPPED on this worker, worker may still be hosting →+// re-issue Destroy via RPC. ReconcileStoppedOnWorker above.+// reverse — cell says RUNNING on this worker, worker doesn't have it →+// close the row on the cell side. THIS function.+//+// Why both directions are needed:+// The cell-side fallback at internal/api/sandbox.go (worker-unreachable+// destroy path) covers the forward direction. There's no symmetric fallback+// for "worker died, never finished EndScaleEvent on its way out" — when a+// worker process crashes/OOMs/restarts, its m.vms is cleared but cell PG+// keeps the scale event open. usage-reporter sums (now - started_at)+// indefinitely; customer gets billed for compute that hasn't run for days.+//+// Empirical fingerprint from prod: 49 still-open scale events on two workers+// that were known to have restarted ~3-5 days prior, accumulating ~$2k of+// phantom Pro billing per restart event.+//+// Process:+// 1. Ask cell PG: what sandboxes are status='running' on this worker?+// 2. Ask worker (existing ListSandboxes RPC): what do you actually have?+// 3. For each cell-PG-running entry the worker doesn't claim:+// - UpdateSandboxSessionStatus → stopped+// - EndScaleEvent → closes the open billing row+// - publish stopped lifecycle event so events-ingest updates D1+func ReconcileRunningOnWorker(ctx context.Context, registry *RedisWorkerRegistry, store *db.Store, cellID, workerID string) {+ if store == nil || registry == nil {+ return+ }++ cellRunning, err := store.ListSandboxesByWorkerStatus(ctx, workerID, "running")+ if err != nil {+ log.Printf("controlplane: reverse-reconcile %s: list running sessions failed: %v", workerID, err)+ return+ }+ if len(cellRunning) == 0 {+ return+ }++ client, err := registry.GetWorkerClient(workerID)+ if err != nil {+ log.Printf("controlplane: reverse-reconcile %s: GetWorkerClient failed: %v", workerID, err)+ return+ }++ rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ resp, err := client.ListSandboxes(rpcCtx, &pb.ListSandboxesRequest{})+ cancel()+ if err != nil {+ log.Printf("controlplane: reverse-reconcile %s: ListSandboxes RPC failed: %v", workerID, err)+ return+ }++ workerHas := make(map[string]struct{}, len(resp.Sandboxes))+ for _, sb := range resp.Sandboxes {+ workerHas[sb.SandboxId] = struct{}{}+ }++ log.Printf("controlplane: reverse-reconcile %s: cell-running=%d worker-has=%d", workerID, len(cellRunning), len(workerHas))++ reason := "reverse_reconcile_worker_lost_session"+ var closed, alive int+ for _, ref := range cellRunning {+ if _, has := workerHas[ref.SandboxID]; has {+ alive+++ continue+ }+ // Close the cell-side state. Order matters: status first (so future+ // dashboard reads see the right thing immediately), then scale event+ // (so usage-reporter stops billing), then the lifecycle event (so D1+ // gets the same signal via events-ingest).+ errMsg := reason+ if err := store.UpdateSandboxSessionStatus(ctx, ref.SandboxID, "stopped", &errMsg); err != nil {+ log.Printf("controlplane: reverse-reconcile %s: UpdateSandboxSessionStatus %s: %v", workerID, ref.SandboxID, err)+ continue+ }+ if err := store.EndScaleEvent(ctx, ref.SandboxID); err != nil {+ log.Printf("controlplane: reverse-reconcile %s: EndScaleEvent %s: %v", workerID, ref.SandboxID, err)+ // Don't continue — the status update already happened, so emit+ // the lifecycle event anyway. The scale event being orphaned is+ // at worst a per-row leak the usage-reporter will eventually+ // notice; the lifecycle event is what unblocks D1.+ }+ publishStoppedLifecycleEvent(ctx, registry.RedisClient(), cellID, ref.SandboxID, ref.OrgID.String(), workerID, reason)+ closed+++ }+ log.Printf("controlplane: reverse-reconcile %s: closed=%d still-alive-on-worker=%d (of %d cell-running)", workerID, closed, alive, len(cellRunning))+}++// publishStoppedLifecycleEvent emits a `stopped` event onto this cell's events+// stream so events-ingest mirrors it into D1 sandboxes_index. Mirrors the+// shape of internal/api/checkpoint_events.go's publishSandboxLifecycleEvent+// — extracted here so the reconcile (which lives in controlplane, doesn't+// have an *api.Server handle) can call it directly.+func publishStoppedLifecycleEvent(ctx context.Context, rdb *redis.Client, cellID, sandboxID, orgID, workerID, reason string) {+ if rdb == nil || cellID == "" || sandboxID == "" {+ return+ }+ envelope := map[string]any{+ "id": uuid.NewString(),+ "type": "stopped",+ "sandbox_id": sandboxID,+ "org_id": orgID,+ "worker_id": workerID,+ "cell_id": cellID,+ "payload": map[string]any{"reason": reason},+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),+ }+ body, err := json.Marshal(envelope)+ if err != nil {+ log.Printf("controlplane: publishStoppedLifecycleEvent: marshal: %v", err)+ return+ }+ streamKey := "events:" + cellID+ xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ if err := rdb.XAdd(xaddCtx, &redis.XAddArgs{+ Stream: streamKey,+ MaxLen: 100000,+ Approx: true,+ Values: map[string]any{"event": string(body)},+ }).Err(); err != nil {+ log.Printf("controlplane: publishStoppedLifecycleEvent: XADD %s: %v", sandboxID, err)+ }+}diff --git a/internal/db/store.go b/internal/db/store.goindex 5050d9b2..8586c9c6 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -974,6 +974,40 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, statusreturn sessions, nil}+// WorkerSandboxRef is the minimum (sandbox_id, org_id) tuple the reverse-direction+// reconcile needs to close orphaned sessions and emit lifecycle events.+type WorkerSandboxRef struct {+ SandboxID string+ OrgID uuid.UUID+}++// ListSandboxesByWorkerStatus returns the (sandbox_id, org_id) pairs for sessions+// on a worker with a given status. Used by the reverse-direction reconcile:+// when a worker rejoins after a gap, we look up what cell PG thinks is *running*+// on that worker, ask the worker what it actually has, and close any cell-PG row+// the worker doesn't claim. Bounded to 1000 rows so a runaway query never blows.+func (s *Store) ListSandboxesByWorkerStatus(ctx context.Context, workerID, status string) ([]WorkerSandboxRef, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT sandbox_id, org_id FROM sandbox_sessions+ WHERE worker_id = $1 AND status = $2+ ORDER BY started_at DESC+ LIMIT 1000`,+ workerID, status)+ if err != nil {+ return nil, fmt.Errorf("list sandboxes by worker+status: %w", err)+ }+ defer rows.Close()+ var refs []WorkerSandboxRef+ for rows.Next() {+ var r WorkerSandboxRef+ if err := rows.Scan(&r.SandboxID, &r.OrgID); err != nil {+ return nil, err+ }+ refs = append(refs, r)+ }+ return refs, rows.Err()+}+// 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