Skip to content

An open-source, faster Devin alternative

TypeScript

Replace getSandboxUsage with points + totals shape

Igor Zalutskib9ee6c940fa8
diff --git a/internal/api/usage.go b/internal/api/usage.go
index 4862b0f4..35421135 100644
--- a/internal/api/usage.go
+++ b/internal/api/usage.go
@@ -288,7 +288,20 @@ func (s *Server) listTags(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]interface{}{"keys": keys})
}
+// sandboxUsageDefaultWindow is the default lookback when callers omit
+// `from`/`to`. v1 of the new shape (per
+// .agents/design/per-sandbox-usage-api.md) treats the per-sandbox
+// endpoint as a "what's it doing now" surface, so the default is short.
+// Longer-range queries are deliberately a different tool — the
+// aggregator at /api/usage.
+const sandboxUsageDefaultWindow = time.Hour
+
// getSandboxUsage → GET /api/sandboxes/:id/usage
+//
+// Returns 1-minute points + envelope totals for memory allocation and
+// utilization over [from, to). Window capped at 30 days (enforced in
+// db.SandboxUsagePoints). v1 is memory only; CPU joins symmetrically
+// once usage_collector.go starts populating cpu_usec.
func (s *Server) getSandboxUsage(c echo.Context) error {
sandboxID := c.Param("id")
if err := s.ownsSandbox(c, sandboxID); err != nil {
@@ -298,7 +311,7 @@ func (s *Server) getSandboxUsage(c echo.Context) error {
orgID, _ := auth.GetOrgID(c)
now := time.Now().UTC()
- from, to := now.Add(-usageDefaultWindow), now
+ from, to := now.Add(-sandboxUsageDefaultWindow), now
if s := c.QueryParam("from"); s != "" {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
@@ -313,59 +326,41 @@ func (s *Server) getSandboxUsage(c echo.Context) error {
}
to = t
}
- if !to.After(from) {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "`to` must be after `from`"})
- }
- if to.Sub(from) > 90*24*time.Hour {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "query window must be <= 90 days"})
- }
ctx, cancel := context.WithTimeout(c.Request().Context(), usageHandlerTimeout)
defer cancel()
- mem, disk, firstStarted, lastEnded, err := s.store.SandboxUsageWindow(ctx, orgID, sandboxID, from, to)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
- }
-
- sess, _ := s.store.GetSandboxSessionInOrg(ctx, orgID, sandboxID)
- tagSet, err := s.store.GetSandboxTags(ctx, orgID, sandboxID)
+ points, totals, err := s.store.SandboxUsagePoints(ctx, orgID, sandboxID, from, to)
if err != nil {
+ // validateSandboxUsageWindow surfaces these strings; map to 400.
+ if msg := err.Error(); strings.Contains(msg, "must be after") ||
+ strings.Contains(msg, "query window must be") {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": msg})
+ }
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
- if tagSet.Tags == nil {
- tagSet.Tags = map[string]string{}
+ if points == nil {
+ // Guarantee a non-null `points` array in the response so SDK
+ // consumers don't have to special-case empty windows.
+ points = []db.UsagePoint{}
}
resp := map[string]interface{}{
- "sandboxId": sandboxID,
- "from": from.UTC().Format(time.RFC3339),
- "to": to.UTC().Format(time.RFC3339),
- "memoryGbSeconds": mem,
- "diskOverageGbSeconds": disk,
- "tags": tagSet.Tags,
- }
- if sess != nil {
- resp["status"] = sess.Status
+ "sandboxId": sandboxID,
+ "from": from.UTC().Format(time.RFC3339),
+ "to": to.UTC().Format(time.RFC3339),
+ "totals": totals,
+ "points": points,
+ }
+
+ // Alias is cheap and useful for CLI/dashboard contexts; impl plan Q1
+ // recommended keeping it. Tags/status/etc. live on /api/sandboxes/:id.
+ if sess, err := s.store.GetSandboxSessionInOrg(ctx, orgID, sandboxID); err == nil && sess != nil {
if alias := aliasFromConfig(sess.Config); alias != "" {
resp["alias"] = alias
}
}
- if tagSet.LastUpdatedAt != nil {
- resp["tagsLastUpdatedAt"] = tagSet.LastUpdatedAt.UTC().Format(time.RFC3339)
- } else {
- resp["tagsLastUpdatedAt"] = nil
- }
- if firstStarted != nil {
- resp["firstStartedAt"] = firstStarted.UTC().Format(time.RFC3339)
- } else {
- resp["firstStartedAt"] = nil
- }
- if lastEnded != nil {
- resp["lastEndedAt"] = lastEnded.UTC().Format(time.RFC3339)
- } else {
- resp["lastEndedAt"] = nil
- }
+
return c.JSON(http.StatusOK, resp)
}
diff --git a/internal/db/usage_points.go b/internal/db/usage_points.go
new file mode 100644
index 00000000..ba479904
--- /dev/null
+++ b/internal/db/usage_points.go
@@ -0,0 +1,203 @@
+package db
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// Per-sandbox usage points. See design at
+// .agents/design/per-sandbox-usage-api.md and impl plan at
+// .agents/work/per-sandbox-usage-api-impl.md.
+//
+// One row per 1-minute bucket in [from, to). Buckets are minute-aligned
+// in UTC, not aligned to `from`. Allocation integrals come from
+// sandbox_scale_events using the same math as GetOrgUsage so totals
+// reconcile to the billing pipeline by construction. Used memory comes
+// from sandbox_usage_samples (cgroup memory.current).
+//
+// v1 is memory only. CPU mirrors this shape once usage_collector.go
+// stops writing CPUUsec: 0 (see design / "Out of scope").
+
+const usagePointsMaxWindow = 30 * 24 * time.Hour
+
+// UsagePoint is one minute bucket of memory usage for a sandbox.
+// Integrals (*GbSeconds, UptimeSeconds) compose by summation;
+// snapshot scalars (AllocatedMemoryMb, UsedMemoryMb*) are for chart
+// rendering and do not compose.
+type UsagePoint struct {
+ Timestamp time.Time `json:"ts"`
+ MemoryAllocatedGbSeconds float64 `json:"memoryAllocatedGbSeconds"`
+ MemoryUsedGbSeconds float64 `json:"memoryUsedGbSeconds"`
+ UptimeSeconds int `json:"uptimeSeconds"`
+ AllocatedMemoryMb int `json:"allocatedMemoryMb"`
+ UsedMemoryMbAvg int `json:"usedMemoryMbAvg"`
+ UsedMemoryMbPeak int `json:"usedMemoryMbPeak"`
+}
+
+// SandboxUsageTotals are envelope totals over [from, to). Computed by
+// summing the materialized points in Go (not by a separate aggregate
+// query), so SUM(points.MemoryAllocatedGbSeconds) ==
+// totals.MemoryAllocatedGbSeconds holds exactly. Same for the used
+// integral and uptime.
+type SandboxUsageTotals struct {
+ MemoryAllocatedGbSeconds float64 `json:"memoryAllocatedGbSeconds"`
+ MemoryUsedGbSeconds float64 `json:"memoryUsedGbSeconds"`
+ UptimeSeconds int `json:"uptimeSeconds"`
+ MemoryAllocatedPeakMb int `json:"memoryAllocatedPeakMb"`
+ MemoryUsedPeakMb int `json:"memoryUsedPeakMb"`
+}
+
+// buildSandboxUsagePointsQuery returns SQL + args. Split out from
+// SandboxUsagePoints so pure-Go tests can assert shape without a
+// Postgres connection. Inputs are validated; callers pass already-
+// validated [from, to).
+func buildSandboxUsagePointsQuery(orgID uuid.UUID, sandboxID string, from, to time.Time) (string, []any) {
+ args := []any{orgID, sandboxID, from, to}
+ // $1 = orgID, $2 = sandboxID, $3 = from, $4 = to.
+ //
+ // Bucket grid: minute-aligned in UTC. The last bucket is the one
+ // whose start time is strictly less than `to`, found via
+ // date_trunc('minute', $4 - 1us). Boundary buckets may be partial
+ // (sample filter is [from, to); allocation overlap is per-bucket
+ // without further clamping). This is the trade-off documented in
+ // Q2 of the impl plan.
+ //
+ // Allocation: time-weighted via SUM(memory_mb * overlap_seconds).
+ // The overlap expression mirrors GetOrgUsage's clamp idiom so the
+ // reconciliation invariant (Σ points.MemoryAllocatedGbSeconds ==
+ // GetOrgUsage allocated total) holds without bespoke math.
+ //
+ // Used memory: AVG/MAX over samples that fall in the bucket. At
+ // the 60s collector cadence there is usually one sample per
+ // bucket; the aggregates absorb the rare clock-skew duplicate.
+ sql := `
+WITH buckets AS (
+ SELECT
+ ts,
+ ts + interval '1 minute' AS ts_end
+ FROM generate_series(
+ date_trunc('minute', $3::timestamptz),
+ date_trunc('minute', $4::timestamptz - interval '1 microsecond'),
+ interval '1 minute'
+ ) AS ts
+),
+samples AS (
+ SELECT
+ date_trunc('minute', sampled_at) AS bucket_ts,
+ AVG(memory_bytes)::bigint AS memory_bytes_avg,
+ MAX(memory_bytes) AS memory_bytes_peak
+ FROM sandbox_usage_samples
+ WHERE org_id = $1
+ AND sandbox_id = $2
+ AND sampled_at >= $3
+ AND sampled_at < $4
+ GROUP BY date_trunc('minute', sampled_at)
+),
+allocated AS (
+ SELECT
+ b.ts AS bucket_ts,
+ SUM(
+ e.memory_mb::float
+ * EXTRACT(EPOCH FROM (
+ LEAST(COALESCE(e.ended_at, $4::timestamptz), b.ts_end)
+ - GREATEST(e.started_at, b.ts)
+ ))
+ ) / 60.0 AS weighted_memory_mb,
+ SUM(
+ e.memory_mb::float / 1024.0
+ * EXTRACT(EPOCH FROM (
+ LEAST(COALESCE(e.ended_at, $4::timestamptz), b.ts_end)
+ - GREATEST(e.started_at, b.ts)
+ ))
+ ) AS gb_seconds
+ FROM buckets b
+ LEFT JOIN sandbox_scale_events e
+ ON e.org_id = $1
+ AND e.sandbox_id = $2
+ AND e.started_at < b.ts_end
+ AND (e.ended_at IS NULL OR e.ended_at > b.ts)
+ GROUP BY b.ts
+)
+SELECT
+ b.ts,
+ COALESCE(a.gb_seconds, 0)::float AS memory_allocated_gb_seconds,
+ COALESCE(a.weighted_memory_mb, 0)::int AS allocated_memory_mb,
+ COALESCE(s.memory_bytes_avg::float / 1e9 * 60, 0) AS memory_used_gb_seconds,
+ COALESCE((s.memory_bytes_avg / 1024 / 1024)::int, 0) AS used_memory_mb_avg,
+ COALESCE((s.memory_bytes_peak / 1024 / 1024)::int, 0) AS used_memory_mb_peak,
+ CASE WHEN s.bucket_ts IS NOT NULL THEN 60 ELSE 0 END AS uptime_seconds
+FROM buckets b
+LEFT JOIN samples s ON s.bucket_ts = b.ts
+LEFT JOIN allocated a ON a.bucket_ts = b.ts
+ORDER BY b.ts`
+ return sql, args
+}
+
+// validateSandboxUsageWindow rejects windows outside the contract.
+// Split out so the handler can return 400s with the same error text.
+func validateSandboxUsageWindow(from, to time.Time) error {
+ if !to.After(from) {
+ return errors.New("`to` must be after `from`")
+ }
+ if to.Sub(from) > usagePointsMaxWindow {
+ return fmt.Errorf("query window must be <= %d days", int(usagePointsMaxWindow/(24*time.Hour)))
+ }
+ return nil
+}
+
+// SandboxUsagePoints returns one UsagePoint per minute in [from, to) and
+// the envelope totals. Totals are computed from the materialized points
+// to guarantee Σ points.* == totals.* exactly.
+//
+// Callers must validate org ownership of sandboxID before invoking;
+// this function performs no auth check (it only filters the query by
+// org_id, which is necessary but not sufficient for ownership).
+func (s *Store) SandboxUsagePoints(ctx context.Context, orgID uuid.UUID, sandboxID string, from, to time.Time) ([]UsagePoint, SandboxUsageTotals, error) {
+ if err := validateSandboxUsageWindow(from, to); err != nil {
+ return nil, SandboxUsageTotals{}, err
+ }
+
+ sql, args := buildSandboxUsagePointsQuery(orgID, sandboxID, from, to)
+ rows, err := s.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, SandboxUsageTotals{}, fmt.Errorf("sandbox usage points query: %w", err)
+ }
+ defer rows.Close()
+
+ var points []UsagePoint
+ var totals SandboxUsageTotals
+ for rows.Next() {
+ var p UsagePoint
+ if err := rows.Scan(
+ &p.Timestamp,
+ &p.MemoryAllocatedGbSeconds,
+ &p.AllocatedMemoryMb,
+ &p.MemoryUsedGbSeconds,
+ &p.UsedMemoryMbAvg,
+ &p.UsedMemoryMbPeak,
+ &p.UptimeSeconds,
+ ); err != nil {
+ return nil, SandboxUsageTotals{}, fmt.Errorf("scan usage point: %w", err)
+ }
+ points = append(points, p)
+
+ totals.MemoryAllocatedGbSeconds += p.MemoryAllocatedGbSeconds
+ totals.MemoryUsedGbSeconds += p.MemoryUsedGbSeconds
+ totals.UptimeSeconds += p.UptimeSeconds
+ if p.AllocatedMemoryMb > totals.MemoryAllocatedPeakMb {
+ totals.MemoryAllocatedPeakMb = p.AllocatedMemoryMb
+ }
+ if p.UsedMemoryMbPeak > totals.MemoryUsedPeakMb {
+ totals.MemoryUsedPeakMb = p.UsedMemoryMbPeak
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, SandboxUsageTotals{}, fmt.Errorf("rows.Err: %w", err)
+ }
+
+ return points, totals, nil
+}
diff --git a/internal/db/usage_points_pgfixture_test.go b/internal/db/usage_points_pgfixture_test.go
new file mode 100644
index 00000000..2c2d3094
--- /dev/null
+++ b/internal/db/usage_points_pgfixture_test.go
@@ -0,0 +1,231 @@
+//go:build pgfixture
+
+// Per-sandbox usage-points correctness against real Postgres. Runs only
+// under `go test -tags=pgfixture` with TEST_DATABASE_URL set. The pure-
+// Go tests in usage_points_test.go cover SQL shape and validation but
+// cannot exercise generate_series, the LEAST/GREATEST overlap clamp,
+// or the reconciliation invariant against GetOrgUsage. Those live here.
+//
+// Run locally:
+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \
+// go test -tags=pgfixture ./internal/db/ -run UsagePoints -v
+package db
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// seedSandboxUsagePointsFixture writes a deterministic set of scale
+// events and usage samples for a single sandbox, scoped to a fresh
+// org UUID so repeated runs don't leak state.
+//
+// Layout (t0 = `from`):
+//
+// scale_event #1: [t0-1h, t0+6h30s), memory_mb=2048
+// scale_event #2: [t0+6h30s, t0+18h), memory_mb=4096
+//
+// samples Phase A: t0 .. t0+(6h-1m) 360 rows, memory_bytes=1.4 GB
+// samples Phase B: t0+6h .. t0+(8h-1m) 120 rows, memory_bytes=2.8 GB
+// samples GAP: t0+8h .. t0+(9h-1m) no rows (60 missing buckets)
+// samples Phase C: t0+9h .. t0+(18h-1m) 540 rows, memory_bytes=3.5 GB
+// (no samples after t0+18h — sandbox stopped)
+//
+// This shape exercises: resize event mid-bucket (bucket 360), a gap
+// where the scale event is still open (allocation accrues, uptime
+// reads 0), and post-stop buckets (both zero).
+func seedSandboxUsagePointsFixture(t *testing.T, store *Store, orgID uuid.UUID, sandboxID string, t0 time.Time) {
+ t.Helper()
+ ctx := context.Background()
+
+ resizeAt := t0.Add(6*time.Hour + 30*time.Second)
+ stoppedAt := t0.Add(18 * time.Hour)
+
+ insertSE := func(memMB int, started, ended time.Time) {
+ if _, err := store.pool.Exec(ctx,
+ `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ sandboxID, orgID, memMB, memMB/40, 20480, started, ended); err != nil {
+ t.Fatalf("seed scale event: %v", err)
+ }
+ }
+ insertSamples := func(startMin, endMin int, memMB int, memBytes int64) {
+ startTs := t0.Add(time.Duration(startMin) * time.Minute)
+ endTs := t0.Add(time.Duration(endMin) * time.Minute)
+ if _, err := store.pool.Exec(ctx, `
+ INSERT INTO sandbox_usage_samples
+ (sandbox_id, org_id, sampled_at, memory_mb, cpu_usec, memory_bytes, pids)
+ SELECT $1, $2, gs.ts, $3, 0, $4, 1
+ FROM generate_series($5::timestamptz, $6::timestamptz - interval '1 minute', interval '1 minute') AS gs(ts)
+ ON CONFLICT DO NOTHING`,
+ sandboxID, orgID, memMB, memBytes, startTs, endTs); err != nil {
+ t.Fatalf("seed samples %d..%d: %v", startMin, endMin, err)
+ }
+ }
+
+ insertSE(2048, t0.Add(-1*time.Hour), resizeAt)
+ insertSE(4096, resizeAt, stoppedAt)
+
+ insertSamples(0, 6*60, 2048, 1_400_000_000) // Phase A
+ insertSamples(6*60, 8*60, 4096, 2_800_000_000) // Phase B
+ // Gap: 8*60..9*60 — no samples
+ insertSamples(9*60, 18*60, 4096, 3_500_000_000) // Phase C
+}
+
+// TestSandboxUsagePoints_Shape_pgfixture asserts the bucket grid, the
+// time-weighted allocation across the resize bucket, the gap-with-open-
+// allocation behavior, and the post-stop zero buckets.
+func TestSandboxUsagePoints_Shape_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ orgID := uuid.New()
+ sandboxID := "sbx-usage-shape"
+ t0 := time.Now().UTC().Truncate(time.Hour).Add(-24 * time.Hour)
+ to := t0.Add(24 * time.Hour)
+ seedSandboxUsagePointsFixture(t, store, orgID, sandboxID, t0)
+
+ points, totals, err := store.SandboxUsagePoints(ctx, orgID, sandboxID, t0, to)
+ if err != nil {
+ t.Fatalf("SandboxUsagePoints: %v", err)
+ }
+
+ if got, want := len(points), 24*60; got != want {
+ t.Fatalf("len(points) = %d, want %d", got, want)
+ }
+
+ // Bucket 0 — phase A, sample present.
+ p0 := points[0]
+ if !p0.Timestamp.Equal(t0) {
+ t.Errorf("points[0].Timestamp = %v, want %v", p0.Timestamp, t0)
+ }
+ if p0.AllocatedMemoryMb != 2048 {
+ t.Errorf("points[0].AllocatedMemoryMb = %d, want 2048", p0.AllocatedMemoryMb)
+ }
+ assertClose(t, "points[0].MemoryAllocatedGbSeconds", 120, p0.MemoryAllocatedGbSeconds)
+ if p0.UptimeSeconds != 60 {
+ t.Errorf("points[0].UptimeSeconds = %d, want 60", p0.UptimeSeconds)
+ }
+ assertClose(t, "points[0].MemoryUsedGbSeconds", 84, p0.MemoryUsedGbSeconds)
+
+ // Bucket 360 — resize at t0+6h+30s splits the bucket 50/50 between
+ // 2 GiB and 4 GiB tiers. Weighted allocated MB:
+ // (2048 * 30 + 4096 * 30) / 60 = 3072
+ // GB-seconds:
+ // (2048/1024) * 30 + (4096/1024) * 30 = 60 + 120 = 180
+ p360 := points[360]
+ if p360.AllocatedMemoryMb != 3072 {
+ t.Errorf("points[360].AllocatedMemoryMb = %d, want 3072 (resize bucket)", p360.AllocatedMemoryMb)
+ }
+ assertClose(t, "points[360].MemoryAllocatedGbSeconds (resize bucket)", 180, p360.MemoryAllocatedGbSeconds)
+
+ // Bucket 480 — inside the sample gap (t0+8h..t0+9h). Scale event 2
+ // is still open here so allocation accrues, but uptime reads 0.
+ p480 := points[480]
+ if p480.AllocatedMemoryMb != 4096 {
+ t.Errorf("points[480].AllocatedMemoryMb = %d, want 4096 (gap with open scale event)", p480.AllocatedMemoryMb)
+ }
+ assertClose(t, "points[480].MemoryAllocatedGbSeconds (gap)", 240, p480.MemoryAllocatedGbSeconds)
+ if p480.UptimeSeconds != 0 {
+ t.Errorf("points[480].UptimeSeconds = %d, want 0 (no sample in gap)", p480.UptimeSeconds)
+ }
+ if p480.UsedMemoryMbAvg != 0 {
+ t.Errorf("points[480].UsedMemoryMbAvg = %d, want 0 (no sample in gap)", p480.UsedMemoryMbAvg)
+ }
+
+ // Bucket 1080 — after stop (t0+18h). No scale event, no sample.
+ p1080 := points[1080]
+ if p1080.AllocatedMemoryMb != 0 || p1080.UptimeSeconds != 0 {
+ t.Errorf("points[1080] = %+v, want all zeros (post-stop)", p1080)
+ }
+ assertClose(t, "points[1080].MemoryAllocatedGbSeconds", 0, p1080.MemoryAllocatedGbSeconds)
+
+ // Totals sanity.
+ // Expected allocated_gb_seconds:
+ // event 1 in [t0, t0+6h30s) → 21630s × 2 GiB = 43260
+ // event 2 in [t0+6h30s, t0+18h) → 41370s × 4 GiB = 165480
+ // total = 208740 ... wait, recompute: 18h - 6h30s = 11h59m30s = 43170s
+ // 43170 * 4 = 172680
+ // Sum = 43260 + 172680 = 215940
+ assertClose(t, "totals.MemoryAllocatedGbSeconds", 215940, totals.MemoryAllocatedGbSeconds)
+ if totals.MemoryAllocatedPeakMb != 4096 {
+ t.Errorf("totals.MemoryAllocatedPeakMb = %d, want 4096", totals.MemoryAllocatedPeakMb)
+ }
+ if totals.UptimeSeconds != 1020*60 {
+ t.Errorf("totals.UptimeSeconds = %d, want %d (1020 sampled minutes)", totals.UptimeSeconds, 1020*60)
+ }
+}
+
+// TestSandboxUsagePoints_SumInvariant_pgfixture pins the contract that
+// Σ points.* == totals.* exactly (Go-side sum, not a separate query),
+// for every additive field. If this drifts, the response shape breaks
+// composability — a client summing points to reconstruct totals would
+// get a different number than the totals field.
+func TestSandboxUsagePoints_SumInvariant_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ orgID := uuid.New()
+ sandboxID := "sbx-usage-sum-invariant"
+ t0 := time.Now().UTC().Truncate(time.Hour).Add(-24 * time.Hour)
+ to := t0.Add(24 * time.Hour)
+ seedSandboxUsagePointsFixture(t, store, orgID, sandboxID, t0)
+
+ points, totals, err := store.SandboxUsagePoints(ctx, orgID, sandboxID, t0, to)
+ if err != nil {
+ t.Fatalf("SandboxUsagePoints: %v", err)
+ }
+
+ var sumAlloc, sumUsed float64
+ var sumUptime int
+ for _, p := range points {
+ sumAlloc += p.MemoryAllocatedGbSeconds
+ sumUsed += p.MemoryUsedGbSeconds
+ sumUptime += p.UptimeSeconds
+ }
+ assertClose(t, "Σ MemoryAllocatedGbSeconds == totals", totals.MemoryAllocatedGbSeconds, sumAlloc)
+ assertClose(t, "Σ MemoryUsedGbSeconds == totals", totals.MemoryUsedGbSeconds, sumUsed)
+ if sumUptime != totals.UptimeSeconds {
+ t.Errorf("Σ UptimeSeconds = %d, totals = %d", sumUptime, totals.UptimeSeconds)
+ }
+}
+
+// TestSandboxUsagePoints_Reconciliation_pgfixture pins the load-bearing
+// claim that totals.MemoryAllocatedGbSeconds == GetOrgUsage's rolled-up
+// allocated total for the same sandbox + window. If this drifts, the
+// new endpoint's "what would the bill say" answer disagrees with what
+// the Stripe pipeline actually reports — a silent correctness bug.
+func TestSandboxUsagePoints_Reconciliation_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ orgID := uuid.New()
+ sandboxID := "sbx-usage-reconcile"
+ t0 := time.Now().UTC().Truncate(time.Hour).Add(-24 * time.Hour)
+ to := t0.Add(24 * time.Hour)
+ seedSandboxUsagePointsFixture(t, store, orgID, sandboxID, t0)
+
+ _, totals, err := store.SandboxUsagePoints(ctx, orgID, sandboxID, t0, to)
+ if err != nil {
+ t.Fatalf("SandboxUsagePoints: %v", err)
+ }
+
+ // GetOrgUsage groups by (memory_mb, cpu_percent, disk_mb). Since we
+ // seeded exactly one sandbox, the org-level rollup IS this sandbox's
+ // rollup; allocated GB-seconds = SUM(memory_mb/1024 * total_seconds).
+ summaries, err := store.GetOrgUsage(ctx, orgID.String(), t0, to)
+ if err != nil {
+ t.Fatalf("GetOrgUsage: %v", err)
+ }
+ var rollupAlloc float64
+ for _, s := range summaries {
+ rollupAlloc += float64(s.MemoryMB) / 1024.0 * s.TotalSeconds
+ }
+ if rollupAlloc == 0 {
+ t.Fatal("expected GetOrgUsage to return non-zero allocated; fixture not seeded?")
+ }
+ assertClose(t, "totals.MemoryAllocatedGbSeconds vs GetOrgUsage", rollupAlloc, totals.MemoryAllocatedGbSeconds)
+}
diff --git a/internal/db/usage_points_test.go b/internal/db/usage_points_test.go
new file mode 100644
index 00000000..b3762220
--- /dev/null
+++ b/internal/db/usage_points_test.go
@@ -0,0 +1,114 @@
+package db
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// Pure-Go tests for the per-sandbox usage points query. SQL shape and
+// validation only — the load-bearing math is exercised by the
+// pgfixture suite (build tag `pgfixture`) which runs the query against
+// real Postgres and reconciles totals against GetOrgUsage.
+
+func TestBuildSandboxUsagePointsQuery_Shape(t *testing.T) {
+ from := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
+ to := from.Add(24 * time.Hour)
+ sql, args := buildSandboxUsagePointsQuery(uuid.New(), "sbx-1", from, to)
+
+ checks := map[string]string{
+ "minute-bucket generate_series": "generate_series(",
+ "date_trunc minute alignment": "date_trunc('minute',",
+ "sub-microsecond upper bound": "$4::timestamptz - interval '1 microsecond'",
+ "samples CTE filter on org": "WHERE org_id = $1",
+ "samples CTE filter on sandbox": "AND sandbox_id = $2",
+ "samples CTE bucket grouping": "GROUP BY date_trunc('minute', sampled_at)",
+ "scale-event overlap (LEAST clamp)": "LEAST(COALESCE(e.ended_at, $4::timestamptz), b.ts_end)",
+ "scale-event overlap (GREATEST)": "GREATEST(e.started_at, b.ts)",
+ "scale-event filter org-scoped": "e.org_id = $1",
+ "scale-event filter sandbox-scoped": "e.sandbox_id = $2",
+ "weighted memory_mb computation": "weighted_memory_mb",
+ "gb-seconds integration": "memory_mb::float / 1024.0",
+ "used GB-seconds from memory_bytes": "memory_bytes_avg::float / 1e9 * 60",
+ "uptime emitted as 60 or 0": "CASE WHEN s.bucket_ts IS NOT NULL THEN 60 ELSE 0 END",
+ "ordered by bucket timestamp": "ORDER BY b.ts",
+ }
+ for label, frag := range checks {
+ if !strings.Contains(sql, frag) {
+ t.Errorf("expected SQL to contain %q (%s)\n--- SQL ---\n%s", frag, label, sql)
+ }
+ }
+
+ // Args order is load-bearing — handler and SQL must agree.
+ if len(args) != 4 {
+ t.Fatalf("expected 4 args ($1..$4), got %d", len(args))
+ }
+ if _, ok := args[0].(uuid.UUID); !ok {
+ t.Errorf("arg[0] should be uuid.UUID (orgID), got %T", args[0])
+ }
+ if args[1] != "sbx-1" {
+ t.Errorf("arg[1] should be sandbox ID, got %v", args[1])
+ }
+ if args[2] != from {
+ t.Errorf("arg[2] should be `from`, got %v", args[2])
+ }
+ if args[3] != to {
+ t.Errorf("arg[3] should be `to`, got %v", args[3])
+ }
+}
+
+func TestValidateSandboxUsageWindow(t *testing.T) {
+ base := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
+ tests := []struct {
+ name string
+ from time.Time
+ to time.Time
+ wantErr string
+ }{
+ {
+ name: "ok 1h window",
+ from: base, to: base.Add(time.Hour),
+ },
+ {
+ name: "ok exactly 30d",
+ from: base, to: base.Add(30 * 24 * time.Hour),
+ },
+ {
+ name: "to equals from",
+ from: base,
+ to: base,
+ wantErr: "`to` must be after `from`",
+ },
+ {
+ name: "to before from",
+ from: base.Add(time.Hour),
+ to: base,
+ wantErr: "`to` must be after `from`",
+ },
+ {
+ name: "window > 30d",
+ from: base,
+ to: base.Add(30*24*time.Hour + time.Second),
+ wantErr: "query window must be <= 30 days",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateSandboxUsageWindow(tt.from, tt.to)
+ if tt.wantErr == "" {
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ return
+ }
+ if err == nil {
+ t.Fatalf("expected error %q, got nil", tt.wantErr)
+ }
+ if !strings.Contains(err.Error(), tt.wantErr) {
+ t.Errorf("expected error containing %q, got %q", tt.wantErr, err.Error())
+ }
+ })
+ }
+}
diff --git a/internal/db/usage_query.go b/internal/db/usage_query.go
index 56696912..f7271589 100644
--- a/internal/db/usage_query.go
+++ b/internal/db/usage_query.go
@@ -454,56 +454,3 @@ func (s *Store) ExecuteOrgTotals(ctx context.Context, q UsageQuery) (UsageTotals
return t, nil
}
-// SandboxUsageWindow returns the single-sandbox drilldown values for
-// GET /sandboxes/{id}/usage: GB-second numbers plus first/last session
-// timestamps clamped to the query window. Tag hydration is left to
-// the handler (which calls GetSandboxTags).
-//
-// Timestamps are explicitly clamped into [from, to] (design F9):
-// without the clamp, long-lived sandboxes leak endpoints outside the
-// requested window. The SQL uses GREATEST(MIN(started_at), from) and
-// LEAST(MAX(...), to).
-func (s *Store) SandboxUsageWindow(ctx context.Context, orgID uuid.UUID, sandboxID string, from, to time.Time) (mem, disk float64, firstStartedAt *time.Time, lastEndedAt *time.Time, err error) {
- // Usage numbers from scale events, identical math to GetOrgUsage.
- err = s.pool.QueryRow(ctx, `
-SELECT
- COALESCE(SUM(e.memory_mb::float / 1024.0 * EXTRACT(EPOCH FROM (COALESCE(e.ended_at, LEAST(now(), $3)) - GREATEST(e.started_at, $2)))), 0),
- COALESCE(SUM(GREATEST(e.disk_mb - 20480, 0)::float / 1024.0 * EXTRACT(EPOCH FROM (COALESCE(e.ended_at, LEAST(now(), $3)) - GREATEST(e.started_at, $2)))), 0)
-FROM sandbox_scale_events e
-WHERE e.org_id = $1 AND e.sandbox_id = $4
- AND e.started_at < $3 AND (e.ended_at IS NULL OR e.ended_at > $2)`,
- orgID, from, to, sandboxID).Scan(&mem, &disk)
- if err != nil {
- return 0, 0, nil, nil, fmt.Errorf("sandbox usage query: %w", err)
- }
-
- // Lifetime bounds from sandbox_sessions, clamped into [from, to].
- // Session-level MIN/MAX is more intuitive than scale-event edges
- // for "when did this sandbox exist" and is stable across scale
- // churn — see design D1.
- //
- // "No session in the window" is expressed as NULL aggregates, not
- // as a scan error — *time.Time handles NULL via nil, and BOOL_OR
- // is COALESCE'd to false so scan never fails on empty input
- // (design F13). A scan error here therefore means a real DB /
- // context failure and is returned up the stack.
- var minStart, maxEnd *time.Time
- var anyOpen bool
- if err := s.pool.QueryRow(ctx, `
-SELECT
- GREATEST(MIN(started_at), $3),
- COALESCE(BOOL_OR(stopped_at IS NULL AND status IN ('running', 'hibernated')), false),
- LEAST(MAX(COALESCE(stopped_at, now())), $4)
-FROM sandbox_sessions
-WHERE org_id = $1 AND sandbox_id = $2
- AND started_at < $4
- AND (stopped_at IS NULL OR stopped_at > $3)`,
- orgID, sandboxID, from, to).Scan(&minStart, &anyOpen, &maxEnd); err != nil {
- return 0, 0, nil, nil, fmt.Errorf("sandbox session bounds query: %w", err)
- }
- firstStartedAt = minStart
- if !anyOpen {
- lastEndedAt = maxEnd
- }
- return mem, disk, firstStartedAt, lastEndedAt, nil
-}