An open-source, faster Devin alternative
TypeScript
feat(capacity-allocator): per-second integration walk + outbox emission (shadow mode)
Igor Zalutskif056bd83705f
diff --git a/cmd/capacity-shadow-verify/main.go b/cmd/capacity-shadow-verify/main.gonew file mode 100644index 00000000..3a239b57--- /dev/null+++ b/cmd/capacity-shadow-verify/main.go@@ -0,0 +1,271 @@+// capacity-shadow-verify compares the phase-2 outbox against the legacy+// UsageReporter pipeline for orgs that have zero capacity reservations+// in the window. With reservedGb=0 the integration walk's per-tier+// overage equals legacy `tier_GB × total_seconds` — any divergence+// surfaces an allocator bug before phase 3 starts shipping outbox rows+// to Stripe.+//+// Usage:+//+// DATABASE_URL=postgres://... \+// go run ./cmd/capacity-shadow-verify \+// --from=2026-04-26T00:00:00Z \+// --to=2026-04-27T00:00:00Z \+// [--org-id=<uuid>] [--epsilon=0.01]+//+// Both bounds must be UTC and 15-minute aligned. Org filter is optional+// — when omitted, every org with at least one outbox row in the window+// is checked.+package main++import (+ "context"+ "flag"+ "fmt"+ "log"+ "math"+ "os"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgxpool"+)++func main() {+ fromS := flag.String("from", "", "window start (RFC3339, UTC, 15-min aligned)")+ toS := flag.String("to", "", "window end (RFC3339, UTC, 15-min aligned)")+ orgFilter := flag.String("org-id", "", "limit comparison to one org id (optional)")+ epsilon := flag.Float64("epsilon", 0.01, "fractional delta tolerated before flagging a mismatch")+ flag.Parse()++ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ log.Fatal("DATABASE_URL is required")+ }+ if *fromS == "" || *toS == "" {+ log.Fatal("--from and --to are required")+ }+ from, err := time.Parse(time.RFC3339, *fromS)+ if err != nil {+ log.Fatalf("parse --from: %v", err)+ }+ to, err := time.Parse(time.RFC3339, *toS)+ if err != nil {+ log.Fatalf("parse --to: %v", err)+ }+ if from.Truncate(15*time.Minute) != from.UTC() || to.Truncate(15*time.Minute) != to.UTC() {+ log.Fatal("--from and --to must be UTC and 15-minute aligned")+ }+ if !to.After(from) {+ log.Fatal("--to must be after --from")+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()++ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ log.Fatalf("connect db: %v", err)+ }+ defer pool.Close()++ orgs, err := orgsToCheck(ctx, pool, from, to, *orgFilter)+ if err != nil {+ log.Fatalf("list orgs: %v", err)+ }+ if len(orgs) == 0 {+ log.Println("no orgs with outbox rows in window — nothing to verify")+ return+ }+ log.Printf("comparing %d org(s) over [%s, %s)", len(orgs), from.Format(time.RFC3339), to.Format(time.RFC3339))++ var mismatches int+ for _, orgID := range orgs {+ ok, err := checkOrg(ctx, pool, orgID, from, to, *epsilon)+ if err != nil {+ log.Printf("org %s: error: %v", orgID, err)+ mismatches+++ continue+ }+ if !ok {+ mismatches+++ }+ }+ if mismatches > 0 {+ log.Printf("RESULT: %d/%d org(s) had mismatches", mismatches, len(orgs))+ os.Exit(1)+ }+ log.Printf("RESULT: all %d org(s) match within epsilon=%.4f", len(orgs), *epsilon)+}++// orgsToCheck returns the set of orgs that have either outbox or legacy+// usage activity in the window, AND zero reservations in the window+// (so the comparison is apples-to-apples — outbox overage should equal+// legacy tier-GB-seconds).+func orgsToCheck(ctx context.Context, pool *pgxpool.Pool, from, to time.Time, orgFilter string) ([]uuid.UUID, error) {+ args := []any{from, to}+ filter := ""+ if orgFilter != "" {+ filter = `AND org_id = $3::uuid`+ args = append(args, orgFilter)+ }+ rows, err := pool.Query(ctx, `+ WITH activity AS (+ SELECT DISTINCT org_id FROM billable_events+ WHERE bucket_start >= $1 AND bucket_start < $2+ UNION+ SELECT DISTINCT org_id FROM sandbox_scale_events+ WHERE started_at < $2 AND (ended_at IS NULL OR ended_at > $1)+ ),+ reserved AS (+ SELECT DISTINCT org_id FROM capacity_reservation_intervals+ WHERE starts_at >= $1 AND starts_at < $2+ )+ SELECT a.org_id+ FROM activity a+ WHERE a.org_id NOT IN (SELECT org_id FROM reserved)+ `+filter+`+ ORDER BY a.org_id+ `, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ var out []uuid.UUID+ for rows.Next() {+ var id uuid.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ out = append(out, id)+ }+ return out, rows.Err()+}++func checkOrg(ctx context.Context, pool *pgxpool.Pool, orgID uuid.UUID, from, to time.Time, epsilon float64) (bool, error) {+ outbox, err := outboxTotals(ctx, pool, orgID, from, to)+ if err != nil {+ return false, fmt.Errorf("outbox: %w", err)+ }+ legacy, err := legacyTotals(ctx, pool, orgID, from, to)+ if err != nil {+ return false, fmt.Errorf("legacy: %w", err)+ }++ // Compare per tier and disk overage. With zero reservations, every+ // outbox overage row should match legacy tier-GB-seconds.+ allTiers := map[int]struct{}{}+ for tier := range outbox.tierGBSec {+ allTiers[tier] = struct{}{}+ }+ for tier := range legacy.tierGBSec {+ allTiers[tier] = struct{}{}+ }++ ok := true+ for tier := range allTiers {+ o := outbox.tierGBSec[tier]+ l := legacy.tierGBSec[tier]+ if !approxEq(o, l, epsilon) {+ fmt.Printf("MISMATCH org=%s tier=%dMB outbox=%.2f legacy=%.2f delta=%.2f (%.2f%%)\n",+ orgID, tier, o, l, o-l, percentDelta(o, l))+ ok = false+ }+ }+ if !approxEq(outbox.diskGBSec, legacy.diskGBSec, epsilon) {+ fmt.Printf("MISMATCH org=%s disk_overage outbox=%.2f legacy=%.2f delta=%.2f (%.2f%%)\n",+ orgID, outbox.diskGBSec, legacy.diskGBSec, outbox.diskGBSec-legacy.diskGBSec,+ percentDelta(outbox.diskGBSec, legacy.diskGBSec))+ ok = false+ }+ if ok {+ log.Printf("OK org=%s (%d tier(s), disk=%.2f)", orgID, len(allTiers), outbox.diskGBSec)+ }+ return ok, nil+}++type totals struct {+ tierGBSec map[int]float64 // memory_mb → GB-seconds (overage only)+ diskGBSec float64+}++func outboxTotals(ctx context.Context, pool *pgxpool.Pool, orgID uuid.UUID, from, to time.Time) (totals, error) {+ out := totals{tierGBSec: map[int]float64{}}+ rows, err := pool.Query(ctx, `+ SELECT event_type, memory_mb, COALESCE(SUM(gb_seconds), 0)::float8+ FROM billable_events+ WHERE org_id = $1 AND bucket_start >= $2 AND bucket_start < $3+ GROUP BY event_type, memory_mb+ `, orgID, from, to)+ if err != nil {+ return out, err+ }+ defer rows.Close()+ for rows.Next() {+ var typ string+ var mem int+ var gbs float64+ if err := rows.Scan(&typ, &mem, &gbs); err != nil {+ return out, err+ }+ switch typ {+ case "overage_usage":+ out.tierGBSec[mem] += gbs+ case "disk_overage_usage":+ out.diskGBSec += gbs+ }+ // reserved_usage rows are skipped: the comparison restricts to+ // orgs with zero reservations in the window.+ }+ return out, rows.Err()+}++// legacyTotals derives the same shape from sandbox_scale_events the way+// UsageReporter does: per-tier total seconds × tier_GB, disk overage as+// (disk_mb − 20480) × seconds / 1024. Window-clipped via GREATEST/LEAST+// to mirror GetOrgUsage.+func legacyTotals(ctx context.Context, pool *pgxpool.Pool, orgID uuid.UUID, from, to time.Time) (totals, error) {+ out := totals{tierGBSec: map[int]float64{}}+ rows, err := pool.Query(ctx, `+ SELECT memory_mb, disk_mb,+ SUM(EXTRACT(EPOCH FROM (LEAST(COALESCE(ended_at, $3), $3) - GREATEST(started_at, $2))))::float8 AS secs+ FROM sandbox_scale_events+ WHERE org_id = $1 AND started_at < $3 AND (ended_at IS NULL OR ended_at > $2)+ GROUP BY memory_mb, disk_mb+ `, orgID, from, to)+ if err != nil {+ return out, err+ }+ defer rows.Close()+ for rows.Next() {+ var mem, disk int+ var secs float64+ if err := rows.Scan(&mem, &disk, &secs); err != nil {+ return out, err+ }+ gbs := float64(mem/1024) * secs+ out.tierGBSec[mem] += gbs+ if disk > 20480 {+ out.diskGBSec += float64(disk-20480) / 1024.0 * secs+ }+ }+ return out, rows.Err()+}++func approxEq(a, b, epsilon float64) bool {+ if a == 0 && b == 0 {+ return true+ }+ denom := math.Max(math.Abs(a), math.Abs(b))+ return math.Abs(a-b)/denom <= epsilon+}++func percentDelta(a, b float64) float64 {+ if b == 0 {+ if a == 0 {+ return 0+ }+ return math.Inf(1)+ }+ return (a - b) / b * 100.0+}diff --git a/cmd/server/main.go b/cmd/server/main.goindex f2b97f97..dd1d77e8 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -6,6 +6,7 @@ import ("fmt""log""os"+ "strconv""strings""os/signal""syscall"@@ -395,6 +396,23 @@ func main() {log.Println("opensandbox: usage reporter started (interval=5m)")}+ // Phase-2 capacity allocator (shadow mode). Off by default; enable+ // per-env to write reserved/overage rows to the billable_events+ // outbox without delivering to Stripe. Phase 3 turns on the sender.+ if opts.Store != nil && os.Getenv("CAPACITY_ALLOCATOR_ENABLED") == "true" {+ allocOpts := billing.CapacityReconcilerOpts{+ Interval: getDurationEnv("CAPACITY_ALLOCATOR_INTERVAL", 5*time.Minute),+ Settle: getDurationEnv("CAPACITY_ALLOCATOR_SETTLE", 30*time.Minute),+ Lookback: getDurationEnv("CAPACITY_ALLOCATOR_LOOKBACK", 24*time.Hour),+ Limit: getIntEnv("CAPACITY_ALLOCATOR_BATCH_LIMIT", 500),+ }+ allocator := billing.NewCapacityReconciler(opts.Store, allocOpts)+ allocator.Start()+ defer allocator.Stop()+ log.Printf("opensandbox: capacity allocator started (interval=%s, settle=%s, lookback=%s)",+ allocOpts.Interval, allocOpts.Settle, allocOpts.Lookback)+ }+// Start NATS sync consumer if both PG and NATS are configuredif opts.Store != nil && cfg.NATSURL != "" {consumer, err := db.NewSyncConsumer(opts.Store, cfg.NATSURL)@@ -444,3 +462,26 @@ func main() {}log.Println("opensandbox: server stopped")}++// getDurationEnv reads a Go duration string (e.g. "5m", "30m", "24h")+// from env or returns the default. Used for the capacity allocator+// knobs which are off the hot path of config.Load().+func getDurationEnv(key string, def time.Duration) time.Duration {+ if v := os.Getenv(key); v != "" {+ if d, err := time.ParseDuration(v); err == nil {+ return d+ }+ log.Printf("opensandbox: invalid duration in %s=%q, using default %s", key, v, def)+ }+ return def+}++func getIntEnv(key string, def int) int {+ if v := os.Getenv(key); v != "" {+ if n, err := strconv.Atoi(v); err == nil {+ return n+ }+ log.Printf("opensandbox: invalid int in %s=%q, using default %d", key, v, def)+ }+ return def+}diff --git a/internal/billing/capacity_reconciler.go b/internal/billing/capacity_reconciler.gonew file mode 100644index 00000000..5b99dd5e--- /dev/null+++ b/internal/billing/capacity_reconciler.go@@ -0,0 +1,337 @@+package billing++import (+ "context"+ "log"+ "sort"+ "time"++ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/db"+)++// CapacityReconciler is the phase-2 outbox allocator. Every `interval`,+// it scans for closed 15-min buckets that are at least `settle` past+// their end and haven't been processed yet, runs the per-second+// integration walk for each (org, bucket), and emits the resulting+// reserved_usage / overage_usage / disk_overage_usage rows to the+// `billable_events` outbox.+//+// Phase 2 runs in shadow: the rows are written but not delivered to+// Stripe. UsageReporter continues to drive real billing. Shadow-verify+// (cmd/capacity-shadow-verify) compares the two for orgs with zero+// reservations to validate the new pipeline before phase 3 cuts over.+//+// The outbox unique constraint+// `(org_id, event_type, memory_mb, bucket_start)` makes the allocator+// idempotent at the DB level — a crashed or restarted reconciler can+// replay any bucket safely.+type CapacityReconciler struct {+ store *db.Store+ interval time.Duration+ settle time.Duration+ lookback time.Duration+ limit int+ stop chan struct{}+ stopped chan struct{}+}++// CapacityReconcilerOpts allows the server bootstrap to override the+// defaults via env (CAPACITY_ALLOCATOR_INTERVAL, _SETTLE_MINUTES,+// _LOOKBACK_HOURS, _BATCH_LIMIT). Zero values fall back to defaults.+type CapacityReconcilerOpts struct {+ Interval time.Duration // default 5m+ Settle time.Duration // default 30m+ Lookback time.Duration // default 24h+ Limit int // candidates per tick, default 500+}++func NewCapacityReconciler(store *db.Store, opts CapacityReconcilerOpts) *CapacityReconciler {+ if opts.Interval <= 0 {+ opts.Interval = 5 * time.Minute+ }+ if opts.Settle <= 0 {+ opts.Settle = 30 * time.Minute+ }+ if opts.Lookback <= 0 {+ opts.Lookback = 24 * time.Hour+ }+ if opts.Limit <= 0 {+ opts.Limit = 500+ }+ return &CapacityReconciler{+ store: store,+ interval: opts.Interval,+ settle: opts.Settle,+ lookback: opts.Lookback,+ limit: opts.Limit,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++func (r *CapacityReconciler) Start() { go r.loop() }+func (r *CapacityReconciler) Stop() { close(r.stop); <-r.stopped }++func (r *CapacityReconciler) loop() {+ defer close(r.stopped)+ ticker := time.NewTicker(r.interval)+ defer ticker.Stop()+ for {+ select {+ case <-ticker.C:+ r.tickSafe()+ case <-r.stop:+ return+ }+ }+}++func (r *CapacityReconciler) tickSafe() {+ defer func() {+ if v := recover(); v != nil {+ log.Printf("capacity-reconciler: recovered from panic: %v", v)+ }+ }()+ r.tick()+}++func (r *CapacityReconciler) tick() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()++ // Cutoff: only buckets whose end is at least `settle` ago are eligible.+ // Truncate to a 15-min boundary so we don't accidentally include a+ // half-finished bucket if `settle` happens to land mid-bucket.+ cutoff := time.Now().UTC().Add(-r.settle).Truncate(15 * time.Minute)+ lookbackStart := cutoff.Add(-r.lookback)++ candidates, err := r.store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, r.limit)+ if err != nil {+ log.Printf("capacity-reconciler: list candidates: %v", err)+ return+ }+ if len(candidates) == 0 {+ return+ }+ log.Printf("capacity-reconciler: processing %d candidate bucket(s)", len(candidates))++ processed := 0+ for _, c := range candidates {+ if err := r.processBucket(ctx, c.OrgID, c.BucketStart); err != nil {+ log.Printf("capacity-reconciler: org=%s bucket=%s: %v", c.OrgID, c.BucketStart.Format(time.RFC3339), err)+ continue+ }+ processed+++ }+ log.Printf("capacity-reconciler: emitted outbox rows for %d/%d bucket(s)", processed, len(candidates))+}++// processBucket runs the per-second integration walk for one (org,+// bucket) and emits the resulting outbox rows. The outbox UNIQUE+// constraint absorbs replays.+func (r *CapacityReconciler) processBucket(ctx context.Context, orgID uuid.UUID, bucketStart time.Time) error {+ bucketEnd := bucketStart.Add(15 * time.Minute)++ reservedGB, err := r.store.GetReservedGBForBucket(ctx, orgID, bucketStart)+ if err != nil {+ return err+ }++ events, err := r.store.GetScaleEventsForBucket(ctx, orgID, bucketStart, bucketEnd)+ if err != nil {+ return err+ }++ totals := IntegrateBucket(bucketStart, bucketEnd, reservedGB, events)+ return emitBucket(ctx, r.store, orgID, bucketStart, bucketEnd, reservedGB, totals)+}++// BucketTotals is the output of the per-bucket integration walk.+// Memory tier keys are `memory_mb` (1024 / 4096 / ...). DiskOverageGBSeconds+// is org-level, summed across all running events at each segment.+type BucketTotals struct {+ OverageGBSecondsByTier map[int]float64+ DiskOverageGBSeconds float64+ ReservedFloorGBSeconds float64 // reservedGb × secs accumulated across segments — for shadow validation only+}++// IntegrateBucket runs the full clip → segments → integrate pipeline+// for one (org, bucket). Pure-Go, deterministic, unit-testable.+func IntegrateBucket(bucketStart, bucketEnd time.Time, reservedGB int, events []db.ScaleEvent) BucketTotals {+ clipped := make([]clippedEvent, 0, len(events))+ for _, e := range events {+ c, ok := clipEvent(e, bucketStart, bucketEnd)+ if !ok {+ continue+ }+ clipped = append(clipped, c)+ }+ boundaries := collectBoundaries(clipped, bucketStart, bucketEnd)+ segs := walkSegments(boundaries, clipped)+ return integrateSegments(segs, reservedGB)+}++type clippedEvent struct {+ From, To time.Time+ TierMB int+ DiskMB int+}++// clipEvent restricts a ScaleEvent's lifetime to the bucket window.+// Returns ok=false if the event's clipped span is empty.+func clipEvent(e db.ScaleEvent, bucketStart, bucketEnd time.Time) (clippedEvent, bool) {+ from := e.StartedAt+ if from.Before(bucketStart) {+ from = bucketStart+ }+ to := bucketEnd+ if e.EndedAt != nil && e.EndedAt.Before(bucketEnd) {+ to = *e.EndedAt+ }+ if !to.After(from) {+ return clippedEvent{}, false+ }+ return clippedEvent{From: from, To: to, TierMB: e.MemoryMB, DiskMB: e.DiskMB}, true+}++func collectBoundaries(events []clippedEvent, bucketStart, bucketEnd time.Time) []time.Time {+ seen := map[int64]struct{}{+ bucketStart.UnixNano(): {},+ bucketEnd.UnixNano(): {},+ }+ out := []time.Time{bucketStart, bucketEnd}+ for _, e := range events {+ if _, ok := seen[e.From.UnixNano()]; !ok {+ seen[e.From.UnixNano()] = struct{}{}+ out = append(out, e.From)+ }+ if _, ok := seen[e.To.UnixNano()]; !ok {+ seen[e.To.UnixNano()] = struct{}{}+ out = append(out, e.To)+ }+ }+ sort.Slice(out, func(i, j int) bool { return out[i].Before(out[j]) })+ return out+}++type segment struct {+ From, To time.Time+ RunningByTier map[int]int // tier_mb → running GB at this tier+ DiskOverageMB int // sum of (disk_mb − 20480) over running events+}++func walkSegments(boundaries []time.Time, events []clippedEvent) []segment {+ segs := make([]segment, 0, len(boundaries)-1)+ for i := 0; i < len(boundaries)-1; i++ {+ from, to := boundaries[i], boundaries[i+1]+ if !to.After(from) {+ continue+ }+ tiers := map[int]int{}+ diskOver := 0+ for _, e := range events {+ // Event is "running" in [from, to) if it covers the segment+ // fully — i.e. e.From <= from AND e.To >= to. Since the+ // boundary set includes every event endpoint, every segment+ // is fully contained in any event whose span covers `from`.+ if !e.From.After(from) && !e.To.Before(to) {+ tiers[e.TierMB] += e.TierMB / 1024+ if e.DiskMB > 20480 {+ diskOver += e.DiskMB - 20480+ }+ }+ }+ segs = append(segs, segment{From: from, To: to, RunningByTier: tiers, DiskOverageMB: diskOver})+ }+ return segs+}++func integrateSegments(segs []segment, reservedGB int) BucketTotals {+ out := BucketTotals{OverageGBSecondsByTier: map[int]float64{}}+ for _, s := range segs {+ secs := s.To.Sub(s.From).Seconds()+ usage := 0+ for _, gb := range s.RunningByTier {+ usage += gb+ }++ if usage > reservedGB {+ spike := float64(usage - reservedGB)+ for tier, gb := range s.RunningByTier {+ share := float64(gb) / float64(usage)+ out.OverageGBSecondsByTier[tier] += spike * share * secs+ }+ out.ReservedFloorGBSeconds += float64(reservedGB) * secs+ } else {+ out.ReservedFloorGBSeconds += float64(usage) * secs+ }++ if s.DiskOverageMB > 0 {+ out.DiskOverageGBSeconds += float64(s.DiskOverageMB) / 1024.0 * secs+ }+ }+ return out+}++// emitBucket writes the outbox rows for one settled bucket.+//+// - reserved_usage — one row per (org, bucket) when reservedGB > 0.+// `gb_seconds = reservedGB × 900` (full bucket charge regardless of+// actual usage — the customer paid for the floor whether or not+// they used it).+// - overage_usage — one row per (org, sandbox_tier, bucket) where+// the tier's overage contribution is non-zero.+// - disk_overage_usage — one row per (org, bucket) when any sandbox+// in the bucket exceeded the 20 GB allowance.+//+// `INSERT ... ON CONFLICT DO NOTHING` (inside `UpsertBillableEvent`)+// makes each emission idempotent at the unique constraint.+func emitBucket(ctx context.Context, store *db.Store, orgID uuid.UUID, bucketStart, bucketEnd time.Time, reservedGB int, totals BucketTotals) error {+ if reservedGB > 0 {+ ev := db.BillableEvent{+ OrgID: orgID,+ EventType: db.BillableEventReservedUsage,+ MemoryMB: 0,+ GBSeconds: float64(reservedGB) * 900.0,+ BucketStart: bucketStart,+ BucketEnd: bucketEnd,+ }+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ return err+ }+ }++ for tier, gbs := range totals.OverageGBSecondsByTier {+ if gbs <= 0 {+ continue+ }+ ev := db.BillableEvent{+ OrgID: orgID,+ EventType: db.BillableEventOverageUsage,+ MemoryMB: tier,+ GBSeconds: gbs,+ BucketStart: bucketStart,+ BucketEnd: bucketEnd,+ }+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ return err+ }+ }++ if totals.DiskOverageGBSeconds > 0 {+ ev := db.BillableEvent{+ OrgID: orgID,+ EventType: db.BillableEventDiskOverageUsage,+ MemoryMB: 0,+ GBSeconds: totals.DiskOverageGBSeconds,+ BucketStart: bucketStart,+ BucketEnd: bucketEnd,+ }+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ return err+ }+ }++ return nil+}diff --git a/internal/billing/capacity_reconciler_test.go b/internal/billing/capacity_reconciler_test.gonew file mode 100644index 00000000..75671d11--- /dev/null+++ b/internal/billing/capacity_reconciler_test.go@@ -0,0 +1,239 @@+package billing++import (+ "math"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+)++// IntegrateBucket is the load-bearing math of the unified billing+// pipeline. These tests pin every branch of the spec from+// ws-pricing/work/001 "Per-second integration walk in detail":+//+// - zero-reservation collapses to legacy reporter totals+// - full-coverage reservation produces zero overage+// - partial overage attributes spike across running tiers+// proportionally to share-of-memory+// - disk overage accumulates per-second per-MB above 20 GB+// - mid-bucket scale events split into segments correctly++const (+ bucketStartCanon = 0+ bucketEndCanon = 900+)++func eventAt(memMB, diskMB, fromSec, toSec int) db.ScaleEvent {+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ from := base.Add(time.Duration(fromSec) * time.Second)+ to := base.Add(time.Duration(toSec) * time.Second)+ return db.ScaleEvent{+ MemoryMB: memMB,+ DiskMB: diskMB,+ StartedAt: from,+ EndedAt: &to,+ }+}++func canonicalBucket() (time.Time, time.Time) {+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ return base, base.Add(15 * time.Minute)+}++func eq(t *testing.T, label string, got, want float64) {+ t.Helper()+ if math.Abs(got-want) > 1e-6 {+ t.Errorf("%s: got %v, want %v", label, got, want)+ }+}++func TestIntegrateBucket_zeroReservation_replaysLegacy(t *testing.T) {+ bs, be := canonicalBucket()+ // One 8 GB sandbox running the full bucket.+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ })+ // Zero reservation → all usage is overage. 8 GB × 900 s = 7200 GB-s+ // at tier 8192. Legacy reporter would report tier-seconds=900 at+ // 8192 MB, which corresponds to 8 × 900 = 7200 GB-seconds — exact+ // replay (modulo the legacy per-tick ceil() which we don't apply+ // at the bucket grain).+ eq(t, "tier 8192", totals.OverageGBSecondsByTier[8192], 7200)+ eq(t, "disk overage", totals.DiskOverageGBSeconds, 0)+ if len(totals.OverageGBSecondsByTier) != 1 {+ t.Errorf("expected only tier 8192, got %v", totals.OverageGBSecondsByTier)+ }+}++func TestIntegrateBucket_fullCoverage_noOverage(t *testing.T) {+ bs, be := canonicalBucket()+ // One 8 GB sandbox, reservation covers it.+ totals := IntegrateBucket(bs, be, 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ })+ if len(totals.OverageGBSecondsByTier) != 0 {+ t.Errorf("expected no overage tiers, got %v", totals.OverageGBSecondsByTier)+ }+ eq(t, "reserved floor", totals.ReservedFloorGBSeconds, 8*900)+}++func TestIntegrateBucket_partialOverage_proportionalSplit(t *testing.T) {+ bs, be := canonicalBucket()+ // 8 GB + 16 GB running concurrently for the full bucket; reserved=8.+ // usage=24, spike=16. Tier 8192 share=8/24, tier 16384 share=16/24.+ totals := IntegrateBucket(bs, be, 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ eventAt(16384, 20480, 0, 900),+ })+ eq(t, "tier 8192 overage", totals.OverageGBSecondsByTier[8192], 16.0*(8.0/24.0)*900.0)+ eq(t, "tier 16384 overage", totals.OverageGBSecondsByTier[16384], 16.0*(16.0/24.0)*900.0)+ // Sum of shares is 1.0: total overage = 16 GB × 900 s = 14400.+ total := totals.OverageGBSecondsByTier[8192] + totals.OverageGBSecondsByTier[16384]+ eq(t, "sum-of-shares", total, 14400)+}++func TestIntegrateBucket_sameTierAccumulates(t *testing.T) {+ bs, be := canonicalBucket()+ // Two 8 GB sandboxes, reserved=8. usage=16, spike=8, all on tier 8192.+ // share=16/16=1.0 → overage[8192] = 8 × 900 = 7200.+ totals := IntegrateBucket(bs, be, 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ eventAt(8192, 20480, 0, 900),+ })+ eq(t, "tier 8192", totals.OverageGBSecondsByTier[8192], 7200)+ if len(totals.OverageGBSecondsByTier) != 1 {+ t.Errorf("expected only tier 8192, got %v", totals.OverageGBSecondsByTier)+ }+}++func TestIntegrateBucket_diskOverage(t *testing.T) {+ bs, be := canonicalBucket()+ // 1 sandbox at 8 GB memory, 30 GB disk (10 GB over the 20 GB+ // allowance) running the full bucket.+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ eventAt(8192, 30720, 0, 900),+ })+ // 10 GB × 900 s = 9000 GB-seconds disk overage.+ eq(t, "disk overage", totals.DiskOverageGBSeconds, 9000)+}++func TestIntegrateBucket_segmentedTimeline(t *testing.T) {+ bs, be := canonicalBucket()+ // Mid-bucket scaling:+ // [000s, 300s) one 8 GB sandbox running+ // [300s, 600s) empty+ // [600s, 900s) one 4 GB sandbox running+ // reserved=0.+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 300),+ eventAt(4096, 20480, 600, 900),+ })+ // Segment 1: 8 GB × 300 s = 2400 at tier 8192.+ // Segment 3: 4 GB × 300 s = 1200 at tier 4096.+ eq(t, "tier 8192", totals.OverageGBSecondsByTier[8192], 2400)+ eq(t, "tier 4096", totals.OverageGBSecondsByTier[4096], 1200)+}++func TestIntegrateBucket_eventClippedToBucket(t *testing.T) {+ bs, be := canonicalBucket()+ // Event spans 60 s before bucket through 60 s after. Should clip+ // to the full bucket (900 s).+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ preStart := base.Add(-60 * time.Second)+ postEnd := base.Add(960 * time.Second)+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ {MemoryMB: 8192, DiskMB: 20480, StartedAt: preStart, EndedAt: &postEnd},+ })+ eq(t, "tier 8192 (clipped to bucket)", totals.OverageGBSecondsByTier[8192], 7200)+}++func TestIntegrateBucket_openEvent(t *testing.T) {+ bs, be := canonicalBucket()+ // Event with EndedAt=nil (still open) starting mid-bucket. Should+ // run until bucket_end.+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ totals := IntegrateBucket(bs, be, 0, []db.ScaleEvent{+ {MemoryMB: 8192, DiskMB: 20480, StartedAt: base.Add(450 * time.Second), EndedAt: nil},+ })+ // 8 GB × 450 s (00:07:30 → 00:15:00) = 3600.+ eq(t, "tier 8192 open", totals.OverageGBSecondsByTier[8192], 3600)+}++func TestIntegrateBucket_emptyBucket(t *testing.T) {+ bs, be := canonicalBucket()+ totals := IntegrateBucket(bs, be, 0, nil)+ if len(totals.OverageGBSecondsByTier) != 0 {+ t.Errorf("expected empty overage, got %v", totals.OverageGBSecondsByTier)+ }+ eq(t, "disk", totals.DiskOverageGBSeconds, 0)+ eq(t, "floor", totals.ReservedFloorGBSeconds, 0)+}++func TestIntegrateBucket_reservationOnly_bucketEmittedFromReservedFloor(t *testing.T) {+ // Reservation with no scale events: emitter still must emit the+ // reserved_usage row from the bucket-level call site, but the walk+ // itself produces no overage and no floor (no usage to account for).+ bs, be := canonicalBucket()+ totals := IntegrateBucket(bs, be, 8, nil)+ if len(totals.OverageGBSecondsByTier) != 0 {+ t.Errorf("expected no overage, got %v", totals.OverageGBSecondsByTier)+ }+ eq(t, "disk", totals.DiskOverageGBSeconds, 0)+ // The walk itself doesn't manufacture floor when there's no usage —+ // the emitter charges the full reservedGb × 900 separately. This+ // behaviour is what lets the reserved row stay independent of+ // whether the customer actually used the capacity.+ eq(t, "floor", totals.ReservedFloorGBSeconds, 0)+}++func TestIntegrateBucket_sumOfSharesAlwaysOne(t *testing.T) {+ // Property: at any segment with usage > reservedGb, the per-tier+ // overage shares add up to the total spike × secs exactly. This is+ // the invariant that lets the unified pipeline reproduce the legacy+ // per-tier totals when reservedGb=0.+ bs, be := canonicalBucket()+ cases := []struct {+ name string+ reserved int+ events []db.ScaleEvent+ }{+ {"three tiers concurrent", 4, []db.ScaleEvent{+ eventAt(4096, 20480, 0, 900),+ eventAt(8192, 20480, 0, 900),+ eventAt(16384, 20480, 0, 900),+ }},+ {"two tiers staggered", 8, []db.ScaleEvent{+ eventAt(8192, 20480, 0, 900),+ eventAt(16384, 20480, 300, 900),+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ totals := IntegrateBucket(bs, be, tc.reserved, tc.events)+ // Brute force: integrate the spike second-by-second and+ // confirm the sum matches.+ expected := 0.0+ for sec := 0; sec < 900; sec++ {+ usageGB := 0+ for _, e := range tc.events {+ base := time.Date(2030, 6, 1, 0, 0, 0, 0, time.UTC)+ t0 := e.StartedAt+ t1 := *e.EndedAt+ tNow := base.Add(time.Duration(sec) * time.Second)+ if !tNow.Before(t0) && tNow.Before(t1) {+ usageGB += e.MemoryMB / 1024+ }+ }+ if usageGB > tc.reserved {+ expected += float64(usageGB - tc.reserved)+ }+ }+ actual := 0.0+ for _, gbs := range totals.OverageGBSecondsByTier {+ actual += gbs+ }+ eq(t, "sum-of-shares == brute-force spike", actual, expected)+ })+ }+}diff --git a/internal/db/billable_events.go b/internal/db/billable_events.goindex c06a6c22..85a2ce9b 100644--- a/internal/db/billable_events.go+++ b/internal/db/billable_events.go@@ -117,6 +117,126 @@ func (s *Store) ListPendingBillableEvents(ctx context.Context, limit int) ([]Bilreturn out, nil}+// AllocatorCandidate is one (org, bucket) tuple that may need outbox+// emission. The reconciler runs per-bucket integration on each candidate.+type AllocatorCandidate struct {+ OrgID uuid.UUID+ BucketStart time.Time+}++// ListAllocatorCandidates returns (org, bucket_start) pairs in+// `[lookbackStart, cutoff)` where there's either a reservation or+// scale-event activity, and no row exists yet in `billable_events` for+// that (org, bucket). Result is the work queue for one allocator tick.+//+// `cutoff` should be `now() - settle` truncated to a 15-min boundary —+// only fully-settled buckets become candidates.+func (s *Store) ListAllocatorCandidates(ctx context.Context, lookbackStart, cutoff time.Time, limit int) ([]AllocatorCandidate, error) {+ if limit <= 0 {+ limit = 500+ }+ rows, err := s.pool.Query(ctx, `+ WITH reservation_buckets AS (+ SELECT org_id, starts_at AS bucket_start+ FROM capacity_reservation_intervals+ WHERE starts_at >= $1 AND starts_at < $2+ GROUP BY org_id, starts_at+ ),+ scale_buckets AS (+ SELECT se.org_id, b.bucket_start+ FROM sandbox_scale_events se+ CROSS JOIN LATERAL generate_series(+ date_bin('15 minutes', GREATEST(se.started_at, $1), '2000-01-01 00:00:00+00'::timestamptz),+ date_bin('15 minutes', LEAST(COALESCE(se.ended_at, $2), $2) - INTERVAL '1 microsecond', '2000-01-01 00:00:00+00'::timestamptz),+ INTERVAL '15 minutes'+ ) AS b(bucket_start)+ WHERE se.started_at < $2+ AND COALESCE(se.ended_at, $2) > $1+ GROUP BY se.org_id, b.bucket_start+ ),+ candidates AS (+ SELECT * FROM reservation_buckets+ UNION+ SELECT * FROM scale_buckets+ )+ SELECT c.org_id, c.bucket_start+ FROM candidates c+ WHERE NOT EXISTS (+ SELECT 1 FROM billable_events be+ WHERE be.org_id = c.org_id AND be.bucket_start = c.bucket_start+ )+ ORDER BY c.bucket_start, c.org_id+ LIMIT $3+ `, lookbackStart, cutoff, limit)+ if err != nil {+ return nil, fmt.Errorf("list allocator candidates: %w", err)+ }+ defer rows.Close()++ out := make([]AllocatorCandidate, 0, limit)+ for rows.Next() {+ var c AllocatorCandidate+ if err := rows.Scan(&c.OrgID, &c.BucketStart); err != nil {+ return nil, fmt.Errorf("scan allocator candidate: %w", err)+ }+ out = append(out, c)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("allocator candidate rows: %w", err)+ }+ return out, nil+}++// GetReservedGBForBucket returns the total reserved GB across all+// reservations in `(orgID, ResourceMemoryGB, bucketStart)`. Returns 0+// when no rows exist (no reservation for that bucket).+func (s *Store) GetReservedGBForBucket(ctx context.Context, orgID uuid.UUID, bucketStart time.Time) (int, error) {+ var gb int+ err := s.pool.QueryRow(ctx, `+ SELECT COALESCE(SUM(capacity_gb), 0)::int+ FROM capacity_reservation_intervals+ WHERE org_id = $1 AND resource = $2 AND starts_at = $3+ `, orgID, ResourceMemoryGB, bucketStart).Scan(&gb)+ if err != nil {+ return 0, fmt.Errorf("read reserved gb for bucket: %w", err)+ }+ return gb, nil+}++// GetScaleEventsForBucket returns every scale-event row whose lifetime+// overlaps `[bucketStart, bucketEnd)` for the given org. Open events+// (`ended_at IS NULL`) are returned with `EndedAt = nil`; the caller+// clips them to the bucket boundary.+func (s *Store) GetScaleEventsForBucket(ctx context.Context, orgID uuid.UUID, bucketStart, bucketEnd time.Time) ([]ScaleEvent, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT id, sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at+ FROM sandbox_scale_events+ WHERE org_id = $1+ AND started_at < $3+ AND (ended_at IS NULL OR ended_at > $2)+ ORDER BY started_at+ `, orgID, bucketStart, bucketEnd)+ if err != nil {+ return nil, fmt.Errorf("read scale events for bucket: %w", err)+ }+ defer rows.Close()++ var out []ScaleEvent+ for rows.Next() {+ var e ScaleEvent+ var orgUUID uuid.UUID+ if err := rows.Scan(&e.ID, &e.SandboxID, &orgUUID, &e.MemoryMB, &e.CPUPct, &e.DiskMB, &e.StartedAt, &e.EndedAt); err != nil {+ return nil, fmt.Errorf("scan scale event: %w", err)+ }+ e.OrgID = orgUUID.String()+ out = append(out, e)+ }+ if err := rows.Err(); err != nil {+ return nil, fmt.Errorf("scale events rows: %w", err)+ }+ return out, nil+}+// ListBillableEventsForBucket returns every emitted row for a single// (org, bucket) pair across all event types. Used by the shadow-verify// script and the dashboard breakdown view to reconcile againstdiff --git a/internal/db/billable_events_pgfixture_test.go b/internal/db/billable_events_pgfixture_test.goindex a3a44d3a..6013efa5 100644--- a/internal/db/billable_events_pgfixture_test.go+++ b/internal/db/billable_events_pgfixture_test.go@@ -155,6 +155,126 @@ func TestBillableEvents_listPendingOrder_pgfixture(t *testing.T) {}}+func TestBillableEvents_allocatorCandidates_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ // Use a far-future window so we don't intersect with state from+ // other tests in the same DB.+ bucket := time.Date(2031, 1, 1, 12, 0, 0, 0, time.UTC)+ cutoff := bucket.Add(15 * time.Minute) // bucket end = candidate window end+ lookbackStart := bucket.Add(-1 * time.Hour)++ // Seed one scale event covering the bucket and one reservation+ // for the same bucket.+ end := bucket.Add(15 * time.Minute)+ 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)`,+ "sbx-alloc", orgID, 8192, 200, 20480, bucket, &end); err != nil {+ t.Fatalf("seed scale event: %v", err)+ }+ if _, err := store.pool.Exec(ctx, `+ INSERT INTO capacity_reservation_intervals+ (reservation_id, org_id, resource, starts_at, ends_at, capacity_gb)+ VALUES ($1, $2, $3, $4, $5, $6)+ `, uuid.New(), orgID, ResourceMemoryGB, bucket, end, 4); err != nil {+ t.Fatalf("seed reservation: %v", err)+ }++ cands, err := store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, 100)+ if err != nil {+ t.Fatalf("list candidates: %v", err)+ }+ found := false+ for _, c := range cands {+ if c.OrgID == orgID && c.BucketStart.Equal(bucket) {+ found = true+ break+ }+ }+ if !found {+ t.Fatalf("expected candidate (orgID=%s, bucket=%s) in result, got %d candidates", orgID, bucket, len(cands))+ }++ // Now emit a row for that bucket and confirm the candidate+ // disappears (NOT EXISTS clause).+ ev := makeBucketEvent(orgID, BillableEventReservedUsage, 0, 4*900, bucket, 0)+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {+ t.Fatalf("upsert: %v", err)+ }+ cands, err = store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, 100)+ if err != nil {+ t.Fatalf("list candidates 2: %v", err)+ }+ for _, c := range cands {+ if c.OrgID == orgID && c.BucketStart.Equal(bucket) {+ t.Fatalf("expected candidate to be excluded after emission, got it back")+ }+ }+}++func TestBillableEvents_reservedAndScaleHelpers_pgfixture(t *testing.T) {+ ctx := context.Background()+ store := openPgStore(t)+ orgID := seedOrgWithCap(t, store, 64)++ bucket := time.Date(2031, 2, 1, 12, 0, 0, 0, time.UTC)+ end := bucket.Add(15 * time.Minute)++ // Two reservations (4 GB + 8 GB) on the same bucket → SUM = 12.+ for _, gb := range []int{4, 8} {+ if _, err := store.pool.Exec(ctx, `+ INSERT INTO capacity_reservation_intervals+ (reservation_id, org_id, resource, starts_at, ends_at, capacity_gb)+ VALUES ($1, $2, $3, $4, $5, $6)+ `, uuid.New(), orgID, ResourceMemoryGB, bucket, end, gb); err != nil {+ t.Fatalf("seed reservation %dGB: %v", gb, err)+ }+ }+ got, err := store.GetReservedGBForBucket(ctx, orgID, bucket)+ if err != nil {+ t.Fatalf("get reserved gb: %v", err)+ }+ if got != 12 {+ t.Errorf("reserved gb: got %d, want 12", got)+ }++ // Scale events: one fully inside, one straddling the start, one+ // straddling the end, and one completely outside (must not be+ // returned).+ insertSE := func(sandboxID string, memMB, diskMB int, started time.Time, 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, diskMB, started, ended); err != nil {+ t.Fatalf("seed scale event %s: %v", sandboxID, err)+ }+ }+ preEnd := bucket.Add(5 * time.Minute)+ postStart := bucket.Add(10 * time.Minute)+ farPast := bucket.Add(-2 * time.Hour)+ farPastEnd := bucket.Add(-1 * time.Hour)+ insertSE("sbx-inside", 4096, 20480, bucket.Add(2*time.Minute), &preEnd)+ insertSE("sbx-pre", 8192, 20480, bucket.Add(-3*time.Minute), &postStart)+ insertSE("sbx-post", 16384, 20480, postStart, nil) // open+ insertSE("sbx-outside", 1024, 20480, farPast, &farPastEnd)++ events, err := store.GetScaleEventsForBucket(ctx, orgID, bucket, end)+ if err != nil {+ t.Fatalf("get scale events: %v", err)+ }+ if len(events) != 3 {+ t.Errorf("expected 3 in-window events, got %d", len(events))+ }+ for _, e := range events {+ if e.SandboxID == "sbx-outside" {+ t.Errorf("expected sbx-outside excluded, got it")+ }+ }+}+func TestBillableEvents_validation_pgfixture(t *testing.T) {ctx := context.Background()store := openPgStore(t)