An open-source, faster Devin alternative
TypeScript
make sure every failure path publishes stop
Brian Reardond2fa9ee6037e
diff --git a/cmd/server/main.go b/cmd/server/main.goindex cd67963e..3ea066e2 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -13,6 +13,7 @@ import ("syscall""time"+ "github.com/google/uuid""github.com/redis/go-redis/v9""github.com/opensandbox/opensandbox/internal/api"@@ -223,6 +224,20 @@ func main() {opts.RedisClient = redisRegistry.RedisClient()log.Println("opensandbox: Redis worker registry started")+ // Wire the terminal lifecycle publisher: any session that transitions to+ // a terminal state (stopped/error/failed) via UpdateSandboxSessionStatus+ // now publishes a `stopped` event → events-ingest → D1 → stop edge+ // billing. Closes the gap where create-failed / fork-failed /+ // proxy-worker-gone / stop-handler paths marked the cell terminal but+ // left D1 (and the edge) billing the sandbox forever.+ if opts.Store != nil && cfg.CellID != "" {+ rc := redisRegistry.RedisClient()+ cellID := cfg.CellID+ opts.Store.SetTerminalHook(func(sandboxID string, orgID uuid.UUID, status, reason string) {+ controlplane.PublishLifecycle(context.Background(), rc, cellID, "stopped", sandboxID, "", orgID, reason)+ })+ }+// Create sandbox API proxy for routing data-plane requests to workersif opts.Store != nil && opts.JWTIssuer != nil {opts.SandboxAPIProxy = proxy.NewSandboxAPIProxy(opts.Store, redisRegistry, opts.JWTIssuer)diff --git a/internal/controlplane/reconcile.go b/internal/controlplane/reconcile.goindex c6d265ad..d9140aef 100644--- a/internal/controlplane/reconcile.go+++ b/internal/controlplane/reconcile.go@@ -2,14 +2,10 @@ 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")@@ -18,15 +14,16 @@ import (// 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.+//+// 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@@ -102,30 +99,31 @@ func isSandboxNotFound(err error) bool {// 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.+// 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.+//+// 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+// 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 D1func ReconcileRunningOnWorker(ctx context.Context, registry *RedisWorkerRegistry, store *db.Store, cellID, workerID string) {if store == nil || registry == nil {return@@ -168,10 +166,11 @@ func ReconcileRunningOnWorker(ctx context.Context, registry *RedisWorkerRegistryalive++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).+ // Close the cell-side state. UpdateSandboxSessionStatus(stopped) does the+ // status flip, closes any open scale event, AND fires the terminal hook+ // that publishes the `stopped` lifecycle event to D1 — all in one place.+ // The explicit EndScaleEvent below is now belt-and-suspenders (the status+ // update already closed it) on this billing-critical reconcile path.errMsg := reasonif err := store.UpdateSandboxSessionStatus(ctx, ref.SandboxID, "stopped", &errMsg); err != nil {log.Printf("controlplane: reverse-reconcile %s: UpdateSandboxSessionStatus %s: %v", workerID, ref.SandboxID, err)@@ -179,50 +178,8 @@ func ReconcileRunningOnWorker(ctx context.Context, registry *RedisWorkerRegistry}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 3a0aa158..3ee03c43 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -23,15 +23,34 @@ var migrationsFS embed.FS// Store provides data access to the global PostgreSQL database.type Store struct {- pool *pgxpool.Pool- encryptor *crypto.Encryptor // nil if no encryption key configured-}+ pool *pgxpool.Pool+ encryptor *crypto.Encryptor // nil if no encryption key configured+ onTerminal TerminalHook // nil if not wired; fires after a terminal session transition commits+}++// TerminalHook is invoked after UpdateSandboxSessionStatus commits a transition+// to a terminal state (stopped/error/failed). It exists so callers can publish+// the `stopped` lifecycle event to the cell's events stream — without it, the+// edge (D1 sandboxes_index / CreditAccount DO) keeps the row at `running` and+// bills it forever. Every terminal transition funnels through one place, so no+// individual call site can forget to publish (the failure mode #361 left in the+// create-failed / fork-failed / proxy-worker-gone / stop-handler paths).+//+// Fired best-effort AFTER the DB commit; a publish failure never fails the DB+// write. workerID is intentionally omitted (the sandbox is leaving its worker).+type TerminalHook func(sandboxID string, orgID uuid.UUID, status, reason string)// SetEncryptor configures the encryption key for project secrets.func (s *Store) SetEncryptor(enc *crypto.Encryptor) {s.encryptor = enc}+// SetTerminalHook wires the lifecycle publisher (see TerminalHook). Set once at+// startup on the server/worker store. Safe to leave unset (e.g. in tests).+func (s *Store) SetTerminalHook(h TerminalHook) {+ s.onTerminal = h+}+// Encryptor exposes the configured encryption helper so callers outside the// db package (edgeclient.LookupSecretStore, etc.) can decrypt with the same// shared SECRET_ENCRYPTION_KEY without holding their own copy.@@ -190,14 +209,14 @@ type Org struct {UpdatedAt time.Time `json:"updatedAt"`// Custom domain fields- CustomDomain *string `json:"customDomain,omitempty"`- CFHostnameID *string `json:"cfHostnameId,omitempty"`- DomainVerificationStatus string `json:"domainVerificationStatus"`- DomainSSLStatus string `json:"domainSslStatus"`- VerificationTxtName *string `json:"verificationTxtName,omitempty"`- VerificationTxtValue *string `json:"verificationTxtValue,omitempty"`- SSLTxtName *string `json:"sslTxtName,omitempty"`- SSLTxtValue *string `json:"sslTxtValue,omitempty"`+ CustomDomain *string `json:"customDomain,omitempty"`+ CFHostnameID *string `json:"cfHostnameId,omitempty"`+ DomainVerificationStatus string `json:"domainVerificationStatus"`+ DomainSSLStatus string `json:"domainSslStatus"`+ VerificationTxtName *string `json:"verificationTxtName,omitempty"`+ VerificationTxtValue *string `json:"verificationTxtValue,omitempty"`+ SSLTxtName *string `json:"sslTxtName,omitempty"`+ SSLTxtValue *string `json:"sslTxtValue,omitempty"`// WorkOS organization fieldsWorkOSOrgID *string `json:"workosOrgId,omitempty"`@@ -211,10 +230,10 @@ type Org struct {FreeCreditsRemainingCents int64 `json:"freeCreditsRemainingCents"`// Stripe billing fields- StripeCustomerID *string `json:"stripeCustomerId,omitempty"`- StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`- LastUsageReportedAt time.Time `json:"lastUsageReportedAt"`- PriceLocked bool `json:"priceLocked"`+ StripeCustomerID *string `json:"stripeCustomerId,omitempty"`+ StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`+ LastUsageReportedAt time.Time `json:"lastUsageReportedAt"`+ PriceLocked bool `json:"priceLocked"`// Per-org billing pipeline selector. 'legacy' = UsageReporter ships// to Stripe; 'unified' = the phase-3 sender ships from@@ -650,29 +669,29 @@ func (s *Store) DeleteAPIKeyForOrg(ctx context.Context, id uuid.UUID, orgID uuid// --- Sandbox Session operations ---type SandboxSession struct {- ID uuid.UUID `json:"id"`- SandboxID string `json:"sandboxId"`- OrgID uuid.UUID `json:"orgId"`- UserID *uuid.UUID `json:"userId,omitempty"`- Template string `json:"template"`- Region string `json:"region"`- WorkerID string `json:"workerId"`- Status string `json:"status"`- Config json.RawMessage `json:"config"`- Metadata json.RawMessage `json:"metadata,omitempty"`- StartedAt time.Time `json:"startedAt"`- StoppedAt *time.Time `json:"stoppedAt,omitempty"`- ErrorMsg *string `json:"errorMsg,omitempty"`- BasedOnCheckpointID *uuid.UUID `json:"basedOnCheckpointId,omitempty"`- LastPatchSequence int `json:"lastPatchSequence"`- MigratingToWorker string `json:"migratingToWorker,omitempty"`- PatchError *string `json:"patchError,omitempty"`- GoldenVersion *string `json:"goldenVersion,omitempty"`+ ID uuid.UUID `json:"id"`+ SandboxID string `json:"sandboxId"`+ OrgID uuid.UUID `json:"orgId"`+ UserID *uuid.UUID `json:"userId,omitempty"`+ Template string `json:"template"`+ Region string `json:"region"`+ WorkerID string `json:"workerId"`+ Status string `json:"status"`+ Config json.RawMessage `json:"config"`+ Metadata json.RawMessage `json:"metadata,omitempty"`+ StartedAt time.Time `json:"startedAt"`+ StoppedAt *time.Time `json:"stoppedAt,omitempty"`+ ErrorMsg *string `json:"errorMsg,omitempty"`+ BasedOnCheckpointID *uuid.UUID `json:"basedOnCheckpointId,omitempty"`+ LastPatchSequence int `json:"lastPatchSequence"`+ MigratingToWorker string `json:"migratingToWorker,omitempty"`+ PatchError *string `json:"patchError,omitempty"`+ GoldenVersion *string `json:"goldenVersion,omitempty"`// PreviewAuthHash is the SHA-256 hex of the bearer token required on// preview-URL requests. NULL = open (the default). Plaintext is never// stored — set once via SetSandboxPreviewAuth and rotated via the same.- PreviewAuthHash *string `json:"-"`- PreviewAuthScheme *string `json:"-"`+ PreviewAuthHash *string `json:"-"`+ PreviewAuthScheme *string `json:"-"`}// SetSandboxPreviewAuth installs or rotates the per-sandbox bearer-token gate@@ -759,6 +778,12 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statuargs = []interface{}{status, sandboxID}}+ // Terminal = the sandbox is no longer running and should stop billing.+ // `failed` (pending→failed, create never succeeded) is terminal too — it+ // was previously omitted from both the scale-event close and any D1 publish,+ // which let failed-creates bill forever on the edge.+ terminal := status == "stopped" || status == "error" || status == "failed"+tx, err := s.pool.Begin(ctx)if err != nil {return fmt.Errorf("failed to begin tx: %w", err)@@ -772,16 +797,32 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu// Close any open scale_events when the session actually transitioned to a// non-billable state. Tied to the same tx as the session update so the- // usage reporter can never observe a stopped/hibernated session with an- // ended_at IS NULL scale_event (which would keep billing the window).- if tag.RowsAffected() > 0 && (status == "stopped" || status == "hibernated" || status == "error") {+ // usage reporter can never observe a stopped/hibernated/failed session with+ // an ended_at IS NULL scale_event (which would keep billing the window).+ var orgID uuid.UUID+ if tag.RowsAffected() > 0 && (terminal || status == "hibernated") {if _, err := tx.Exec(ctx,`UPDATE sandbox_scale_events SET ended_at = now()WHERE sandbox_id = $1 AND ended_at IS NULL`, sandboxID); err != nil {return fmt.Errorf("failed to close scale events: %w", err)}+ // Capture org for the lifecycle publish below (same tx; cheap).+ _ = tx.QueryRow(ctx,+ `SELECT org_id FROM sandbox_sessions WHERE sandbox_id = $1`, sandboxID).Scan(&orgID)}- return tx.Commit(ctx)+ if err := tx.Commit(ctx); err != nil {+ return err+ }++ // Fire the lifecycle publish AFTER the commit so the edge (D1 / CreditAccount+ // DO) flips the row running→stopped and stops billing. Best-effort: a publish+ // failure must not fail an already-committed DB write. Only on a real terminal+ // transition that affected a row (hibernated is NOT a stop — billing pauses,+ // the sandbox can wake — so it keeps its own dedicated event path).+ if terminal && tag.RowsAffected() > 0 && s.onTerminal != nil {+ s.onTerminal(sandboxID, orgID, status, "session_terminal:"+status)+ }+ return nil}// SetMigrating marks a sandbox as migrating to a target worker.diff --git a/internal/db/terminal_hook_pgfixture_test.go b/internal/db/terminal_hook_pgfixture_test.gonew file mode 100644index 00000000..3c5fe0f4--- /dev/null+++ b/internal/db/terminal_hook_pgfixture_test.go@@ -0,0 +1,140 @@+//go:build pgfixture++// Verifies the terminal lifecycle hook: UpdateSandboxSessionStatus must fire+// the hook exactly on terminal transitions (stopped/error/failed) and never on+// non-terminal ones (running) or on hibernated (a pause, not a stop). This is+// the guarantee that every cell-side terminal transition publishes a `stopped`+// event to D1 — the gap that left create-failed / fork-failed / proxy-worker-+// gone / stop-handler paths billing the edge forever.+//+// Run locally:+//+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \+// go test -tags=pgfixture ./internal/db/ -run TerminalHook -v+package db++import (+ "context"+ "encoding/json"+ "sync"+ "testing"++ "github.com/google/uuid"+)++func TestTerminalHookFiresOnlyOnTerminalTransitions(t *testing.T) {+ store := openPgStore(t)+ ctx := context.Background()++ type fired struct {+ sandboxID string+ orgID uuid.UUID+ status string+ reason string+ }+ var mu sync.Mutex+ var events []fired+ store.SetTerminalHook(func(sandboxID string, orgID uuid.UUID, status, reason string) {+ mu.Lock()+ events = append(events, fired{sandboxID, orgID, status, reason})+ mu.Unlock()+ })++ // Fresh org per run isolates state; derive unique sandbox IDs from it so+ // re-runs against the same DB don't collide on the sandbox_id key.+ org := uuid.New()+ pfx := "sb-hook-" + org.String()[:8] + "-"+ cfg := json.RawMessage(`{}`)+ seed := func(sb, status string) {+ if _, err := store.CreateSandboxSessionWithStatus(+ ctx, sb, org, nil, "base", "test", "w-test", cfg, cfg, status, nil); err != nil {+ t.Fatalf("seed %s (%s): %v", sb, status, err)+ }+ }++ // --- terminal transitions: MUST fire ---+ // running -> stopped, running -> error+ for _, status := range []string{"stopped", "error"} {+ sb := pfx + status+ seed(sb, "running")+ if err := store.UpdateSandboxSessionStatus(ctx, sb, status, nil); err != nil {+ t.Fatalf("UpdateSandboxSessionStatus(%s): %v", status, err)+ }+ }+ // pending -> failed (create never succeeded)+ {+ sb := pfx + "failed"+ seed(sb, "pending")+ em := "worker create failed"+ if err := store.UpdateSandboxSessionStatus(ctx, sb, "failed", &em); err != nil {+ t.Fatalf("UpdateSandboxSessionStatus(failed): %v", err)+ }+ }++ // --- non-terminal: MUST NOT fire ---+ // pending -> running (promotion)+ {+ sb := pfx + "running"+ seed(sb, "pending")+ if err := store.UpdateSandboxSessionStatus(ctx, sb, "running", nil); err != nil {+ t.Fatalf("UpdateSandboxSessionStatus(running): %v", err)+ }+ }+ // running -> hibernated (pause, not stop — has its own event path)+ {+ sb := pfx + "hibernated"+ seed(sb, "running")+ if err := store.UpdateSandboxSessionStatus(ctx, sb, "hibernated", nil); err != nil {+ t.Fatalf("UpdateSandboxSessionStatus(hibernated): %v", err)+ }+ }+ // a no-op transition (sandbox not found / wrong precondition) MUST NOT fire+ if err := store.UpdateSandboxSessionStatus(ctx, pfx+"ghost", "stopped", nil); err != nil {+ t.Fatalf("UpdateSandboxSessionStatus(ghost): %v", err)+ }++ mu.Lock()+ defer mu.Unlock()++ byStatus := map[string]fired{}+ for _, e := range events {+ byStatus[e.status] = e+ if e.orgID != org {+ t.Errorf("hook fired with org %s, want %s (sandbox %s)", e.orgID, org, e.sandboxID)+ }+ if e.reason != "session_terminal:"+e.status {+ t.Errorf("hook reason = %q, want %q", e.reason, "session_terminal:"+e.status)+ }+ }++ for _, want := range []string{"stopped", "error", "failed"} {+ if _, ok := byStatus[want]; !ok {+ t.Errorf("expected hook to fire for terminal status %q, but it did not", want)+ }+ }+ for _, notWant := range []string{"running", "hibernated"} {+ if _, ok := byStatus[notWant]; ok {+ t.Errorf("hook fired for non-terminal status %q; it must not", notWant)+ }+ }+ if len(events) != 3 {+ t.Errorf("expected exactly 3 hook fires (stopped/error/failed), got %d: %+v", len(events), events)+ }+}++// A store with no hook wired must not panic on terminal transitions.+func TestTerminalHookUnsetIsSafe(t *testing.T) {+ store := openPgStore(t)+ ctx := context.Background()+ org := uuid.New()+ sb := "sb-nohook-" + org.String()[:8]+ cfg := json.RawMessage(`{}`)+ if _, err := store.CreateSandboxSessionWithStatus(+ ctx, sb, org, nil, "base", "test", "w-test", cfg, cfg, "running", nil); err != nil {+ t.Fatalf("seed: %v", err)+ }+ // onTerminal is nil here — must be a no-op, not a panic.+ if err := store.UpdateSandboxSessionStatus(ctx, sb, "stopped", nil); err != nil {+ t.Fatalf("UpdateSandboxSessionStatus(stopped) with no hook: %v", err)+ }+}