Skip to content

An open-source, faster Devin alternative

TypeScript

close event on pause for chart accuracy

Brian Reardona956d742ff9b
diff --git a/internal/db/pause.go b/internal/db/pause.go
index 29387901..d7365198 100644
--- a/internal/db/pause.go
+++ b/internal/db/pause.go
@@ -2,6 +2,7 @@ package db
import (
"context"
+ "fmt"
"time"
"github.com/google/uuid"
@@ -19,15 +20,45 @@ type PausedRef struct {
// tier: customer-visible status stays "hibernated", hibernation_mode becomes
// "paused", paused_at is stamped. CAS on status='running' so a concurrent
// stop/deep-hibernate/terminate wins cleanly. Returns whether a row changed.
+//
+// Paused = UNBILLED (the usage ticker skips paused boxes, so it never refreshes
+// the open scale_events row again). So — like every other transition that leaves
+// UpdateSandboxSessionStatus's inline close-out (see
+// closeOpenScaleEventsForSandboxes) — this must close the open billing row in
+// the SAME tx. Every pause path funnels through here (customer hibernate,
+// idle-timeout, migrate re-pause), so this is the one chokepoint. Missing it
+// left a scale_events row open on every pause since the pause tier shipped,
+// over-counting the usage chart and OVER-BILLING legacy (scale-event) orgs for
+// boxes that should be free. Resume re-opens a fresh row via the ticker's next
+// tick, so this only needs to close.
func (s *Store) SetSandboxPaused(ctx context.Context, sandboxID string) (bool, error) {
- tag, err := s.pool.Exec(ctx,
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return false, fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+
+ tag, err := tx.Exec(ctx,
`UPDATE sandbox_sessions
SET status = 'hibernated', hibernation_mode = 'paused', paused_at = now()
WHERE sandbox_id = $1 AND status = 'running'`, sandboxID)
if err != nil {
return false, err
}
- return tag.RowsAffected() > 0, nil
+ changed := tag.RowsAffected() > 0
+
+ // Only close on a real running→paused transition; a no-op CAS (already
+ // paused/terminal) must not touch a row a concurrent winner may own.
+ if changed {
+ if err := closeOpenScaleEventsForSandboxes(ctx, tx, []string{sandboxID}); err != nil {
+ return false, fmt.Errorf("close scale events: %w", err)
+ }
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ return false, fmt.Errorf("commit tx: %w", err)
+ }
+ return changed, nil
}
// SetSandboxResumed transitions a paused sandbox back to running (QMP cont on
diff --git a/internal/db/pause_scale_event_pgfixture_test.go b/internal/db/pause_scale_event_pgfixture_test.go
new file mode 100644
index 00000000..366f476c
--- /dev/null
+++ b/internal/db/pause_scale_event_pgfixture_test.go
@@ -0,0 +1,84 @@
+//go:build pgfixture
+
+// SetSandboxPaused must close the open sandbox_scale_events billing row in the
+// same tx. Paused is UNBILLED and the usage ticker stops refreshing the row, so
+// a left-open row accrues phantom GB-hours forever — the pause-tier billing leak
+// that over-counted the usage chart and over-billed legacy (scale-event) orgs.
+//
+// Run locally:
+//
+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \
+// go test -tags=pgfixture ./internal/db/ -run PausedScaleEvent -v
+package db
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+func TestSetSandboxPausedClosesOpenScaleEvent(t *testing.T) {
+ store := openPgStore(t)
+ ctx := context.Background()
+ org := uuid.New()
+ sb := "sb-pause-" + 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)
+ }
+ // Open a billing row — what the usage ticker does each tick for a running box.
+ if err := store.RecordScaleEvent(ctx, sb, org.String(), 4096, 0, 0); err != nil {
+ t.Fatalf("RecordScaleEvent: %v", err)
+ }
+ if got := openScaleEvents(t, store, sb); got != 1 {
+ t.Fatalf("precondition: want 1 open scale event, got %d", got)
+ }
+
+ // Pause: must flip the session AND close the open billing row.
+ changed, err := store.SetSandboxPaused(ctx, sb)
+ if err != nil {
+ t.Fatalf("SetSandboxPaused: %v", err)
+ }
+ if !changed {
+ t.Fatalf("SetSandboxPaused: want changed=true on running->paused")
+ }
+ if got := openScaleEvents(t, store, sb); got != 0 {
+ t.Errorf("after pause: want 0 open scale events (closed), got %d — phantom billing leak", got)
+ }
+
+ // Session reflects the paused tier.
+ var status, mode string
+ if err := store.pool.QueryRow(ctx,
+ `SELECT status, COALESCE(hibernation_mode, '') FROM sandbox_sessions WHERE sandbox_id = $1`, sb,
+ ).Scan(&status, &mode); err != nil {
+ t.Fatalf("read session: %v", err)
+ }
+ if status != "hibernated" || mode != "paused" {
+ t.Errorf("session state = (%s,%s), want (hibernated,paused)", status, mode)
+ }
+
+ // Idempotent CAS: a second pause is a no-op (already paused) — no error, and
+ // it must not touch a row a concurrent stop/terminate may own.
+ changed2, err := store.SetSandboxPaused(ctx, sb)
+ if err != nil {
+ t.Fatalf("SetSandboxPaused (repeat): %v", err)
+ }
+ if changed2 {
+ t.Errorf("SetSandboxPaused on already-paused box: want changed=false")
+ }
+}
+
+func openScaleEvents(t *testing.T, store *Store, sandboxID string) int {
+ t.Helper()
+ var n int
+ if err := store.pool.QueryRow(context.Background(),
+ `SELECT count(*) FROM sandbox_scale_events WHERE sandbox_id = $1 AND ended_at IS NULL`, sandboxID,
+ ).Scan(&n); err != nil {
+ t.Fatalf("count open scale events: %v", err)
+ }
+ return n
+}