Skip to content

An open-source, faster Devin alternative

TypeScript

feat(billing): phase 3 — unified pipeline for new orgs (dual-path)

Igor Zalutski337e4d6977a6
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 0caefc08..7e013a25 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -396,10 +396,10 @@ func main() {
log.Println("opensandbox: usage reporter started (interval=5m)")
}
- // Phase-2 capacity allocator (shadow mode). Writes reserved/overage
- // rows to the billable_events outbox after each settled bucket;
- // Stripe delivery is not enabled until phase 3. Tunable via env;
- // rollback is by reverting the deploy.
+ // Phase-2 capacity allocator. Writes outbox rows for unified-mode
+ // pro orgs after each settled bucket. Allocator skips legacy and
+ // free orgs (see ListAllocatorCandidates); rollback is by
+ // reverting the deploy.
if opts.Store != nil {
allocOpts := billing.CapacityReconcilerOpts{
Interval: getDurationEnv("CAPACITY_ALLOCATOR_INTERVAL", 5*time.Minute),
@@ -414,6 +414,24 @@ func main() {
allocOpts.Interval, allocOpts.Settle, allocOpts.Lookback)
}
+ // Phase-3 billable-events sender. Ships pending outbox rows to
+ // Stripe via meter events for orgs in `billing_mode='unified'`
+ // with a Stripe customer ID. New orgs default to unified per
+ // migration 031; existing orgs are pinned to legacy and stay
+ // untouched on UsageReporter. Idempotency is per-row via
+ // `billable_events.id` as Stripe meter event Identifier.
+ if opts.Store != nil && stripeClient != nil {
+ senderOpts := billing.BillableEventsSenderOpts{
+ Interval: getDurationEnv("BILLABLE_EVENTS_SENDER_INTERVAL", 5*time.Minute),
+ Batch: getIntEnv("BILLABLE_EVENTS_SENDER_BATCH", 200),
+ }
+ sender := billing.NewBillableEventsSender(opts.Store, stripeClient, senderOpts)
+ sender.Start()
+ defer sender.Stop()
+ log.Printf("opensandbox: billable events sender started (interval=%s, batch=%d)",
+ senderOpts.Interval, senderOpts.Batch)
+ }
+
// Start NATS sync consumer if both PG and NATS are configured
if opts.Store != nil && cfg.NATSURL != "" {
consumer, err := db.NewSyncConsumer(opts.Store, cfg.NATSURL)
diff --git a/internal/billing/billable_events_sender.go b/internal/billing/billable_events_sender.go
new file mode 100644
index 00000000..0dd17c5e
--- /dev/null
+++ b/internal/billing/billable_events_sender.go
@@ -0,0 +1,164 @@
+package billing
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// BillableEventsSender is the phase-3 Stripe shipper. Every `interval`,
+// it pulls pending rows from `billable_events` for orgs in
+// `billing_mode='unified'` and submits them to Stripe meter events
+// using `billable_events.id` as the idempotency key. On success the
+// row's `delivery_state` flips to `'sent'`. On error the row stays
+// `'pending'` and gets retried next tick — Stripe meter events are
+// idempotent by identifier within 24h, so retrying is safe.
+//
+// New orgs default to `billing_mode='unified'` (per migration 031);
+// existing orgs are pinned to `'legacy'`. So on deploy this goroutine
+// has zero work to do until the first new pro signup or until an org
+// is manually flipped.
+type BillableEventsSender struct {
+ store *db.Store
+ stripe *StripeClient
+ interval time.Duration
+ batch int
+ stop chan struct{}
+ stopped chan struct{}
+}
+
+// BillableEventsSenderOpts allows the server bootstrap to override the
+// defaults via env. Zero values fall back to defaults.
+type BillableEventsSenderOpts struct {
+ Interval time.Duration // default 5m — same cadence as UsageReporter
+ Batch int // pending rows per tick, default 200
+}
+
+func NewBillableEventsSender(store *db.Store, stripe *StripeClient, opts BillableEventsSenderOpts) *BillableEventsSender {
+ if opts.Interval <= 0 {
+ opts.Interval = 5 * time.Minute
+ }
+ if opts.Batch <= 0 {
+ opts.Batch = 200
+ }
+ return &BillableEventsSender{
+ store: store,
+ stripe: stripe,
+ interval: opts.Interval,
+ batch: opts.Batch,
+ stop: make(chan struct{}),
+ stopped: make(chan struct{}),
+ }
+}
+
+func (s *BillableEventsSender) Start() { go s.loop() }
+func (s *BillableEventsSender) Stop() { close(s.stop); <-s.stopped }
+
+func (s *BillableEventsSender) loop() {
+ defer close(s.stopped)
+ ticker := time.NewTicker(s.interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ s.tickSafe()
+ case <-s.stop:
+ return
+ }
+ }
+}
+
+func (s *BillableEventsSender) tickSafe() {
+ defer func() {
+ if v := recover(); v != nil {
+ log.Printf("billable-events-sender: recovered from panic: %v", v)
+ }
+ }()
+ s.tick()
+}
+
+func (s *BillableEventsSender) tick() {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+
+ pending, err := s.store.ListPendingBillableEventsForSender(ctx, s.batch)
+ if err != nil {
+ log.Printf("billable-events-sender: list pending: %v", err)
+ return
+ }
+ if len(pending) == 0 {
+ return
+ }
+ log.Printf("billable-events-sender: shipping %d pending event(s)", len(pending))
+
+ sent, failed := 0, 0
+ for _, p := range pending {
+ if err := s.shipOne(ctx, p); err != nil {
+ log.Printf("billable-events-sender: event=%s org=%s type=%s tier=%d: %v",
+ p.Event.ID, p.Event.OrgID, p.Event.EventType, p.Event.MemoryMB, err)
+ failed++
+ continue
+ }
+ sent++
+ }
+ log.Printf("billable-events-sender: sent=%d failed=%d (failed rows stay 'pending' for retry)", sent, failed)
+}
+
+// shipOne maps one outbox row to its Stripe meter event_name, submits
+// the meter event with `Identifier = billable_events.id` for at-least-
+// once safety, and marks the row 'sent' on success.
+func (s *BillableEventsSender) shipOne(ctx context.Context, p db.PendingBillableEventForSender) error {
+ eventName, err := s.meterEventNameFor(p.Event.EventType, p.Event.MemoryMB)
+ if err != nil {
+ return err
+ }
+
+ // Stripe wants a unix timestamp for the meter event. Use the
+ // bucket end — that's the moment the usage was "incurred" from
+ // Stripe's perspective and is stable across retries.
+ timestamp := p.Event.BucketEnd.Unix()
+ identifier := p.Event.ID.String()
+
+ stripeID, err := s.stripe.ReportMeterEvent(eventName, p.StripeCustomerID, p.Event.GBSeconds, identifier, timestamp)
+ if err != nil {
+ return fmt.Errorf("submit meter event: %w", err)
+ }
+
+ if err := s.store.MarkBillableEventSent(ctx, p.Event.ID, stripeID); err != nil {
+ // Stripe accepted the event but we couldn't update the row.
+ // Next tick will resubmit; the Identifier dedup makes this
+ // safe — Stripe will return the same event ID without
+ // double-counting.
+ return fmt.Errorf("mark sent (will retry): %w", err)
+ }
+ return nil
+}
+
+// meterEventNameFor maps an outbox event_type → Stripe meter event_name.
+// All three event types route to a single meter each — overage is flat
+// (the per-tier memory_mb on the outbox row is preserved for analytics
+// but ignored when shipping; Stripe sums GB-seconds across rows).
+func (s *BillableEventsSender) meterEventNameFor(eventType string, memoryMB int) (string, error) {
+ switch eventType {
+ case db.BillableEventReservedUsage:
+ if s.stripe.ReservedMeterEventName == "" {
+ return "", fmt.Errorf("reserved meter not provisioned (run EnsureProducts)")
+ }
+ return s.stripe.ReservedMeterEventName, nil
+ case db.BillableEventOverageUsage:
+ if s.stripe.OverageMeterEventName == "" {
+ return "", fmt.Errorf("overage meter not provisioned (run EnsureProducts)")
+ }
+ return s.stripe.OverageMeterEventName, nil
+ case db.BillableEventDiskOverageUsage:
+ if s.stripe.DiskOverageMeterEventName == "" {
+ return "", fmt.Errorf("disk overage meter not provisioned")
+ }
+ return s.stripe.DiskOverageMeterEventName, nil
+ default:
+ return "", fmt.Errorf("unknown event_type %q", eventType)
+ }
+}
diff --git a/internal/billing/billable_events_sender_test.go b/internal/billing/billable_events_sender_test.go
new file mode 100644
index 00000000..5d7d9d96
--- /dev/null
+++ b/internal/billing/billable_events_sender_test.go
@@ -0,0 +1,85 @@
+package billing
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// meterEventNameFor pins the (event_type, memory_mb) → Stripe meter
+// routing. Overage is flat — memory_mb is preserved on the outbox row
+// for analytics but ignored at ship time so a 1 GB and 64 GB sandbox
+// hit the same meter.
+
+func newSenderForTest() *BillableEventsSender {
+ stripe := &StripeClient{
+ ReservedMeterEventName: "sandbox_compute_sandbox_reserved",
+ OverageMeterEventName: "sandbox_compute_sandbox_overage",
+ DiskOverageMeterEventName: "sandbox_compute_sandbox_disk_overage",
+ }
+ return &BillableEventsSender{stripe: stripe}
+}
+
+func TestSender_meterEventName_reservedFlat(t *testing.T) {
+ s := newSenderForTest()
+ got, err := s.meterEventNameFor(db.BillableEventReservedUsage, 0)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if got != "sandbox_compute_sandbox_reserved" {
+ t.Errorf("got %q", got)
+ }
+}
+
+func TestSender_meterEventName_overageFlatAcrossTiers(t *testing.T) {
+ s := newSenderForTest()
+ for _, tier := range []int{1024, 4096, 8192, 16384, 32768, 65536} {
+ got, err := s.meterEventNameFor(db.BillableEventOverageUsage, tier)
+ if err != nil {
+ t.Fatalf("tier %d: err: %v", tier, err)
+ }
+ if got != "sandbox_compute_sandbox_overage" {
+ t.Errorf("tier %d: got %q, want flat overage meter", tier, got)
+ }
+ }
+}
+
+func TestSender_meterEventName_diskOverage(t *testing.T) {
+ s := newSenderForTest()
+ got, err := s.meterEventNameFor(db.BillableEventDiskOverageUsage, 0)
+ if err != nil {
+ t.Fatalf("err: %v", err)
+ }
+ if got != "sandbox_compute_sandbox_disk_overage" {
+ t.Errorf("got %q", got)
+ }
+}
+
+func TestSender_meterEventName_unknownTypeRejected(t *testing.T) {
+ s := newSenderForTest()
+ _, err := s.meterEventNameFor("totally_made_up", 0)
+ if err == nil || !strings.Contains(err.Error(), "unknown event_type") {
+ t.Errorf("expected unknown event_type error, got %v", err)
+ }
+}
+
+func TestSender_meterEventName_missingProvisionRejected(t *testing.T) {
+ // Empty stripe client — no meters provisioned. Sender must error
+ // loudly rather than ship to an empty event_name.
+ s := &BillableEventsSender{stripe: &StripeClient{}}
+ cases := []struct {
+ eventType string
+ want string
+ }{
+ {db.BillableEventReservedUsage, "reserved meter not provisioned"},
+ {db.BillableEventOverageUsage, "overage meter not provisioned"},
+ {db.BillableEventDiskOverageUsage, "disk overage meter not provisioned"},
+ }
+ for _, tc := range cases {
+ _, err := s.meterEventNameFor(tc.eventType, 0)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Errorf("event_type=%s: expected %q, got %v", tc.eventType, tc.want, err)
+ }
+ }
+}
diff --git a/internal/billing/pricing.go b/internal/billing/pricing.go
index 508310cc..62db397b 100644
--- a/internal/billing/pricing.go
+++ b/internal/billing/pricing.go
@@ -59,6 +59,41 @@ const (
DiskOverageMetadataKey = "sandbox_disk_overage"
)
+// --- Phase-3 unified pipeline meters ---
+//
+// New orgs (`billing_mode='unified'`, default per migration 031) are
+// billed via two flat meters with `unit = GB-seconds`:
+//
+// - Reserved: customer-facing name "pre-booked." Only orgs that
+// reserve capacity pay this.
+// - Overage: customer-facing name "instant." Flat per-GB rate
+// regardless of sandbox tier.
+//
+// **Dollar rates are deliberately not in code.** Stripe Prices are
+// configured in the Stripe Dashboard (or via Stripe API by the
+// pricing team) and linked to the meters below. The sender ships
+// meter events with `value = GB-seconds`; Stripe computes invoice
+// dollars from Price × value at billing time. This decouples
+// pricing changes from code deploys.
+//
+// **Existing orgs (`billing_mode='legacy'`) are completely unaffected
+// by these meters.** They continue to bill via `TierPricePerSecond`
+// and the legacy `sandbox_compute_<tier>` meters through
+// `UsageReporter`. The dollar amounts in `TierPricePerSecond` stay
+// in code because free-tier credit deduction
+// (`CalculateUsageCostCents`) computes cents locally without a
+// Stripe round-trip — a real reason for those constants. Phase 3
+// just doesn't add new ones.
+const (
+ // Pre-booked: single meter, no tier breakdown.
+ ReservedMeterKey = "sandbox_reserved"
+ ReservedPriceKey = "sandbox_reserved_v1"
+
+ // Instant (overage): single meter, flat across all sandbox sizes.
+ OverageMeterKey = "sandbox_overage"
+ OveragePriceKey = "sandbox_overage_v1"
+)
+
// DiskOverageGBSeconds returns the chargeable GB-seconds for one usage summary
// row (zero if the sandbox stayed within the free allowance).
func DiskOverageGBSeconds(s db.OrgUsageSummary) float64 {
diff --git a/internal/billing/stripe.go b/internal/billing/stripe.go
index ea7ca527..58b1c019 100644
--- a/internal/billing/stripe.go
+++ b/internal/billing/stripe.go
@@ -34,6 +34,15 @@ type StripeClient struct {
// Disk overage meter / price (single dimension: GB-seconds above 20GB).
DiskOveragePriceID string
DiskOverageMeterEventName string
+
+ // Phase-3 unified-pipeline meters and prices. Two flat meters
+ // (overage + reserved) used by new orgs (`billing_mode='unified'`).
+ // Legacy per-tier meters above are untouched and continue to serve
+ // existing orgs via UsageReporter.
+ OveragePriceID string // flat overage Price for `overage_usage` events
+ OverageMeterEventName string // "sandbox_compute_sandbox_overage"
+ ReservedPriceID string // flat reserved Price for `reserved_usage` events
+ ReservedMeterEventName string // "sandbox_compute_sandbox_reserved"
}
// NewStripeClient creates a new Stripe client.
@@ -222,9 +231,64 @@ func (s *StripeClient) EnsureProducts() error {
log.Printf("billing: created disk overage price (id=%s)", p.ID)
}
+ // 5. Phase-3 unified-pipeline meters. Two flat meters (overage +
+ // reserved) at unit GB-seconds. Code creates the *meters* (their
+ // event names are stable wire-protocol coupling) but **does not
+ // create Prices** — those are configured in the Stripe Dashboard
+ // so pricing changes don't need a code deploy. The Price IDs
+ // are discovered below if present; if missing, meter events
+ // still flow but won't appear on invoices until a Price is
+ // linked to the meter in Stripe.
+ s.OverageMeterEventName = ensureMeter(existingMeters, "sandbox_compute_"+OverageMeterKey, "Sandbox Instant Compute (GB-seconds)")
+ s.ReservedMeterEventName = ensureMeter(existingMeters, "sandbox_compute_"+ReservedMeterKey, "Sandbox Reserved Capacity (GB-seconds)")
+
+ if id, ok := existingPrices[OveragePriceKey]; ok {
+ s.OveragePriceID = id
+ log.Printf("billing: found existing overage price (id=%s)", id)
+ } else {
+ log.Printf("billing: no overage price configured for meter %s — meter events will flow but won't appear on invoices until a Price is created in Stripe", s.OverageMeterEventName)
+ }
+ if id, ok := existingPrices[ReservedPriceKey]; ok {
+ s.ReservedPriceID = id
+ log.Printf("billing: found existing reserved price (id=%s)", id)
+ } else {
+ log.Printf("billing: no reserved price configured for meter %s — meter events will flow but won't appear on invoices until a Price is created in Stripe", s.ReservedMeterEventName)
+ }
+
return nil
}
+// ensureMeter is a small helper that returns the event_name after
+// creating or finding the meter. Used only for the phase-3 flat
+// meters; legacy per-tier meters retain their inline creation so the
+// unrelated stripe.go diff stays small.
+func ensureMeter(existing map[string]*stripe.BillingMeter, eventName, displayName string) string {
+ if m, ok := existing[eventName]; ok {
+ log.Printf("billing: found existing meter %s (id=%s)", eventName, m.ID)
+ return eventName
+ }
+ m, err := meter.New(&stripe.BillingMeterParams{
+ DisplayName: stripe.String(displayName),
+ EventName: stripe.String(eventName),
+ DefaultAggregation: &stripe.BillingMeterDefaultAggregationParams{
+ Formula: stripe.String(string(stripe.BillingMeterDefaultAggregationFormulaSum)),
+ },
+ CustomerMapping: &stripe.BillingMeterCustomerMappingParams{
+ EventPayloadKey: stripe.String("stripe_customer_id"),
+ Type: stripe.String(string(stripe.BillingMeterCustomerMappingTypeByID)),
+ },
+ ValueSettings: &stripe.BillingMeterValueSettingsParams{
+ EventPayloadKey: stripe.String("value"),
+ },
+ })
+ if err != nil {
+ log.Printf("billing: WARN failed to create meter %s: %v", eventName, err)
+ return eventName // return name anyway; sender will fail loudly if used
+ }
+ log.Printf("billing: created meter %s (id=%s)", eventName, m.ID)
+ return eventName
+}
+
// CreateCustomer creates a Stripe customer for an org.
func (s *StripeClient) CreateCustomer(orgName, email string) (string, error) {
params := &stripe.CustomerParams{
@@ -275,7 +339,10 @@ func (s *StripeClient) CreatePortalSession(customerID, returnURL string) (string
}
// CreateSubscription creates a subscription with metered prices for all tiers.
-// Returns subscription ID and map of memoryMB → subscription item ID.
+// Returns subscription ID and map of memoryMB → subscription item ID
+// (legacy per-second tier items only; phase-3 overage/reserved items
+// are added to the subscription but not returned in the map since
+// `org_subscription_items` only tracks the legacy mapping).
func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]string, error) {
var items []*stripe.SubscriptionItemsParams
for _, priceID := range s.PriceIDs {
@@ -288,6 +355,21 @@ func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]st
Price: stripe.String(s.DiskOveragePriceID),
})
}
+ // Phase-3 unified-pipeline items: flat overage + flat reserved.
+ // New orgs default to `billing_mode='unified'` so meter events
+ // flow to these items. Existing legacy orgs sit at zero usage
+ // on these line items (Stripe omits zero-usage rows from invoices,
+ // so they're invisible to the customer).
+ if s.OveragePriceID != "" {
+ items = append(items, &stripe.SubscriptionItemsParams{
+ Price: stripe.String(s.OveragePriceID),
+ })
+ }
+ if s.ReservedPriceID != "" {
+ items = append(items, &stripe.SubscriptionItemsParams{
+ Price: stripe.String(s.ReservedPriceID),
+ })
+ }
sub, err := subscription.New(&stripe.SubscriptionParams{
Customer: stripe.String(customerID),
@@ -346,6 +428,34 @@ func (s *StripeClient) ReportUsage(customerID string, memoryMB int, seconds int6
return nil
}
+// ReportMeterEvent sends a single Stripe meter event with an
+// idempotency identifier. Used by the phase-3 sender to ship outbox
+// rows; the identifier (typically `billable_events.id`) makes
+// at-least-once shipping safe — Stripe dedups repeated submissions
+// of the same identifier within 24h.
+//
+// Returns the resulting BillingMeterEvent.Identifier echo'd by Stripe
+// (which equals the input on successful submission). Caller stores
+// this in `billable_events.stripe_event_id` for traceability.
+func (s *StripeClient) ReportMeterEvent(eventName, customerID string, value float64, identifier string, timestamp int64) (string, error) {
+ resp, err := meterevent.New(&stripe.BillingMeterEventParams{
+ EventName: stripe.String(eventName),
+ Identifier: stripe.String(identifier),
+ Timestamp: stripe.Int64(timestamp),
+ Payload: map[string]string{
+ "stripe_customer_id": customerID,
+ // Stripe accepts string-encoded values; use a high-precision
+ // format so fractional GB-seconds (the proportional split
+ // produces them) don't get truncated to integers.
+ "value": fmt.Sprintf("%.6f", value),
+ },
+ })
+ if err != nil {
+ return "", fmt.Errorf("report meter event %s: %w", eventName, err)
+ }
+ return resp.Identifier, nil
+}
+
// ReportDiskOverageUsage sends a meter event for disk overage GB-seconds
// (provisioned disk above 20GB, integrated over time).
func (s *StripeClient) ReportDiskOverageUsage(customerID string, gbSeconds int64, timestamp int64) error {
diff --git a/internal/db/billable_events.go b/internal/db/billable_events.go
index 9f3ce72e..48549d82 100644
--- a/internal/db/billable_events.go
+++ b/internal/db/billable_events.go
@@ -124,6 +124,83 @@ type AllocatorCandidate struct {
BucketStart time.Time
}
+// PendingBillableEventForSender carries the row plus the joined
+// `orgs.stripe_customer_id` so the sender can submit a meter event
+// without a second per-event DB lookup. Only orgs with
+// `billing_mode='unified'` and a non-null Stripe customer ID are
+// returned — legacy orgs and unset-billing orgs are filtered out at
+// query time.
+type PendingBillableEventForSender struct {
+ Event BillableEvent
+ StripeCustomerID string
+}
+
+// ListPendingBillableEventsForSender returns up to `limit` pending
+// rows ordered by `(created_at, id)` from orgs in unified mode that
+// have a Stripe customer ID set. Skipped:
+// - rows where the org is `billing_mode='legacy'` (UsageReporter
+// ships those)
+// - rows where the org has no Stripe customer (free-tier or
+// unfinished checkout)
+// - rows already in `delivery_state='sent'` or `'failed'`
+func (s *Store) ListPendingBillableEventsForSender(ctx context.Context, limit int) ([]PendingBillableEventForSender, error) {
+ if limit <= 0 {
+ limit = 100
+ }
+ rows, err := s.pool.Query(ctx, `
+ SELECT be.id, be.org_id, be.event_type, be.memory_mb, be.gb_seconds,
+ be.bucket_start, be.bucket_end, be.delivery_state,
+ be.stripe_event_id, be.created_at, be.delivered_at,
+ o.stripe_customer_id
+ FROM billable_events be
+ JOIN orgs o ON o.id = be.org_id
+ WHERE be.delivery_state = 'pending'
+ AND o.billing_mode = 'unified'
+ AND o.stripe_customer_id IS NOT NULL
+ ORDER BY be.created_at, be.id
+ LIMIT $1
+ `, limit)
+ if err != nil {
+ return nil, fmt.Errorf("list pending billable events for sender: %w", err)
+ }
+ defer rows.Close()
+
+ out := make([]PendingBillableEventForSender, 0, limit)
+ for rows.Next() {
+ var p PendingBillableEventForSender
+ if err := rows.Scan(
+ &p.Event.ID, &p.Event.OrgID, &p.Event.EventType, &p.Event.MemoryMB, &p.Event.GBSeconds,
+ &p.Event.BucketStart, &p.Event.BucketEnd, &p.Event.DeliveryState,
+ &p.Event.StripeEventID, &p.Event.CreatedAt, &p.Event.DeliveredAt,
+ &p.StripeCustomerID,
+ ); err != nil {
+ return nil, fmt.Errorf("scan pending event for sender: %w", err)
+ }
+ out = append(out, p)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("pending events for sender rows: %w", err)
+ }
+ return out, nil
+}
+
+// MarkBillableEventSent flips delivery_state to 'sent', stamps
+// stripe_event_id and delivered_at. Idempotent at the row level: a
+// concurrent re-run with the same id is harmless.
+func (s *Store) MarkBillableEventSent(ctx context.Context, id uuid.UUID, stripeEventID string) error {
+ _, err := s.pool.Exec(ctx, `
+ UPDATE billable_events
+ SET delivery_state = 'sent',
+ stripe_event_id = $2,
+ delivered_at = now()
+ WHERE id = $1
+ `, id, stripeEventID)
+ if err != nil {
+ return fmt.Errorf("mark billable event sent: %w", err)
+ }
+ return nil
+}
+
// 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
@@ -131,15 +208,27 @@ type AllocatorCandidate struct {
//
// `cutoff` should be `now() - settle` truncated to a 15-min boundary —
// only fully-settled buckets become candidates.
+//
+// **Filter:** only orgs with `plan='pro' AND billing_mode='unified'`.
+// Legacy-mode orgs are billed by `UsageReporter`, so writing outbox
+// rows for them would be both wasted work and a landmine on a
+// later flip (the historical rows would ship at once). Free-plan
+// orgs use the legacy credit-deduction path; the future free-tier
+// drainer will revisit allocator scope when it ships.
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 (
+ WITH eligible_orgs AS (
+ SELECT id FROM orgs
+ WHERE plan = 'pro' AND billing_mode = 'unified'
+ ),
+ reservation_buckets AS (
SELECT org_id, starts_at AS bucket_start
FROM capacity_reservation_intervals
WHERE starts_at >= $1 AND starts_at < $2
+ AND org_id IN (SELECT id FROM eligible_orgs)
GROUP BY org_id, starts_at
),
scale_buckets AS (
@@ -152,6 +241,7 @@ func (s *Store) ListAllocatorCandidates(ctx context.Context, lookbackStart, cuto
) AS b(bucket_start)
WHERE se.started_at < $2
AND COALESCE(se.ended_at, $2) > $1
+ AND se.org_id IN (SELECT id FROM eligible_orgs)
GROUP BY se.org_id, b.bucket_start
),
candidates AS (
diff --git a/internal/db/billable_events_pgfixture_test.go b/internal/db/billable_events_pgfixture_test.go
index 6013efa5..132cafa0 100644
--- a/internal/db/billable_events_pgfixture_test.go
+++ b/internal/db/billable_events_pgfixture_test.go
@@ -275,6 +275,176 @@ func TestBillableEvents_reservedAndScaleHelpers_pgfixture(t *testing.T) {
}
}
+// seedOrgWithBillingMode inserts an org with explicit plan, billing_mode,
+// and optional Stripe customer ID — used by the sender's filtering
+// tests so we can exercise every branch of the JOIN+WHERE clause.
+func seedOrgWithBillingMode(t *testing.T, store *Store, plan, billingMode string, stripeCustomerID *string) uuid.UUID {
+ t.Helper()
+ ctx := context.Background()
+ orgID := uuid.New()
+ _, err := store.pool.Exec(ctx, `
+ INSERT INTO orgs (id, name, slug, plan, billing_mode, stripe_customer_id, max_concurrent_sandboxes, max_sandbox_timeout_sec, max_disk_mb, max_memory_gb)
+ VALUES ($1, $2, $3, $4, $5, $6, 100, 86400, 20480, 64)
+ `, orgID, "sender-"+orgID.String()[:8], "sender-"+orgID.String()[:8], plan, billingMode, stripeCustomerID)
+ if err != nil {
+ t.Fatalf("seed org plan=%s billing_mode=%s: %v", plan, billingMode, err)
+ }
+ return orgID
+}
+
+func TestSender_listFiltersCorrectly_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ // Three orgs covering all branches of the sender's JOIN+WHERE filter.
+ // Each gets a distinct stripe_customer_id (unique constraint on orgs).
+ cusUnified := "cus_test_unified_" + uuid.New().String()[:8]
+ cusLegacy := "cus_test_legacy_" + uuid.New().String()[:8]
+ orgUnified := seedOrgWithBillingMode(t, store, "pro", "unified", &cusUnified)
+ orgLegacy := seedOrgWithBillingMode(t, store, "pro", "legacy", &cusLegacy)
+ orgUnifiedNoCustomer := seedOrgWithBillingMode(t, store, "pro", "unified", nil)
+
+ // Use far-future buckets to avoid cross-test interference.
+ base := time.Date(2032, 1, 1, 12, 0, 0, 0, time.UTC)
+ for i, orgID := range []uuid.UUID{orgUnified, orgLegacy, orgUnifiedNoCustomer} {
+ ev := makeBucketEvent(orgID, BillableEventOverageUsage, 8192, 7200, base, i)
+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {
+ t.Fatalf("upsert org %d: %v", i, err)
+ }
+ }
+
+ pending, err := store.ListPendingBillableEventsForSender(ctx, 100)
+ if err != nil {
+ t.Fatalf("list pending: %v", err)
+ }
+
+ mine := map[uuid.UUID]bool{}
+ for _, p := range pending {
+ mine[p.Event.OrgID] = true
+ if p.Event.OrgID == orgUnified && p.StripeCustomerID != cusUnified {
+ t.Errorf("expected stripe_customer_id=%q, got %q", cusUnified, p.StripeCustomerID)
+ }
+ }
+ if !mine[orgUnified] {
+ t.Errorf("expected unified+customer org in result")
+ }
+ if mine[orgLegacy] {
+ t.Errorf("legacy org must be excluded (UsageReporter handles it)")
+ }
+ if mine[orgUnifiedNoCustomer] {
+ t.Errorf("unified org without stripe_customer_id must be excluded")
+ }
+}
+
+func TestSender_markSent_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ customerID := "cus_test_marksent"
+ orgID := seedOrgWithBillingMode(t, store, "pro", "unified", &customerID)
+ base := time.Date(2032, 2, 1, 12, 0, 0, 0, time.UTC)
+ ev := makeBucketEvent(orgID, BillableEventOverageUsage, 8192, 7200, base, 0)
+ if _, err := store.UpsertBillableEvent(ctx, ev); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+
+ // Find the event we just inserted (id is generated by the DB).
+ pending, err := store.ListPendingBillableEventsForSender(ctx, 100)
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ var eventID uuid.UUID
+ for _, p := range pending {
+ if p.Event.OrgID == orgID {
+ eventID = p.Event.ID
+ break
+ }
+ }
+ if eventID == uuid.Nil {
+ t.Fatalf("could not locate inserted event")
+ }
+
+ if err := store.MarkBillableEventSent(ctx, eventID, "stripe_test_event_42"); err != nil {
+ t.Fatalf("mark sent: %v", err)
+ }
+
+ // Confirm row flipped + sender no longer sees it.
+ rows, err := store.ListBillableEventsForBucket(ctx, orgID, ev.BucketStart)
+ if err != nil {
+ t.Fatalf("list bucket: %v", err)
+ }
+ if len(rows) != 1 {
+ t.Fatalf("expected 1 row, got %d", len(rows))
+ }
+ if rows[0].DeliveryState != BillableDeliverySent {
+ t.Errorf("delivery_state: got %q, want sent", rows[0].DeliveryState)
+ }
+ if rows[0].StripeEventID == nil || *rows[0].StripeEventID != "stripe_test_event_42" {
+ t.Errorf("stripe_event_id mismatch: %v", rows[0].StripeEventID)
+ }
+ if rows[0].DeliveredAt == nil {
+ t.Errorf("delivered_at should be set")
+ }
+
+ pending2, err := store.ListPendingBillableEventsForSender(ctx, 100)
+ if err != nil {
+ t.Fatalf("list pending 2: %v", err)
+ }
+ for _, p := range pending2 {
+ if p.Event.ID == eventID {
+ t.Errorf("sender still sees event after mark sent")
+ }
+ }
+}
+
+func TestAllocatorCandidates_filtersByBillingMode_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ cusUnified := "cus_test_alloc_unified_" + uuid.New().String()[:8]
+ cusLegacy := "cus_test_alloc_legacy_" + uuid.New().String()[:8]
+ orgUnified := seedOrgWithBillingMode(t, store, "pro", "unified", &cusUnified)
+ orgLegacy := seedOrgWithBillingMode(t, store, "pro", "legacy", &cusLegacy)
+ orgFree := seedOrgWithBillingMode(t, store, "free", "unified", nil)
+
+ // Far-future window so other tests don't interfere.
+ bucket := time.Date(2032, 3, 1, 12, 0, 0, 0, time.UTC)
+ end := bucket.Add(15 * time.Minute)
+ cutoff := end
+ lookbackStart := bucket.Add(-1 * time.Hour)
+
+ // Each org gets one scale event covering the bucket.
+ for _, orgID := range []uuid.UUID{orgUnified, orgLegacy, orgFree} {
+ 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-"+orgID.String()[:8], orgID, 8192, 200, 20480, bucket, &end); err != nil {
+ t.Fatalf("seed scale event: %v", err)
+ }
+ }
+
+ cands, err := store.ListAllocatorCandidates(ctx, lookbackStart, cutoff, 100)
+ if err != nil {
+ t.Fatalf("list candidates: %v", err)
+ }
+
+ mine := map[uuid.UUID]bool{}
+ for _, c := range cands {
+ if c.BucketStart.Equal(bucket) {
+ mine[c.OrgID] = true
+ }
+ }
+ if !mine[orgUnified] {
+ t.Errorf("expected pro+unified org as candidate")
+ }
+ if mine[orgLegacy] {
+ t.Errorf("legacy pro org must NOT be a candidate (UsageReporter handles it)")
+ }
+ if mine[orgFree] {
+ t.Errorf("free org must NOT be a candidate (legacy credit deduction handles it)")
+ }
+}
+
func TestBillableEvents_validation_pgfixture(t *testing.T) {
ctx := context.Background()
store := openPgStore(t)
diff --git a/internal/db/migrations/031_orgs_billing_mode.down.sql b/internal/db/migrations/031_orgs_billing_mode.down.sql
new file mode 100644
index 00000000..5dca6648
--- /dev/null
+++ b/internal/db/migrations/031_orgs_billing_mode.down.sql
@@ -0,0 +1 @@
+ALTER TABLE orgs DROP COLUMN IF EXISTS billing_mode;
diff --git a/internal/db/migrations/031_orgs_billing_mode.up.sql b/internal/db/migrations/031_orgs_billing_mode.up.sql
new file mode 100644
index 00000000..65f7ac0d
--- /dev/null
+++ b/internal/db/migrations/031_orgs_billing_mode.up.sql
@@ -0,0 +1,14 @@
+-- Per-org billing pipeline selector. The unified pipeline (allocator
+-- + outbox + sender) ships outbox rows to Stripe for orgs in
+-- 'unified' mode; UsageReporter ships for orgs in 'legacy' mode.
+-- Both paths use the same dollar amounts via current tiered rates —
+-- the column controls which goroutine emits the meter events, not
+-- what the customer pays.
+--
+-- Policy: new orgs default to 'unified' (covered by the column
+-- DEFAULT). Existing orgs are pinned to 'legacy' below to preserve
+-- their current billing path until an explicit decision flips them.
+ALTER TABLE orgs ADD COLUMN billing_mode TEXT NOT NULL DEFAULT 'unified'
+ CHECK (billing_mode IN ('legacy', 'unified'));
+
+UPDATE orgs SET billing_mode = 'legacy';
diff --git a/internal/db/store.go b/internal/db/store.go
index 39c511c9..238f640f 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -124,6 +124,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{31, "migrations/028_capacity_idempotency_keys.up.sql"},
{32, "migrations/029_orgs_max_memory_gb.up.sql"},
{33, "migrations/030_billable_events.up.sql"},
+ {34, "migrations/031_orgs_billing_mode.up.sql"},
}
for _, m := range migrations {
@@ -194,6 +195,13 @@ type Org struct {
StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`
LastUsageReportedAt time.Time `json:"lastUsageReportedAt"`
PriceLocked bool `json:"priceLocked"`
+
+ // Per-org billing pipeline selector. 'legacy' = UsageReporter ships
+ // to Stripe; 'unified' = the phase-3 sender ships from
+ // billable_events. Both paths produce the same dollar amounts via
+ // today's tiered rates — the column controls *how* events are
+ // emitted, not what the customer pays.
+ BillingMode string `json:"billingMode"`
}
// orgColumns is the list of columns returned by all Org queries.
@@ -202,7 +210,7 @@ const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_
verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,
workos_org_id, is_personal, owner_user_id, credit_balance_cents,
stripe_customer_id, stripe_subscription_id, last_usage_reported_at, price_locked,
- free_credits_remaining_cents`
+ free_credits_remaining_cents, billing_mode`
// scanOrg scans a row into an Org struct.
func scanOrg(row pgx.Row) (*Org, error) {
@@ -215,7 +223,7 @@ func scanOrg(row pgx.Row) (*Org, error) {
&org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,
&org.StripeCustomerID, &org.StripeSubscriptionID, &org.LastUsageReportedAt,
&org.PriceLocked,
- &org.FreeCreditsRemainingCents,
+ &org.FreeCreditsRemainingCents, &org.BillingMode,
)
return org, err
}
diff --git a/internal/db/usage.go b/internal/db/usage.go
index bfb6a716..2260d533 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -233,14 +233,19 @@ func (s *Store) UpdateLastUsageReportedAt(ctx context.Context, orgID uuid.UUID,
return err
}
-// ListBillableOrgIDs returns org IDs with plan="pro" that have unreported usage:
-// either a currently-running sandbox or a scale event that ended after the last report.
+// ListBillableOrgIDs returns org IDs with plan="pro" AND
+// billing_mode='legacy' that have unreported usage: either a
+// currently-running sandbox or a scale event that ended after the last
+// report. Orgs in billing_mode='unified' are shipped via the phase-3
+// `BillableEventsSender` reading from `billable_events`, so they must
+// be skipped here to prevent double-billing.
func (s *Store) ListBillableOrgIDs(ctx context.Context) ([]uuid.UUID, error) {
rows, err := s.pool.Query(ctx,
`SELECT DISTINCT se.org_id
FROM sandbox_scale_events se
JOIN orgs o ON o.id = se.org_id
WHERE o.plan = 'pro'
+ AND o.billing_mode = 'legacy'
AND (se.ended_at IS NULL OR se.ended_at > o.last_usage_reported_at)`)
if err != nil {
return nil, err