An open-source, faster Devin alternative
TypeScript
reap stale pending, gaurd phantom ticks on edge
Brian Reardoncdf0fa448884
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 14688930..deec7790 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -375,8 +375,37 @@ 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.+ const tickSandboxIds = [+ ...new Set(fresh.filter((e) => e.type === "usage_tick" && e.sandbox_id).map((e) => e.sandbox_id as string)),+ ];+ const owners = await resolveSandboxOwners(env, tickSandboxIds);+ const TERMINAL_STATUSES = new Set(["stopped", "terminated", "failed", "error"]);+ let droppedZombieTicks = 0;+ const tickFromCurrentWorker = (e: SandboxEventEnvelope): boolean => {+ if (!owners.ok) return true;+ const row = e.sandbox_id ? owners.byId.get(e.sandbox_id) : undefined;+ if (!row) return true; // no index row yet — don't drop a legit fresh create+ if (TERMINAL_STATUSES.has(row.status)) {+ droppedZombieTicks++;+ return false;+ }+ if (row.worker_id && e.worker_id && row.worker_id !== e.worker_id) {+ droppedZombieTicks++;+ return false;+ }+ return true;+ };const usageSampleBatches = fresh- .filter((e) => e.type === "usage_tick" && planFor(e) === "pro" && e.org_id && e.sandbox_id)+ .filter((e) => e.type === "usage_tick" && planFor(e) === "pro" && e.org_id && e.sandbox_id && tickFromCurrentWorker(e)).map((e) => {const p = (e.payload ?? {}) as {memory_mb?: number;@@ -395,6 +424,10 @@ export default {);});+ if (droppedZombieTicks > 0) {+ console.warn(`events-ingest: dropped ${droppedZombieTicks} usage_tick(s) from non-owner/terminal sandboxes (zombie-tick guard)`);+ }+try {await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches, ...checkpointBatches, ...imageBatches, ...usageSampleBatches]);} catch (err) {@@ -471,6 +504,34 @@ async function fanoutDebits(env: Env, events: SandboxEventEnvelope[]): Promise<v// lookup fails, signalling callers to fall back to the envelope plan rather// than dropping billing entirely. Orgs absent from D1 (new-org race) are simply// missing from the map → treated as unknown plan → skipped, the safe default.+// resolveSandboxOwners fetches each sandbox's current worker_id + status from+// the D1 sandboxes_index, so the usage-tick guard can reject ticks from a worker+// that no longer owns the sandbox (migration source / zombie) or for a sandbox+// that's already terminal. Lookup failure returns ok:false so the caller allows+// the ticks (degraded, never blocks billing on a transient D1 error).+async function resolveSandboxOwners(+ env: Env,+ sandboxIds: string[],+): Promise<{ ok: boolean; byId: Map<string, { worker_id: string; status: string }> }> {+ const byId = new Map<string, { worker_id: string; status: string }>();+ if (sandboxIds.length === 0) return { ok: true, byId };+ const placeholders = sandboxIds.map((_, i) => `?${i + 1}`).join(",");+ try {+ const res = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, worker_id, status FROM sandboxes_index WHERE id IN (${placeholders})`,+ )+ .bind(...sandboxIds)+ .all<{ id: string; worker_id: string | null; status: string | null }>();+ for (const r of res.results ?? []) {+ byId.set(r.id, { worker_id: r.worker_id ?? "", status: r.status ?? "" });+ }+ return { ok: true, byId };+ } catch (err) {+ console.error("events-ingest: sandbox owner lookup failed — allowing ticks", err);+ return { ok: false, byId };+ }+}+async function resolvePlans(env: Env,orgIds: string[],diff --git a/cmd/server/main.go b/cmd/server/main.goindex 60706e86..62168e7e 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -585,6 +585,21 @@ func main() {log.Printf("maintenance: reverted %d stale migrations", recovered)}+ // 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.+ 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")+ } else if len(stale) > 0 {+ log.Printf("maintenance: reaped %d stale-pending sandboxes (failed → billing closed)", len(stale))+ if redisRegistry.RedisClient() != nil && cfg.CellID != "" {+ publishStoppedFromMaintenance(ctx, redisRegistry.RedisClient(), cfg.CellID, stale)+ }+ }+// DB/worker reconciliation: mark sandboxes on dead workers as errorliveWorkers := make(map[string]bool)for _, w := range redisRegistry.GetAllWorkers() {diff --git a/internal/db/store.go b/internal/db/store.goindex f6ea9397..a655004f 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -1015,8 +1015,13 @@ 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.rows, err := s.pool.Query(ctx,- `SELECT DISTINCT worker_id FROM sandbox_sessions WHERE status = 'running'`)+ `SELECT DISTINCT worker_id FROM sandbox_sessions WHERE status IN ('running', 'pending')`)if err != nil {return nil, err}@@ -1044,7 +1049,7 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin}upd, err := tx.Query(ctx,`UPDATE sandbox_sessions SET status = 'error', error_msg = 'worker lost', stopped_at = now()- WHERE worker_id = $1 AND status = 'running'+ WHERE worker_id = $1 AND status IN ('running', 'pending')RETURNING sandbox_id, org_id, worker_id`, workerID)if err != nil {tx.Rollback(ctx)@@ -1077,6 +1082,52 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strinreturn orphans, nil}+// 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.+func (s *Store) ReapStalePendingSessions(ctx context.Context, olderThan time.Duration) ([]OrphanedSandbox, error) {+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback(ctx)++ upd, err := tx.Query(ctx,+ `UPDATE sandbox_sessions SET status = 'failed', error_msg = 'stale_pending', stopped_at = now()+ WHERE status = 'pending' AND started_at < now() - $1::interval+ RETURNING sandbox_id, org_id, worker_id`,+ fmt.Sprintf("%d seconds", int(olderThan.Seconds())))+ if err != nil {+ return nil, fmt.Errorf("reap stale pending: %w", err)+ }+ var reaped []OrphanedSandbox+ for upd.Next() {+ var o OrphanedSandbox+ if err := upd.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); err == nil {+ reaped = append(reaped, o)+ }+ }+ upd.Close()+ if len(reaped) == 0 {+ return nil, tx.Commit(ctx)+ }+ ids := make([]string, len(reaped))+ for i, o := range reaped {+ ids[i] = o.SandboxID+ }+ if err := closeOpenScaleEventsForSandboxes(ctx, tx, ids); err != nil {+ return nil, fmt.Errorf("reap stale pending: close scale events: %w", err)+ }+ if err := tx.Commit(ctx); err != nil {+ return nil, err+ }+ return reaped, nil+}+func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {session := &SandboxSession{}err := s.pool.QueryRow(ctx,