Skip to content

An open-source, faster Devin alternative

TypeScript

Address review: boundary clamping, units, uptime semantics, reconciliation scope

Igor Zalutskia4554eecf55f
diff --git a/.agents/design/per-sandbox-usage-api.md b/.agents/design/per-sandbox-usage-api.md
index 9c7f3c8f..e4e28377 100644
--- a/.agents/design/per-sandbox-usage-api.md
+++ b/.agents/design/per-sandbox-usage-api.md
@@ -110,8 +110,15 @@ because resize is rare relative to the 1m bucket.
## Window
-Required: `from`, `to`. Both RFC3339. Default: last 1 hour. Max:
-**30 days**. `to` must be strictly greater than `from`.
+Optional: `from`, `to`. Both RFC3339. When omitted, server defaults
+to `from = now - 1h`, `to = now`. Max: **30 days**. `to` must be
+strictly greater than `from`.
+
+Boundary buckets are clamped to the original window — when `from`
+falls mid-minute, the first bucket's allocation and uptime reflect
+only the portion that actually overlaps `[from, to)`, not the full
+minute it nominally covers. Without this clamp, a default
+`now-1h..now` call would over-report by up to two full minutes.
At 1m granularity, 30 days = 43,200 points ≈ 5 MB uncompressed JSON,
~300–500 KB gzipped. Trivial for browsers and SDK consumers. The
@@ -175,11 +182,16 @@ tag/lifetime hydration:
utilization. It stays on `/api/usage` where billing consumers
already read it. Disk is provisioned, not measured continuously —
there is no `memory_bytes` analogue to surface.
-- **`tags`, `tagsLastUpdatedAt`, `status`, `alias`**: these are
- identity, not usage. They belong on the sandbox detail endpoint
+- **`tags`, `tagsLastUpdatedAt`, `status`**: these are identity, not
+ usage. They belong on the sandbox detail endpoint
(`GET /api/sandboxes/:id`), which already returns them. Bundling
them here forces every usage call to re-hydrate metadata that
doesn't change in a usage-relevant way.
+- **`alias`**: dropped from the strict-narrowing rationale above but
+ kept inline as an exception — it's a 2-line lookup from the
+ sandbox_sessions config JSONB, and CLI/dashboard contexts
+ ("which sandbox am I looking at?") read much better with it
+ present than with a follow-up call to `GET /api/sandboxes/:id`.
- **`firstStartedAt`, `lastEndedAt`**: derivable from the points
array (first/last point with `uptimeSeconds > 0`). The aggregate
fields go away; the data they represented is still recoverable.
@@ -299,13 +311,33 @@ mark, with the noisy `usedMemoryMbAvg` curve underneath.
same materialized points, so this is testing the contract, not the
math).
-**Reconciliation against the existing billing query:**
-
-`totals.memoryAllocatedGbSeconds` should equal the existing
-`/api/usage`'s `memoryGbSeconds` for the same `[from, to]` and
-sandbox, since both derive from `sandbox_scale_events` with the
-same integration math. A reconciliation test catches accidental
-drift from the billing pipeline.
+**Reconciliation against the existing billing query — and one
+intentional divergence:**
+
+`totals.memoryAllocatedGbSeconds` equals the existing `/api/usage`'s
+`memoryGbSeconds` for the same `[from, to]` and sandbox **when all
+in-window scale events terminate at or before `to`**. Both derive from
+`sandbox_scale_events` with the same integration math (and the same
+`COALESCE(ended_at, LEAST(now(), to))` clamp for open events), so the
+common case is bug-for-bug identical and the Stripe pipeline keeps
+its reconciliation invariant.
+
+The two endpoints **disagree by design when an event's `ended_at > to`**.
+The existing aggregator does not clamp `ended_at` to `to` (an inherited
+quirk in `GetOrgUsage` documented at `internal/db/usage_query.go`);
+overflow time accrues into the "in-window" total. The new endpoint
+clamps via the bucket-edge `LEAST(..., $4)` chain, so it reports the
+mathematically correct in-window allocation while the aggregator
+overshoots.
+
+This divergence is pinned by `TestSandboxUsagePoints_OvershootDivergence_pgfixture`
+so it can't drift silently. The two endpoints will converge again when
+the aggregator's clamp is fixed (out of scope here).
+
+**Units note:** every `GbSeconds` field is **GiB-seconds** (binary,
+1 GiB = 2³⁰ bytes). The wire-format keeps the historical `Gb` name to
+stay compatible with the existing aggregator field; do not interpret
+it as decimal GB.
**End-to-end on the GCP dev box:**
diff --git a/docs/api-reference/usage/get-sandbox-usage.mdx b/docs/api-reference/usage/get-sandbox-usage.mdx
index 349b06c8..4ce95679 100644
--- a/docs/api-reference/usage/get-sandbox-usage.mdx
+++ b/docs/api-reference/usage/get-sandbox-usage.mdx
@@ -34,36 +34,45 @@ cgroup `cpu.stat` — additive change, no shape break.
"from": "2026-05-27T00:00:00Z",
"to": "2026-05-28T00:00:00Z",
"totals": {
- "memoryAllocatedGbSeconds": 8000,
- "memoryUsedGbSeconds": 5400,
- "uptimeSeconds": 86400,
- "memoryAllocatedPeakMb": 2048,
- "memoryUsedPeakMb": 1640
+ "memoryAllocatedGbSeconds": 86400,
+ "memoryUsedGbSeconds": 51640,
+ "uptimeSeconds": 86400,
+ "memoryAllocatedPeakMb": 1024,
+ "memoryUsedPeakMb": 742
},
"points": [
{
- "ts": "2026-05-27T00:00:00Z",
- "memoryAllocatedGbSeconds": 1.024,
- "memoryUsedGbSeconds": 0.612,
- "uptimeSeconds": 60,
- "allocatedMemoryMb": 1024,
- "usedMemoryMbAvg": 612,
- "usedMemoryMbPeak": 720
+ "ts": "2026-05-27T00:00:00Z",
+ "memoryAllocatedGbSeconds": 60.0,
+ "memoryUsedGbSeconds": 35.86,
+ "uptimeSeconds": 60,
+ "allocatedMemoryMb": 1024,
+ "usedMemoryMbAvg": 612,
+ "usedMemoryMbPeak": 720
},
{
- "ts": "2026-05-27T00:01:00Z",
- "memoryAllocatedGbSeconds": 1.024,
- "memoryUsedGbSeconds": 0.683,
- "uptimeSeconds": 60,
- "allocatedMemoryMb": 1024,
- "usedMemoryMbAvg": 683,
- "usedMemoryMbPeak": 742
+ "ts": "2026-05-27T00:01:00Z",
+ "memoryAllocatedGbSeconds": 60.0,
+ "memoryUsedGbSeconds": 40.02,
+ "uptimeSeconds": 60,
+ "allocatedMemoryMb": 1024,
+ "usedMemoryMbAvg": 683,
+ "usedMemoryMbPeak": 742
}
]
}
```
</ResponseExample>
+### Units
+
+All `*GbSeconds` fields are **GiB-seconds** (binary, 2<sup>30</sup>
+bytes/GiB). For a sandbox provisioned at 1024 MiB running for one
+minute, `memoryAllocatedGbSeconds` is `1024/1024 × 60 = 60`. For an
+RSS sample of 612 MiB, `memoryUsedGbSeconds` is `612/1024 × 60 ≈
+35.86`. The wire name uses `Gb` for backwards compatibility with the
+billing aggregator; do not interpret it as decimal GB.
+
### Reading the response
`totals.memoryAllocatedGbSeconds` is what the bill is computed from —
diff --git a/internal/api/sandbox_tags.go b/internal/api/sandbox_tags.go
index 670eadcb..2d57d728 100644
--- a/internal/api/sandbox_tags.go
+++ b/internal/api/sandbox_tags.go
@@ -12,10 +12,11 @@ import (
"github.com/opensandbox/opensandbox/internal/auth"
)
-// Sandbox tag endpoints. All ownership checks read sandbox_sessions —
-// the sandbox_tags PK is (sandbox_id, key) without org_id, so the
-// handler is the enforcement point that prevents cross-tenant tag
-// writes. Never bypass that lookup.
+// Sandbox tag endpoints. Tag rows are keyed on (org_id, sandbox_id, key)
+// — see migration 026 — so storage is org-scoped on its own. Handlers
+// still run ownsSandbox before reads/writes so a caller can't probe
+// the existence of another org's sandbox via this surface, but the
+// table itself is the tenancy boundary.
const (
maxTagsPerSandbox = 50
diff --git a/internal/db/usage_points.go b/internal/db/usage_points.go
index ba479904..dc4fb5d8 100644
--- a/internal/db/usage_points.go
+++ b/internal/db/usage_points.go
@@ -55,21 +55,36 @@ type SandboxUsageTotals struct {
// SandboxUsagePoints so pure-Go tests can assert shape without a
// Postgres connection. Inputs are validated; callers pass already-
// validated [from, to).
+//
+// Units note: every GbSeconds field is GiB-seconds (binary, 2^30
+// bytes/GiB). `memory_mb` is treated as MiB (`/1024.0 → GiB`) to
+// match the billing pipeline; `memory_bytes` is divided by 1073741824
+// for the same unit. Mixing decimal GB with binary GiB would silently
+// bias the allocated-vs-used ratio.
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.
+ // Bucket grid: minute-aligned in UTC. First bucket starts at
+ // date_trunc('minute', from) — may be earlier than `from` itself
+ // when `from` is mid-minute. Last bucket is the one whose start is
+ // strictly less than `to`. Per-event overlap is clamped to [$3, $4]
+ // as well as to bucket edges, so boundary buckets report only the
+ // fraction that overlaps the original window — the contract is
+ // [from, to), not "the union of minutes touching [from, to)".
+ //
+ // Allocation source is sandbox_scale_events (same table the billing
+ // aggregator reads). Open events (ended_at IS NULL) are clamped to
+ // LEAST(now(), $4) to match GetOrgUsage's COALESCE idiom — so the
+ // two endpoints agree exactly when ended_at IS NULL. They diverge
+ // when ended_at > to: the aggregator overshoots (inherited quirk;
+ // see internal/db/usage_query.go:durationExpr), the new endpoint
+ // clamps to $4. This divergence is intentional and tested.
//
- // 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.
+ // Uptime per bucket = SUM(overlap_seconds) across joined events.
+ // This makes uptime track "was a scale event open" rather than
+ // "did we receive a sample," so collector outages don't masquerade
+ // as downtime in the response.
//
// Used memory: AVG/MAX over samples that fall in the bucket. At
// the 60s collector cadence there is usually one sample per
@@ -97,39 +112,45 @@ samples AS (
AND sampled_at < $4
GROUP BY date_trunc('minute', sampled_at)
),
-allocated AS (
+event_overlap AS (
+ -- Named event_overlap because OVERLAPS is a Postgres reserved word
+ -- (temporal predicate). INNER JOIN (not LEFT) so buckets with no
+ -- matching scale event produce no rows -- the outer LEFT JOIN to
+ -- the allocated CTE then COALESCEs missing buckets to zero. A LEFT
+ -- JOIN here would let phantom NULL-event rows sneak through the
+ -- GREATEST(NULL, b.ts, $3) idiom and emit a full-bucket
+ -- overlap_seconds for buckets that should have no allocation.
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
+ e.memory_mb,
+ GREATEST(EXTRACT(EPOCH FROM (
+ LEAST(COALESCE(e.ended_at, LEAST(now(), $4::timestamptz)), b.ts_end, $4::timestamptz)
+ - GREATEST(e.started_at, b.ts, $3::timestamptz)
+ )), 0) AS overlap_seconds
FROM buckets b
- LEFT JOIN sandbox_scale_events e
+ INNER 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
+),
+allocated AS (
+ SELECT
+ bucket_ts,
+ SUM(memory_mb::float * overlap_seconds) / 60.0 AS weighted_memory_mb,
+ SUM(memory_mb::float / 1024.0 * overlap_seconds) AS gb_seconds,
+ COALESCE(SUM(overlap_seconds)::int, 0) AS uptime_seconds
+ FROM event_overlap
+ GROUP BY bucket_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
+ 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 / 1073741824.0 * 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,
+ COALESCE(a.uptime_seconds, 0) 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
diff --git a/internal/db/usage_points_pgfixture_test.go b/internal/db/usage_points_pgfixture_test.go
index 2c2d3094..02588865 100644
--- a/internal/db/usage_points_pgfixture_test.go
+++ b/internal/db/usage_points_pgfixture_test.go
@@ -13,12 +13,24 @@ package db
import (
"context"
+ "fmt"
+ "math"
"testing"
"time"
"github.com/google/uuid"
)
+// freshSandboxID picks a sandbox_id that won't collide with prior test
+// runs in the same database. The sandbox_usage_samples PK is
+// (sandbox_id, sampled_at) — not (org_id, sandbox_id, sampled_at) —
+// so even with a fresh orgID, reusing a hardcoded sandbox_id across
+// runs can cause ON CONFLICT DO NOTHING to silently drop the new
+// fixture data. See the P1 schema gap in the reviewer notes.
+func freshSandboxID(prefix string) string {
+ return fmt.Sprintf("%s-%s", prefix, uuid.New().String()[:8])
+}
+
// 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.
@@ -83,7 +95,7 @@ func TestSandboxUsagePoints_Shape_pgfixture(t *testing.T) {
store := openPgStore(t)
orgID := uuid.New()
- sandboxID := "sbx-usage-shape"
+ sandboxID := freshSandboxID("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)
@@ -109,7 +121,9 @@ func TestSandboxUsagePoints_Shape_pgfixture(t *testing.T) {
if p0.UptimeSeconds != 60 {
t.Errorf("points[0].UptimeSeconds = %d, want 60", p0.UptimeSeconds)
}
- assertClose(t, "points[0].MemoryUsedGbSeconds", 84, p0.MemoryUsedGbSeconds)
+ // 1.4 GB sample → 1.4e9 / 1073741824 GiB × 60s.
+ expUsed := 1_400_000_000.0 / (1024 * 1024 * 1024) * 60
+ assertClose(t, "points[0].MemoryUsedGbSeconds (GiB units)", expUsed, p0.MemoryUsedGbSeconds)
// Bucket 360 — resize at t0+6h+30s splits the bucket 50/50 between
// 2 GiB and 4 GiB tiers. Weighted allocated MB:
@@ -121,16 +135,21 @@ func TestSandboxUsagePoints_Shape_pgfixture(t *testing.T) {
t.Errorf("points[360].AllocatedMemoryMb = %d, want 3072 (resize bucket)", p360.AllocatedMemoryMb)
}
assertClose(t, "points[360].MemoryAllocatedGbSeconds (resize bucket)", 180, p360.MemoryAllocatedGbSeconds)
+ if p360.UptimeSeconds != 60 {
+ t.Errorf("points[360].UptimeSeconds = %d, want 60 (resize bucket fully covered by events)", p360.UptimeSeconds)
+ }
// Bucket 480 — inside the sample gap (t0+8h..t0+9h). Scale event 2
- // is still open here so allocation accrues, but uptime reads 0.
+ // is still open here, so allocation AND uptime accrue (uptime now
+ // derives from scale-event overlap, not sample presence — collector
+ // gaps don't masquerade as downtime).
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.UptimeSeconds != 60 {
+ t.Errorf("points[480].UptimeSeconds = %d, want 60 (scale event open)", p480.UptimeSeconds)
}
if p480.UsedMemoryMbAvg != 0 {
t.Errorf("points[480].UsedMemoryMbAvg = %d, want 0 (no sample in gap)", p480.UsedMemoryMbAvg)
@@ -146,16 +165,16 @@ func TestSandboxUsagePoints_Shape_pgfixture(t *testing.T) {
// 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
+ // event 2 in [t0+6h30s, t0+18h) → 43170s × 4 GiB = 172680
+ // Sum = 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)
+ // Uptime now derives from scale-event overlap: 18h × 60min/h × 60s/min
+ // = 64800. The 60 minutes of sample gap no longer subtract from uptime.
+ if totals.UptimeSeconds != 18*3600 {
+ t.Errorf("totals.UptimeSeconds = %d, want %d (18h × 3600s)", totals.UptimeSeconds, 18*3600)
}
}
@@ -169,7 +188,7 @@ func TestSandboxUsagePoints_SumInvariant_pgfixture(t *testing.T) {
store := openPgStore(t)
orgID := uuid.New()
- sandboxID := "sbx-usage-sum-invariant"
+ sandboxID := freshSandboxID("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)
@@ -203,7 +222,7 @@ func TestSandboxUsagePoints_Reconciliation_pgfixture(t *testing.T) {
store := openPgStore(t)
orgID := uuid.New()
- sandboxID := "sbx-usage-reconcile"
+ sandboxID := freshSandboxID("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)
@@ -229,3 +248,123 @@ func TestSandboxUsagePoints_Reconciliation_pgfixture(t *testing.T) {
}
assertClose(t, "totals.MemoryAllocatedGbSeconds vs GetOrgUsage", rollupAlloc, totals.MemoryAllocatedGbSeconds)
}
+
+// TestSandboxUsagePoints_Boundary_pgfixture pins the [from, to) contract
+// when callers pass mid-minute timestamps. Boundary buckets must report
+// only the fraction of the bucket that overlaps the original window —
+// not the full minute they nominally cover. Without per-event clamping
+// to $3/$4, a default `now-1h .. now` query (almost never aligned)
+// over-reports allocation by up to two full minutes per call.
+func TestSandboxUsagePoints_Boundary_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ orgID := uuid.New()
+ sandboxID := freshSandboxID("sbx-usage-boundary")
+
+ // Anchor everything to a known minute so the fractional math is
+ // reproducible regardless of when the test runs.
+ anchor := time.Now().UTC().Truncate(time.Hour)
+ from := anchor.Add(30 * time.Second) // mid-minute lower bound
+ to := anchor.Add(1*time.Minute + 45*time.Second) // mid-minute upper bound; 75s window total
+
+ // Scale event covers the entire window and beyond.
+ 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, 1024, 25, 20480, anchor.Add(-1*time.Hour), anchor.Add(1*time.Hour)); err != nil {
+ t.Fatalf("seed scale event: %v", err)
+ }
+
+ points, totals, err := store.SandboxUsagePoints(ctx, orgID, sandboxID, from, to)
+ if err != nil {
+ t.Fatalf("SandboxUsagePoints: %v", err)
+ }
+ if len(points) != 2 {
+ t.Fatalf("expected 2 buckets (date_trunc(from) .. date_trunc(to-1us)), got %d", len(points))
+ }
+
+ // Bucket 0 = [anchor, anchor+1m). Effective overlap with [from, to)
+ // = [from, anchor+1m) = 30 seconds. Allocated GiB-seconds = 1 × 30.
+ assertClose(t, "boundary bucket 0 allocated", 30, points[0].MemoryAllocatedGbSeconds)
+ if points[0].UptimeSeconds != 30 {
+ t.Errorf("boundary bucket 0 uptime = %d, want 30 (clamped to from)", points[0].UptimeSeconds)
+ }
+
+ // Bucket 1 = [anchor+1m, anchor+2m). Effective overlap = [anchor+1m, to)
+ // = 45 seconds. Allocated GiB-seconds = 1 × 45.
+ assertClose(t, "boundary bucket 1 allocated", 45, points[1].MemoryAllocatedGbSeconds)
+ if points[1].UptimeSeconds != 45 {
+ t.Errorf("boundary bucket 1 uptime = %d, want 45 (clamped to to)", points[1].UptimeSeconds)
+ }
+
+ // Totals = 30 + 45 = 75 GiB-seconds for the 75-second window.
+ // Without clamping, this would be 120 (2 × 60s).
+ assertClose(t, "boundary totals", 75, totals.MemoryAllocatedGbSeconds)
+ if totals.UptimeSeconds != 75 {
+ t.Errorf("boundary totals.UptimeSeconds = %d, want 75", totals.UptimeSeconds)
+ }
+}
+
+// TestSandboxUsagePoints_OvershootDivergence_pgfixture pins the
+// intentional divergence between this endpoint and /api/usage when a
+// scale event extends past `to`. The aggregator's GetOrgUsage uses
+// COALESCE(ended_at, LEAST(now(), to)) — which DOES NOT clamp when
+// ended_at is set, so it over-reports. The new per-sandbox endpoint
+// clamps to $4 via the LEAST(..., b.ts_end, $4) chain, so it reports
+// the mathematically correct value.
+//
+// This test exists so the divergence is a known, tested property, not
+// a silent disagreement between two public usage APIs. If billing is
+// later fixed, both endpoints will agree again and this test will
+// require updating to match.
+func TestSandboxUsagePoints_OvershootDivergence_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ orgID := uuid.New()
+ sandboxID := freshSandboxID("sbx-usage-overshoot")
+
+ // Anchor to an even hour so seconds-precision arithmetic is exact.
+ anchor := time.Now().UTC().Truncate(time.Hour).Add(-24 * time.Hour)
+ from := anchor
+ to := anchor.Add(24 * time.Hour)
+
+ // Event started 1h after `from`, ends 6h after `to`. In-window
+ // allocation should be 23h × 1 GiB = 82800 GiB-seconds.
+ 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, 1024, 25, 20480,
+ anchor.Add(1*time.Hour), anchor.Add(30*time.Hour)); err != nil {
+ t.Fatalf("seed scale event: %v", err)
+ }
+
+ _, totals, err := store.SandboxUsagePoints(ctx, orgID, sandboxID, from, to)
+ if err != nil {
+ t.Fatalf("SandboxUsagePoints: %v", err)
+ }
+ const expectedCorrect = 23.0 * 3600.0 // 23h × 1 GiB
+ assertClose(t, "new endpoint clamps to `to`", expectedCorrect, totals.MemoryAllocatedGbSeconds)
+
+ // GetOrgUsage reports 29h (started_at = anchor+1h, ended_at = anchor+30h,
+ // no upper clamp). For memory_mb=1024 → 29 × 3600 = 104400 GiB-seconds.
+ summaries, err := store.GetOrgUsage(ctx, orgID.String(), from, to)
+ if err != nil {
+ t.Fatalf("GetOrgUsage: %v", err)
+ }
+ var rollup float64
+ for _, s := range summaries {
+ rollup += float64(s.MemoryMB) / 1024.0 * s.TotalSeconds
+ }
+ const expectedOvershoot = 29.0 * 3600.0
+ assertClose(t, "aggregator overshoots `to`", expectedOvershoot, rollup)
+
+ // The divergence is exactly 6 hours of allocation.
+ const expectedDivergence = 6.0 * 3600.0
+ if diff := rollup - totals.MemoryAllocatedGbSeconds; math.Abs(diff-expectedDivergence) > 1e-6 {
+ t.Errorf("divergence = %.3f, want %.3f (6h × 1 GiB)", diff, expectedDivergence)
+ }
+}
diff --git a/internal/db/usage_points_test.go b/internal/db/usage_points_test.go
index b3762220..b6571e91 100644
--- a/internal/db/usage_points_test.go
+++ b/internal/db/usage_points_test.go
@@ -19,21 +19,23 @@ func TestBuildSandboxUsagePointsQuery_Shape(t *testing.T) {
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",
+ "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)",
+ "open-event clamp matches aggregator": "COALESCE(e.ended_at, LEAST(now(), $4::timestamptz))",
+ "upper-bound window clamp": "b.ts_end, $4::timestamptz",
+ "lower-bound window clamp": "GREATEST(e.started_at, b.ts, $3::timestamptz)",
+ "negative-overlap guard": "GREATEST(EXTRACT(EPOCH FROM (",
+ "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 GiB-seconds from memory_bytes": "memory_bytes_avg::float / 1073741824.0",
+ "uptime derived from overlap": "a.uptime_seconds",
+ "ordered by bucket timestamp": "ORDER BY b.ts",
}
for label, frag := range checks {
if !strings.Contains(sql, frag) {