Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(ai-billing): remove direct usage charges (#7752)
Peter Chinmand14bac5547be
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex 1de8455ef6..c7369ccd2e 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -100,7 +100,7 @@ import type {} from './schemas';/**- * @summary Turn automatic credit reloads (and with them overage) on with the given+ * @summary Turn automatic credit reloads on with the giventhresholds, or off. Payer only. Enabling settles right away, so a balancealready under the minimum reloads immediately.*/@@ -258,7 +258,7 @@ export const createAiCreditCheckout = async (};/**- * @summary Turn overage billing on or off and set the per-period cap. Payer only.+ * @summary Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.*/export type updateAiBillingOverageResponse200 = {data: UsageSnapshot;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.tsindex 2c778d2a3d..e898f17007 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/autoReloadSnapshot.ts@@ -10,7 +10,7 @@ import type { AutoReloadSnapshotMonthlySpendLimitCents } from './autoReloadSnaps* The payer's automatic reload settings, as shown in Billing settings.*/export interface AutoReloadSnapshot {- /** Whether reloads will fire: overage is on and reloads are not suspended. */+ /** Whether reloads will fire: the payer opted in and reloads are not suspended. */active: boolean;/** Reload once the effective balance drops below this, in customer cents. */minimum_balance_cents: number;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequest.tsindex 28f94791de..9ad504c98b 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequest.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequest.ts@@ -10,15 +10,12 @@ import type { UpdateAutoReloadRequestMonthlySpendLimitCents } from './updateAuto* Request body for [`update_auto_reload_handler`].*/export interface UpdateAutoReloadRequest {- /** Reload credits automatically, billing usage past allowance and-credits to the payer's card. Turning this off also turns off overage. */+ /** Purchase prepaid credits automatically using the payer's card. */enabled: boolean;/** Reload once the balance drops below this, cents. Must be positive. */minimumBalanceCents: number;/** Most to reload per calendar month, cents. Omit or `null` for no limit.-Also serves as the per-period overage cap, so it must be at least the-catalog's `overage_limit_min_cents`; larger values are capped at-`overage_limit_max_cents`. */+Must be at least the catalog's `overage_limit_min_cents` (legacy name). */monthlySpendLimitCents?: UpdateAutoReloadRequestMonthlySpendLimitCents;/** Reload the balance back up to this, cents. At least $0.50 above theminimum and no more than the catalog's `auto_reload_target_max_cents`. */diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequestMonthlySpendLimitCents.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequestMonthlySpendLimitCents.tsindex 692bd53aff..1703d599c2 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequestMonthlySpendLimitCents.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/updateAutoReloadRequestMonthlySpendLimitCents.ts@@ -7,8 +7,6 @@/*** Most to reload per calendar month, cents. Omit or `null` for no limit.-Also serves as the per-period overage cap, so it must be at least the-catalog's `overage_limit_min_cents`; larger values are capped at-`overage_limit_max_cents`.+Must be at least the catalog's `overage_limit_min_cents` (legacy name).*/export type UpdateAutoReloadRequestMonthlySpendLimitCents = number | null;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.tsindex 17d982dc1e..317f7bb8d0 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts@@ -13,7 +13,7 @@ import type { UsageSnapshotBlockedReason } from './usageSnapshotBlockedReason';by the gate.*/export interface UsageSnapshot {- /** Automatic credit reload settings. `active` means overage is on and+ /** Automatic credit reload settings. `active` means the payer opted in andreloads are not suspended. */auto_reload: AutoReloadSnapshot;blocked_reason?: UsageSnapshotBlockedReason;@@ -27,7 +27,7 @@ reloads are not suspended. */included_cents: number;/** Shared overage charged so far this period, in customer cents. */overage_charged_cents: number;- /** Whether overage billing is on. */+ /** Legacy API name for the automatic reload opt-in. Never authorizes direct charges. */overage_enabled: boolean;/** Per-period overage cap, in customer cents. */overage_limit_cents: number;diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex cf38f9e762..23c9831b11 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -13,7 +13,7 @@"/ai-billing/auto-reload": {"patch": {"tags": ["ai_billing"],- "summary": "Turn automatic credit reloads (and with them overage) on with the given\nthresholds, or off. Payer only. Enabling settles right away, so a balance\nalready under the minimum reloads immediately.",+ "summary": "Turn automatic credit reloads on with the given\nthresholds, or off. Payer only. Enabling settles right away, so a balance\nalready under the minimum reloads immediately.","operationId": "update_ai_billing_auto_reload","requestBody": {"content": {@@ -157,7 +157,7 @@"/ai-billing/overage": {"patch": {"tags": ["ai_billing"],- "summary": "Turn overage billing on or off and set the per-period cap. Payer only.",+ "summary": "Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.","operationId": "update_ai_billing_overage","requestBody": {"content": {@@ -4886,7 +4886,7 @@"properties": {"active": {"type": "boolean",- "description": "Whether reloads will fire: overage is on and reloads are not suspended."+ "description": "Whether reloads will fire: the payer opted in and reloads are not suspended."},"minimum_balance_cents": {"type": "integer",@@ -6814,7 +6814,7 @@"properties": {"enabled": {"type": "boolean",- "description": "Reload credits automatically, billing usage past allowance and\ncredits to the payer's card. Turning this off also turns off overage."+ "description": "Purchase prepaid credits automatically using the payer's card."},"minimumBalanceCents": {"type": "integer",@@ -6824,7 +6824,7 @@"monthlySpendLimitCents": {"type": ["integer", "null"],"format": "int64",- "description": "Most to reload per calendar month, cents. Omit or `null` for no limit.\nAlso serves as the per-period overage cap, so it must be at least the\ncatalog's `overage_limit_min_cents`; larger values are capped at\n`overage_limit_max_cents`."+ "description": "Most to reload per calendar month, cents. Omit or `null` for no limit.\nMust be at least the catalog's `overage_limit_min_cents` (legacy name)."},"targetBalanceCents": {"type": "integer",@@ -6875,7 +6875,7 @@"properties": {"auto_reload": {"$ref": "#/components/schemas/AutoReloadSnapshot",- "description": "Automatic credit reload settings. `active` means overage is on and\nreloads are not suspended."+ "description": "Automatic credit reload settings. `active` means the payer opted in and\nreloads are not suspended."},"blocked_reason": {"oneOf": [@@ -6914,7 +6914,7 @@},"overage_enabled": {"type": "boolean",- "description": "Whether overage billing is on."+ "description": "Legacy API name for the automatic reload opt-in. Never authorizes direct charges."},"overage_limit_cents": {"type": "integer",diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rsindex bc76a22357..22575deecc 100644--- a/crates/ai_billing/src/domain/ledger.rs+++ b/crates/ai_billing/src/domain/ledger.rs@@ -3,14 +3,14 @@//!//! For a payer and period, each seat first consumes only its own included//! allowance, both measured in cost cents. The remaining usage is chargeable to-//! the payer's shared credits and overage at the markup, in customer cents:+//! the payer's shared prepaid credits at the markup, in customer cents://!//! ```text//! chargeable_cost = sum(max(0, seat_used_cost - seat_included_cost))//! chargeable = extra_customer_cents(chargeable_cost)//! covered = credits_consumed + overage_charged//! uncovered = max(0, chargeable - covered)-//! headroom = (covered - chargeable) + credit_balance + overage_room+//! headroom = (covered - chargeable) + credit_balance//! remaining = seat_remaining_cost + cost_cents_covered_by(headroom)//! effective = credit_balance - uncovered//! reload = min(target - effective, monthly_limit - reloaded_this_month)@@ -19,16 +19,17 @@//!//! The markup is applied to the period's cumulative chargeable cost, never to//! an increment, so settling in several chunks books exactly the same money as-//! settling once. Settlement moves `uncovered` into `credits_consumed` (from-//! the balance) and then into `overage_charged` (when overage is on, within the-//! cap, and the chunk is worth charging). Between settlements `uncovered` is-//! simply usage that has not been booked yet; the gate accounts for it through-//! `headroom`.+//! settling once. Settlement moves `uncovered` into `credits_consumed` from+//! the balance. Historical charges retain their recorded coverage. The legacy+//! planner can describe direct-charge arithmetic, but the service always+//! disables that policy and the gateway rejects direct usage invoices. Between+//! settlements the gate accounts for unbooked usage through `headroom`.//!//! When automatic reloads are on, the current period is checked before//! settlement: `effective` is what the balance will be once this settlement//! consumes credits, and a reload tops it back up to `target` (within the-//! calendar-month limit) so credits, not overage, pay for the usage.+//! calendar-month limit). Unfunded usage remains uncovered; it cannot trigger+//! a direct charge.//!//! Free users have no credits or overage: their `remaining` is only the//! unused part of the free allowance, and nothing is ever settled for them.@@ -170,11 +171,6 @@ pub fn build_snapshot(let included_cents = entitlement.included_ai_cents(pricing);let shared_covered = ledger.credits_consumed_cents + ledger.overage_charged_cents;let uncovered_cents = (shared_chargeable_customer_cents - shared_covered).max(0);- let overage_room = if settings.overage_active() {- (settings.overage_limit_cents - ledger.overage_charged_cents).max(0)- } else {- 0- };let seat_remaining = (included_cents - used_cost_cents).max(0);let remaining_cents = if entitlement.unlimited {i64::MAX@@ -183,9 +179,8 @@ pub fn build_snapshot(seat_remaining} else {let shared_headroom = ((shared_covered - shared_chargeable_customer_cents)- + credit_balance_cents.max(0)- + overage_room)- .max(0);+ + credit_balance_cents.max(0))+ .max(0);seat_remaining.saturating_add(pricing.cost_cents_covered_by(shared_headroom))};@@ -227,17 +222,15 @@ pub fn build_snapshot(////// Enterprise users are never metered. Free users are allowed until their/// monthly cap is used up, after which only an upgrade helps. Everyone else-/// needs headroom from their allowance, credits, or overage.+/// needs headroom from their allowance or prepaid credits.pub fn decide(snapshot: &UsageSnapshot) -> AllowanceDecision {if snapshot.unlimited || snapshot.remaining_cents > 0 {return AllowanceDecision::Allow;}let reason = if snapshot.tier == PlanTier::Free {DenyReason::FreeAllowanceExhausted- } else if snapshot.overage_suspended {+ } else if snapshot.auto_reload.suspended {DenyReason::OveragePaymentFailed- } else if snapshot.overage_enabled && snapshot.overage_limit_cents > 0 {- DenyReason::OverageLimitReached} else {DenyReason::AllowanceExhausted};diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rsindex 4703850332..80aab755d9 100644--- a/crates/ai_billing/src/domain/ledger/test.rs+++ b/crates/ai_billing/src/domain/ledger/test.rs@@ -352,7 +352,7 @@ fn gate_counts_unsettled_usage_against_credits() {}#[test]-fn gate_uses_overage_room_and_reports_the_cap() {+fn gate_never_counts_legacy_overage_room_as_funding() {let settings = BillingSettings {overage_enabled: true,overage_limit_cents: 2_000,@@ -365,10 +365,13 @@ fn gate_uses_overage_room_and_reports_the_cap() {PeriodLedger::default(),0,);- // 1_500 cost over is 1_575 owed against 2_000 of room: 425 left pays for 404 cost cents.+ // The historical cap cannot fund any of the 1_575 uncovered cents.assert_eq!(s.uncovered_cents, 1_575);- assert_eq!(s.remaining_cents, 404);- assert_eq!(decide(&s), AllowanceDecision::Allow);+ assert_eq!(s.remaining_cents, 0);+ assert_eq!(+ decide(&s),+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted)+ );let s = snapshot_for(PlanTier::Premium,@@ -383,7 +386,7 @@ fn gate_uses_overage_room_and_reports_the_cap() {assert_eq!(s.remaining_cents, 0);assert_eq!(decide(&s),- AllowanceDecision::Deny(DenyReason::OverageLimitReached)+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted));}@@ -403,11 +406,11 @@ fn a_single_cent_of_headroom_does_not_pay_for_marked_up_usage() {}#[test]-fn gate_reports_failed_payment_when_suspended() {+fn gate_reports_failed_reload_when_suspended() {let settings = BillingSettings {overage_enabled: true,overage_limit_cents: 2_000,- overage_suspended_at: Some(Utc::now()),+ auto_reload_suspended_at: Some(Utc::now()),..Default::default()};let s = snapshot_for(diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex f0882ae061..abe4ee7deb 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -12,7 +12,7 @@ use thiserror::Error;use utoipa::ToSchema;/// Whether usage past a payer's allowance is settled: prepaid credits consumed-/// and overage collected through Stripe. Hosts load it from+/// and automatic credit reloads collected through Stripe. Hosts load it from/// `ENABLE_AI_USAGE_BILLING` at startup. It is independent of quota admission/// ([`AiUsageEnforcement`](ai_usage::AiUsageEnforcement)) and of the deployment/// environment.@@ -21,7 +21,7 @@ pub enum AiUsageBilling {/// Never consume credits, reserve overage, or collect payment.#[default]Disabled,- /// Settle uncovered usage from credits, then collect overage.+ /// Settle uncovered usage from credits, with optional automatic reloads.Enabled,}@@ -38,7 +38,7 @@ impl AiUsageBilling {#[serde(rename_all = "snake_case")]pub enum UsagePolicy {/// Aggregate per-period settlement in [`super::ledger`]: the at-cost- /// allowance, then credits and overage at the markup.+ /// allowance, then prepaid credits at the markup.Legacy,/// Per-attempt exact-money policy in [`super::policy`]: the same allowance/// at public price, then public usage at the same markup.@@ -423,8 +423,7 @@ impl Entitlement {/// When and how far a payer's credit balance is automatically reloaded.///-/// Reloads piggyback on the overage opt-in: they only run while-/// [`BillingSettings::overage_active`] holds.+/// The legacy `overage_enabled` storage field now controls only automatic reloads.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct AutoReloadThresholds {/// Reload once the effective balance drops below this, in customer cents.@@ -465,9 +464,7 @@ impl AutoReloadThresholds {"target balance exceeds the largest offered reload",));}- // The monthly limit doubles as the per-period overage cap, which is- // clamped into the offered range: a smaller limit would be raised to- // the cap minimum and the payer billed more than they set.+ // Keep the offered minimum monthly reload budget.if self.monthly_limit_cents.is_some_and(|limit| limit < OVERAGE_LIMIT_MIN_CENTS)@@ -483,7 +480,7 @@ impl AutoReloadThresholds {/// The payer's overage settings, Stripe period anchor, and open-seat generation.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct BillingSettings {- /// Whether usage past allowance and credits is billed as overage.+ /// Legacy storage name for the automatic reload opt-in. Never authorizes direct charges.pub overage_enabled: bool,/// Per-period cap on overage, in customer cents.pub overage_limit_cents: i64,@@ -500,15 +497,15 @@ pub struct BillingSettings {}impl BillingSettings {- /// Whether overage can currently be charged.+ /// Direct usage charges are permanently disabled, regardless of stored legacy settings.pub fn overage_active(&self) -> bool {- self.overage_enabled && self.overage_suspended_at.is_none() && self.overage_limit_cents > 0+ false}- /// Whether credits are automatically reloaded: overage is on and no+ /// Whether credits are automatically reloaded: the payer opted in and no/// reload has failed since the payer last re-enabled it.pub fn auto_reload_active(&self) -> bool {- self.overage_active() && self.auto_reload_suspended_at.is_none()+ self.overage_enabled && self.auto_reload_suspended_at.is_none()}}@@ -595,7 +592,7 @@ impl DenyReason {pub fn message(self) -> &'static str {match self {DenyReason::AllowanceExhausted => {- "You've used this period's included AI. Add credits or turn on usage billing to keep going."+ "You've used this period's included AI. Add credits or turn on automatic reload to keep going."}DenyReason::FreeAllowanceExhausted => {"You've used this month's free AI. Upgrade to a paid plan to keep going."@@ -604,7 +601,7 @@ impl DenyReason {"You've reached your AI spending limit for this period. Raise the limit or add credits to keep going."}DenyReason::OveragePaymentFailed => {- "Your last AI usage charge didn't go through. Update your payment method and re-enable usage billing."+ "Your last automatic credit reload didn't go through. Update your payment method and re-enable automatic reload."}}}@@ -631,7 +628,7 @@ pub struct AutoReloadSnapshot {pub monthly_spend_limit_cents: Option<i64>,/// Whether reloads are paused after a failed reload charge.pub suspended: bool,- /// Whether reloads will fire: overage is on and reloads are not suspended.+ /// Whether reloads will fire: the payer opted in and reloads are not suspended.pub active: bool,}@@ -662,7 +659,7 @@ pub struct UsageSnapshot {pub credits_consumed_cents: i64,/// Shared prepaid credit balance, in customer cents.pub credit_balance_cents: i64,- /// Whether overage billing is on.+ /// Legacy API name for the automatic reload opt-in. Never authorizes direct charges.pub overage_enabled: bool,/// Per-period overage cap, in customer cents.pub overage_limit_cents: i64,@@ -670,7 +667,7 @@ pub struct UsageSnapshot {pub overage_charged_cents: i64,/// Whether overage is paused after a failed charge.pub overage_suspended: bool,- /// Automatic credit reload settings. `active` means overage is on and+ /// Automatic credit reload settings. `active` means the payer opted in and/// reloads are not suspended.pub auto_reload: AutoReloadSnapshot,/// Team-wide usage beyond per-seat allowances, at the overage markup, that@@ -701,6 +698,9 @@ pub enum BillingError {/// Outside the allowed overage cap range.#[error("overage limit must be between ${} and ${}", OVERAGE_LIMIT_MIN_CENTS / 100, OVERAGE_LIMIT_MAX_CENTS / 100)]InvalidOverageLimit,+ /// Direct usage billing has been retired; only prepaid credits fund extra usage.+ #[error("direct usage billing is no longer available; use automatic credit reload")]+ DirectUsageBillingDisabled,/// Automatic reload thresholds that could never charge or exceed the/// offered range ([`AutoReloadThresholds::validate`]).#[error("invalid automatic reload settings: {0}")]diff --git a/crates/ai_billing/src/domain/policy.rs b/crates/ai_billing/src/domain/policy.rsindex 2465df7d9a..9ff9bc5a9a 100644--- a/crates/ai_billing/src/domain/policy.rs+++ b/crates/ai_billing/src/domain/policy.rs@@ -162,20 +162,9 @@ pub enum PostpaidAuthorization {}impl PostpaidAuthorization {- /// Capture existing enable/cap/suspension semantics without changing settings.- pub fn from_settings(settings: &BillingSettings) -> Result<Self, PolicyError> {- if !settings.overage_enabled {- return Ok(Self::Disabled);- }- if settings.overage_suspended_at.is_some() {- return Ok(Self::Suspended);- }- if settings.overage_limit_cents <= 0 {- return Ok(Self::Disabled);- }- Ok(Self::Enabled {- limit: CustomerMoney::from_cents(settings.overage_limit_cents as u64)?,- })+ /// New admissions never authorize direct charges, including for legacy opt-ins.+ pub fn from_settings(_settings: &BillingSettings) -> Result<Self, PolicyError> {+ Ok(Self::Disabled)}}diff --git a/crates/ai_billing/src/domain/policy/test.rs b/crates/ai_billing/src/domain/policy/test.rsindex 4513189186..ce5f91b6e9 100644--- a/crates/ai_billing/src/domain/policy/test.rs+++ b/crates/ai_billing/src/domain/policy/test.rs@@ -345,7 +345,7 @@ fn new_credits_cannot_reclassify_captured_or_settled_sources() {}#[test]-fn captured_suspension_and_zero_cap_deny_only_new_postpaid() {+fn legacy_opt_in_never_authorizes_new_postpaid_but_prepaid_still_works() {let mut settings = BillingSettings {overage_enabled: true,overage_limit_cents: 500,@@ -353,12 +353,12 @@ fn captured_suspension_and_zero_cap_deny_only_new_postpaid() {};assert_eq!(PostpaidAuthorization::from_settings(&settings).unwrap(),- PostpaidAuthorization::Enabled { limit: money(500) }+ PostpaidAuthorization::Disabled);settings.overage_suspended_at = Some(Utc::now());let mut auth = authorization(true);auth.postpaid = PostpaidAuthorization::from_settings(&settings).unwrap();- assert_eq!(auth.postpaid, PostpaidAuthorization::Suspended);+ assert_eq!(auth.postpaid, PostpaidAuthorization::Disabled);assert!(matches!(reserve(AiPricing::testing(),diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex fcf2a3fada..ad4143bbe4 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -242,7 +242,9 @@ pub trait BillingRepo: Send + Sync + 'static {/// overage policy is read inside the lock, with `charge_threshold_cents` and/// `period_ended` taken from `policy`.///- /// A charge that was reserved earlier but never collected is handed back+ /// When `policy.overage_active` is false, neither new nor historical charges+ /// are returned. The service always selects this credit-only policy.+ /// A legacy charge that was reserved earlier but never collected is handed back/// before anything new is reserved, so retries reuse its id (and so its/// Stripe idempotency keys and invoice) rather than billing the same/// usage twice:@@ -289,7 +291,8 @@ pub trait BillingRepo: Send + Sync + 'static {payer: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<Option<OverageChargeStatus>>> + Send;- /// Set overage on/off with the cap, and optionally the reload thresholds.+ /// Set the stored reload opt-in and optionally its thresholds. The service+ /// supplies zero for the retired direct-charge cap./// `None` thresholds keep the stored ones. Clears both the overage and the/// reload suspension.fn update_auto_reload(@@ -417,33 +420,26 @@ pub trait PaymentGateway: Send + Sync + 'static {request: CreditCheckoutRequest,) -> impl Future<Output = Result<String>> + Send;- /// Open a finalized invoice for exactly this overage chunk (and nothing- /// else pending on the customer). [`OverageChargeRequest::scope`] selects- /// the active or trialing subscription. Another scope is ignored. No- /// matching subscription fails unless an idempotent retry finds an invoice- /// that already stores its payment method. Distinct effective methods in- /// the selected scope fail with- /// [`BillingError::Payment`](super::BillingError::Payment).- /// Returns the invoice id. Idempotent on `charge_id`.+ /// Retired direct usage billing capability. Adapters must reject opening+ /// these invoices without creating payment-provider objects.fn open_overage_invoice(&self,request: OverageChargeRequest,) -> impl Future<Output = Result<String>> + Send;- /// Open a finalized invoice for exactly this credit reload, following the- /// same routing and payment-method rules as [`open_overage_invoice`]- /// (selected by [`CreditReloadRequest::scope`]). Returns the invoice id.- /// Idempotent on `reload_id`.- ///- /// [`open_overage_invoice`]: PaymentGateway::open_overage_invoice+ /// Open a finalized invoice for exactly this credit reload, excluding other+ /// pending items. [`CreditReloadRequest::scope`] selects the active or trialing+ /// subscription. Ambiguous routing fails. Missing subscription routing fails+ /// unless a retry finds an invoice with a stored payment method. Returns the invoice id;+ /// idempotent on `reload_id`.fn open_credit_reload_invoice(&self,request: CreditReloadRequest,) -> impl Future<Output = Result<String>> + Send;- /// Attempt to collect now an open one-off invoice this crate opened (an- /// overage chunk or a credit reload). `charge_id` is the reserved charge- /// or reload id and only keeps the idempotency key unique. `scope` is the+ /// Collect an automatic credit reload invoice. Historical direct usage+ /// invoices must be rejected. `charge_id` is the reload id and only keeps+ /// the idempotency key unique. `scope` is the/// payer's current subscription scope. A scope stamped on the invoice/// overrides it. Invoices without that stamp use `scope`. Distinct/// effective methods in the chosen scope fail with@@ -518,14 +514,14 @@ pub trait BillingService: Send + Sync + 'static {) -> impl Future<Output = Result<UsageSnapshot>> + Send;/// Book each seat's usage beyond its own allowance for the payer of `user`- /// (previous and current period) from shared credits and then shared- /// overage, collecting overage via the payment gateway. The previous+ /// (previous and current period) from shared prepaid credits. Only the+ /// current period may trigger an automatic credit reload. The previous/// period is settled against the per-seat allowances frozen while it was/// open, not the live plan or seat list.fn settle(&self, user: &MacroUserIdStr<'_>) -> impl Future<Output = Result<()>> + Send;- /// Turn overage on/off with a per-period cap. Payer only. Re-enabling- /// retries collection.+ /// Retired direct usage opt-in. Enabling is rejected; disabling remains+ /// supported for older clients. Payer only.fn update_overage(&self,user: &MacroUserIdStr<'_>,@@ -533,9 +529,9 @@ pub trait BillingService: Send + Sync + 'static {limit_cents: i64,) -> impl Future<Output = Result<UsageSnapshot>> + Send;- /// Turn automatic credit reloads, and with them overage, on with+ /// Turn automatic credit reloads on with/// `thresholds` or off. Payer only. Enabling validates the thresholds,- /// derives the overage cap from the monthly spend limit, clears both+ /// clears the retired direct-charge cap and both/// suspensions, and settles right away, so a balance already under the/// minimum reloads immediately. Disabling keeps the stored thresholds.fn update_auto_reload(diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex 1e5bd05113..9d979a7ff2 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -8,14 +8,13 @@ use super::ledger::{SettlementPolicy, build_snapshot, decide};use super::models::{AiUsageBilling, AllowanceDecision, AllowanceStore, AutoReloadThresholds, BillingError,BillingPeriod, BillingSettings, CREDIT_PACKS_CENTS, CreditReloadStatus, Entitlement,- OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,- OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, Result, SeatAllowance,- SeatUsage, SubscriptionScope, UsageSnapshot,+ OVERAGE_CHARGE_THRESHOLD_CENTS, OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger,+ Result, SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,};use super::period::{PeriodSync, SubscriptionPeriod};use super::ports::{BillingRepo, BillingService, CreditCheckoutRequest, CreditReloadRequest, EntitlementSource,- OverageChargeRequest, PaymentGateway, PendingCharge, PendingReload, UsageReader,+ PaymentGateway, PendingReload, UsageReader,};use super::pricing::AiPricing;use ai_usage::AiUsageEnforcement;@@ -79,7 +78,7 @@ impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {self}- /// Configure settlement (credit consumption and overage collection) from+ /// Configure settlement (credit consumption and automatic reloads) from/// the host's `ENABLE_AI_USAGE_BILLING` policy, independently of admission.pub fn with_billing(mut self, billing: AiUsageBilling) -> Self {self.billing = billing;@@ -99,7 +98,7 @@ impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {enum ReloadCheck {/// A closed period is settled from what is on hand.Skip,- /// The open period reloads credits before any overage is reserved.+ /// The open period reloads credits before consuming them.Current,}@@ -437,7 +436,7 @@ where/// Settle one period for a payer: top up credits when automatic reload/// asks for it, book uncovered usage from credits, then reserve and- /// collect an overage chunk.+ /// consume prepaid credits. Direct usage charges are never collected.#[tracing::instrument(skip(self, entitlement), fields(payer = %entitlement.payer), err)]async fn settle_period(&self,@@ -462,7 +461,7 @@ wherelet chargeable_customer_cents = self.pricing.extra_customer_cents(chargeable_cost);if reload == ReloadCheck::Current {// Before credits are consumed, so the top-up covers this usage- // instead of an overage chunk.+ // from prepaid credits.self.reload_credits(entitlement, period.start, chargeable_customer_cents, now).await?;}@@ -477,9 +476,8 @@ whereperiod.start,chargeable_customer_cents,SettlementPolicy {- // The repo reads the live overage settings under its lock;- // these two are the caller's contribution.- overage_active: true,+ // Disable both new charges and retries of historical charges.+ overage_active: false,overage_limit_cents: 0,charge_threshold_cents: OVERAGE_CHARGE_THRESHOLD_CENTS,period_ended: period.has_ended(now),@@ -494,131 +492,14 @@ where);}- if let Some(charge) = outcome.pending_charge {- self.collect(entitlement, period, charge).await?;- }Ok(())}- /// Collect a reserved overage charge: open its invoice (or pick up the- /// one an earlier attempt opened) and try to pay it. A provider failure- /// marks the charge failed and suspends overage until the payer re-enables- /// it. A recorded invoice continues covering usage because Stripe may- /// still collect it; re-enabling retries that same invoice.- async fn collect(- &self,- entitlement: &Entitlement,- period: BillingPeriod,- charge: PendingCharge,- ) -> Result<()> {- let payer = &entitlement.payer;- let scope = SubscriptionScope::from(&entitlement.scope);- let customer_id = match self.entitlements.stripe_customer_id(payer).await {- Ok(Some(customer_id)) => customer_id,- Ok(None) => {- tracing::warn!("overage charge reserved but payer has no stripe customer");- self.fail_charge(payer, charge.id).await?;- return Err(BillingError::NoStripeCustomer);- }- Err(e) => {- // Left pending, the charge would cover usage that is never- // invoiced. Fail it so the next settlement retries it.- self.fail_charge(payer, charge.id).await?;- return Err(e);- }- };-- let invoice_id = match charge.stripe_invoice_id.clone() {- Some(invoice_id) => invoice_id,- None => {- let description = format!(- "Macro AI usage beyond plan, {} to {}",- period.start.format("%b %-d"),- period.end.format("%b %-d, %Y")- );- match self- .payments- .open_overage_invoice(OverageChargeRequest {- customer_id,- charge_id: charge.id,- amount_cents: charge.amount_cents,- description,- scope,- })- .await- {- Ok(invoice_id) => invoice_id,- Err(e) => {- tracing::error!(- error = ?e,- cents = charge.amount_cents,- "ai overage invoice could not be opened"- );- self.fail_charge(payer, charge.id).await?;- return Err(e);- }- }- }- };- // Record the invoice before collecting: if this process dies here the- // next settlement pays this invoice instead of opening another.- self.repo- .finish_overage_charge(charge.id, Some(&invoice_id), OverageChargeStatus::Pending)- .await?;-- match self- .payments- .pay_overage_invoice(charge.id, &invoice_id, scope)- .await- {- Ok(true) => {- self.repo- .finish_overage_charge(charge.id, Some(&invoice_id), OverageChargeStatus::Paid)- .await?;- tracing::info!(- cents = charge.amount_cents,- invoice = %invoice_id,- "collected ai overage"- );- Ok(())- }- Ok(false) => {- // Declined: the invoice stays open for Stripe's retries and- // the webhook reports the outcome either way.- tracing::info!(- cents = charge.amount_cents,- invoice = %invoice_id,- "ai overage invoice awaiting payment"- );- Ok(())- }- Err(e) => {- tracing::error!(- error = ?e,- cents = charge.amount_cents,- invoice = %invoice_id,- "ai overage charge failed"- );- self.fail_charge(payer, charge.id).await?;- Err(e)- }- }- }-- /// A charge that could not be collected: overage pauses until the payer- /// re-enables it. A recorded Stripe invoice continues covering usage.- async fn fail_charge(&self, payer: &MacroUserIdStr<'_>, charge_id: Uuid) -> Result<()> {- self.repo- .finish_overage_charge(charge_id, None, OverageChargeStatus::Failed)- .await?;- self.repo.suspend_overage(payer).await- }-/// Reserve and collect an automatic credit reload when the payer's/// balance, net of the usage this settlement is about to consume, is/// under their minimum. A card or customer problem is logged and left to- /// the webhook or the next attempt: it never blocks the overage fallback- /// or the summary read that triggered settlement.+ /// the webhook or the next attempt: it leaves unfunded usage uncovered+ /// and never blocks the summary read that triggered settlement.async fn reload_credits(&self,entitlement: &Entitlement,@@ -643,7 +524,7 @@ whereErr(e @ (BillingError::Payment(_) | BillingError::NoStripeCustomer)) => {tracing::warn!(error = ?e,- "automatic credit reload failed; overage remains the fallback"+ "automatic credit reload failed; unfunded usage remains uncovered");Ok(())}@@ -754,7 +635,7 @@ where}/// A reload that could not be collected: automatic reloads pause until- /// the payer saves their settings again. Overage itself stays as it was.+ /// the payer saves their settings again.async fn fail_reload(&self, payer: &MacroUserIdStr<'_>, reload_id: Uuid) -> Result<()> {self.repo.finish_credit_reload(reload_id, None, CreditReloadStatus::Failed)@@ -855,24 +736,16 @@ where&self,user: &MacroUserIdStr<'_>,enabled: bool,- limit_cents: i64,+ _limit_cents: i64,) -> Result<UsageSnapshot> {let entitlement = self.entitlements.entitlement(user).await?;Self::require_payer(&entitlement, user)?;- if enabled && !(OVERAGE_LIMIT_MIN_CENTS..=OVERAGE_LIMIT_MAX_CENTS).contains(&limit_cents) {- return Err(BillingError::InvalidOverageLimit);+ if enabled {+ return Err(BillingError::DirectUsageBillingDisabled);}- let limit_cents = if enabled { limit_cents } else { 0 };self.repo- .update_overage(&entitlement.payer, enabled, limit_cents)+ .update_overage(&entitlement.payer, false, 0).await?;- if enabled {- // Retry anything that was waiting on overage (or a failed charge);- // a collection failure re-suspends and is reported in the snapshot.- if let Err(e) = self.settle(user).await {- tracing::warn!(error = ?e, "settlement after enabling overage failed");- }- }self.snapshot(user).await}@@ -892,24 +765,12 @@ wherereturn self.snapshot(user).await;}thresholds.validate()?;- // The dialog has no overage cap of its own: the monthly spend limit- // doubles as the per-period cap. Validation keeps it at or above the- // cap minimum, so the clamp only ever lowers it.- let overage_limit_cents = thresholds- .monthly_limit_cents- .unwrap_or(OVERAGE_LIMIT_MAX_CENTS)- .clamp(OVERAGE_LIMIT_MIN_CENTS, OVERAGE_LIMIT_MAX_CENTS);+ // Preserve the stored reload opt-in, without a direct-charge cap.self.repo- .update_auto_reload(- &entitlement.payer,- true,- overage_limit_cents,- Some(&thresholds),- )+ .update_auto_reload(&entitlement.payer, true, 0, Some(&thresholds)).await?;- // A balance already under the minimum reloads now, and anything that- // was waiting on overage is retried; a collection failure re-suspends- // and is reported in the snapshot.+ // A balance already under the minimum reloads now; a collection failure+ // re-suspends reloads and is reported in the snapshot.if let Err(e) = self.settle(user).await {tracing::warn!(error = ?e, "settlement after enabling automatic reload failed");}diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex 7c4c19848e..5ccbb6a18e 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -1,10 +1,13 @@use super::*;use crate::domain::ledger::{ReloadState, plan_reload, plan_settlement};use crate::domain::models::{- AllowanceStore, AutoReloadThresholds, CreditReloadStatus, DenyReason, OpenPeriodStart,- PayerScope, PeriodAllowance, PeriodLedger, PlanTier, SeatGeneration,+ AllowanceStore, AutoReloadThresholds, CreditReloadStatus, DenyReason, OVERAGE_LIMIT_MIN_CENTS,+ OpenPeriodStart, PayerScope, PeriodAllowance, PeriodLedger, PlanTier, SeatGeneration,+};+use crate::domain::ports::{+ CreditReloadRequest, OverageChargeRequest, PendingCharge, PendingReload, ResolvedReload,+ SettlementOutcome,};-use crate::domain::ports::{CreditReloadRequest, PendingReload, ResolvedReload, SettlementOutcome};use chrono::TimeZone;use macro_user_id::cowlike::CowLike;use macro_uuid::Uuid;@@ -398,8 +401,10 @@ impl BillingRepo for FakeRepo {) -> Result<SettlementOutcome> {let mut s = self.state.lock().unwrap();let ledger = s.ledger(period_start);- let overage_active =- s.settings.overage_enabled && !s.suspended && s.settings.overage_limit_cents > 0;+ let overage_active = policy.overage_active+ && s.settings.overage_enabled+ && !s.suspended+ && s.settings.overage_limit_cents > 0;let plan = plan_settlement(crate::domain::ledger::SettlementState {chargeable_customer_cents,@@ -417,7 +422,8 @@ impl BillingRepo for FakeRepo {s.balance -= plan.consume_credits_cents;let owed = s.charges.iter().position(|c| {- c.period_start == period_start+ policy.overage_active+ && c.period_start == period_start&& ((c.status == OverageChargeStatus::Pending && c.invoice.is_none())|| (c.status == OverageChargeStatus::Failed&& overage_active@@ -517,10 +523,7 @@ impl BillingRepo for FakeRepo {now: DateTime<Utc>,) -> Result<Option<PendingReload>> {let mut s = self.state.lock().unwrap();- let active = s.settings.overage_enabled- && !s.suspended- && s.settings.overage_limit_cents > 0- && !s.auto_reload_suspended;+ let active = s.settings.overage_enabled && !s.auto_reload_suspended;if !active {return Ok(None);}@@ -1015,9 +1018,9 @@ async fn enabled_enforces_allowances_under_either_settlement_policy_without_sett*usage.cents.lock().unwrap() = 5_000;assert_eq!(svc.check_allowance(&payer).await.unwrap(),- AllowanceDecision::Deny(DenyReason::OverageLimitReached)+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted));- repo.state.lock().unwrap().suspended = true;+ repo.state.lock().unwrap().auto_reload_suspended = true;assert_eq!(svc.check_allowance(&payer).await.unwrap(),AllowanceDecision::Deny(DenyReason::OveragePaymentFailed)@@ -1074,7 +1077,7 @@ async fn disabled_settlement_preserves_credits_and_never_reserves_or_collects_ov1_000_000,);- svc.update_overage(&payer, true, 10_000).await.unwrap();+ repo.update_overage(&payer, true, 10_000).await.unwrap();svc.apply_credit_purchase(&payer, 2_500, "cs_paused").await.unwrap();@@ -1096,11 +1099,10 @@ async fn disabled_settlement_preserves_credits_and_never_reserves_or_collects_ov}#[tokio::test]-async fn disabled_settlement_does_not_retry_pending_or_failed_charges() {+async fn enabled_settlement_does_not_retry_pending_or_failed_direct_charges() {for status in [OverageChargeStatus::Pending, OverageChargeStatus::Failed] {for invoice in [None, Some("in_existing".to_string())] {- let (svc, repo, payments, _) =- premium_service_with(AiUsageBilling::Disabled, 1_000_000);+ let (svc, repo, payments, _) = premium_service_with(AiUsageBilling::Enabled, 1_000_000);let payer = user("[email protected]");let period = BillingPeriod::current(None, Utc::now());repo.state.lock().unwrap().charges.push(FakeCharge {@@ -1111,7 +1113,8 @@ async fn disabled_settlement_does_not_retry_pending_or_failed_charges() {invoice: invoice.clone(),});- svc.update_overage(&payer, true, 10_000).await.unwrap();+ repo.update_overage(&payer, true, 10_000).await.unwrap();+ repo.pause_reloads();svc.settle(&payer).await.unwrap();let charges = repo.charges();@@ -1239,188 +1242,37 @@ async fn credits_unblock_and_settlement_consumes_them() {}#[tokio::test]-async fn overage_is_charged_in_chunks_and_respects_the_cap() {- let (svc, repo, payments, usage) = premium_service(2_500);+async fn legacy_overage_opt_in_never_funds_or_charges_usage() {+ let (svc, repo, payments, _) = premium_service(5_000);let payer = user("[email protected]");+ repo.update_overage(&payer, true, 10_000).await.unwrap();repo.pause_reloads();-- let snap = svc.update_overage(&payer, true, 2_000).await.unwrap();- assert!(snap.overage_enabled);- // 500 cost over is 525 owed: under the $10 chunk, nothing charged yet, and- // the 1_475 of room left pays for 1_404 more cost cents.- assert_eq!(snap.overage_charged_cents, 0);- assert_eq!(snap.remaining_cents, 1_404);-- *usage.cents.lock().unwrap() = 3_200;- svc.settle(&payer).await.unwrap();- let opened = payments.opened();- assert_eq!(opened.len(), 1);- assert_eq!(opened[0].amount_cents, 1_260);- assert_eq!(opened[0].customer_id, "cus_123");- assert_eq!(opened[0].scope, SubscriptionScope::Personal);- let charges = repo.charges();- let charge = &charges[0];- assert_eq!(charge.status, OverageChargeStatus::Paid);- assert_eq!(- charge.invoice.as_deref(),- Some(format!("in_{}", charge.id).as_str())- );-- // Past the cap: the last 740 of room is under the charge chunk, so it- // waits for period end, and the payer is blocked with the right reason.- *usage.cents.lock().unwrap() = 5_000;+ repo.set_balance(500);svc.settle(&payer).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.overage_charged_cents, 1_260);+ assert_eq!(snap.credits_consumed_cents, 500);+ assert_eq!(snap.credit_balance_cents, 0);+ assert_eq!(snap.uncovered_cents, 2_650);assert_eq!(snap.remaining_cents, 0);- assert_eq!(snap.blocked_reason, Some(DenyReason::OverageLimitReached));-}--#[tokio::test]-async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated() {- let (svc, repo, payments, _) = premium_service(3_500);- let payer = user("[email protected]");- repo.pause_reloads();- payments.set_pay(PayOutcome::Error);-- // Enabling settles; the collection failure is swallowed into the snapshot.- let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();- assert!(snap.overage_suspended);assert_eq!(snap.blocked_reason, Some(DenyReason::OveragePaymentFailed));- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, OverageChargeStatus::Failed);- // The invoice was recorded before the payment attempt.- let invoice = charges[0].invoice.clone().expect("invoice recorded");- assert_eq!(- svc.check_allowance(&payer).await.unwrap(),- AllowanceDecision::Deny(DenyReason::OveragePaymentFailed)- );-- // Fixing the card and re-enabling retries the same charge: the existing- // invoice is paid, no second invoice is opened, no second row reserved.- payments.set_pay(PayOutcome::Paid);- let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();- assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 1_575);- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, OverageChargeStatus::Paid);- assert_eq!(payments.opened().len(), 1);- let paid = payments.payments();- assert_eq!(paid.len(), 2);- assert!(- paid.iter()- .all(|(id, inv)| *id == charges[0].id && *inv == invoice)- );-}--#[tokio::test]-async fn opening_the_invoice_failing_marks_the_charge_failed() {- let (svc, repo, payments, _) = premium_service(3_500);- let payer = user("[email protected]");- repo.pause_reloads();- *payments.fail_open.lock().unwrap() = true;-- let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();- assert!(snap.overage_suspended);- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, OverageChargeStatus::Failed);- assert!(charges[0].invoice.is_none());- assert!(payments.payments().is_empty());-- // Once Stripe is back the retry opens the invoice for the same charge.- *payments.fail_open.lock().unwrap() = false;- svc.update_overage(&payer, true, 5_000).await.unwrap();- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, OverageChargeStatus::Paid);- assert_eq!(payments.opened()[0].charge_id, charges[0].id);-}--#[tokio::test]-async fn a_failed_uninvoiced_charge_whose_usage_credits_covered_is_not_retried() {- let (svc, repo, payments, _) = premium_service(3_800);- let payer = user("[email protected]");- repo.pause_reloads();- *payments.fail_open.lock().unwrap() = true;- svc.update_overage(&payer, true, 10_000).await.unwrap();- assert_eq!(repo.charges()[0].status, OverageChargeStatus::Failed);- assert!(repo.charges()[0].invoice.is_none());-- // Credits arrive and cover the 1_890 (1_800 cost, marked up) that was never invoiced.- *payments.fail_open.lock().unwrap() = false;- svc.apply_credit_purchase(&payer, 2_500, "cs_1")- .await- .unwrap();- let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.credits_consumed_cents, 1_890);- assert_eq!(snap.uncovered_cents, 0);-- // Re-enabling overage must not collect that stale charge.- let snap = svc.update_overage(&payer, true, 10_000).await.unwrap();- assert_eq!(snap.overage_charged_cents, 0);- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, OverageChargeStatus::Failed);+ assert!(repo.charges().is_empty());assert!(payments.opened().is_empty());assert!(payments.payments().is_empty());}#[tokio::test]-async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {+async fn direct_usage_billing_cannot_be_enabled() {let (svc, repo, payments, _) = premium_service(5_000);let payer = user("[email protected]");- repo.pause_reloads();- payments.set_pay(PayOutcome::Error);-- svc.update_overage(&payer, true, 10_000).await.unwrap();- let first = repo.charges().into_iter().next().unwrap();- assert_eq!(first.amount_cents, 3_150);- assert_eq!(first.status, OverageChargeStatus::Failed);- assert!(first.invoice.is_some());-- payments.set_pay(PayOutcome::Declined);- svc.apply_credit_purchase(&payer, 1_000, "cs_shrink")- .await- .unwrap();- let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.credits_consumed_cents, 0);- assert_eq!(snap.credit_balance_cents, 1_000);- assert_eq!(snap.overage_charged_cents, 3_150);-- svc.update_overage(&payer, true, 10_000).await.unwrap();- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].id, first.id);- assert_eq!(charges[0].status, OverageChargeStatus::Pending);- assert_eq!(charges[0].amount_cents, 3_150);- assert_eq!(charges[0].invoice, first.invoice);- assert_eq!(payments.opened().len(), 1);- assert_eq!(payments.payments().len(), 2);-}--#[tokio::test]-async fn a_declined_card_leaves_the_invoice_open_for_the_webhook() {- let (svc, repo, payments, _) = premium_service(3_500);- let payer = user("[email protected]");- repo.pause_reloads();- payments.set_pay(PayOutcome::Declined);-- let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();- // Not suspended yet: Stripe retries, the webhook decides.- assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 1_575);- let charges = repo.charges();- assert_eq!(charges[0].status, OverageChargeStatus::Pending);- let invoice = charges[0].invoice.clone().unwrap();-- svc.mark_overage_invoice(&invoice, false).await.unwrap();- let snap = svc.snapshot(&payer).await.unwrap();- assert!(snap.overage_suspended);- // Stripe may still retry the open invoice, so it remains coverage.- assert_eq!(snap.overage_charged_cents, 1_575);+ for limit in [100, 5_000, 500_000] {+ assert!(matches!(+ svc.update_overage(&payer, true, limit).await,+ Err(BillingError::DirectUsageBillingDisabled)+ ));+ }+ assert!(!repo.settings(&payer).await.unwrap().overage_enabled);+ assert!(repo.charges().is_empty());+ assert!(payments.payments().is_empty());}#[tokio::test]@@ -1470,7 +1322,7 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {));assert!(matches!(svc.update_overage(&owner, true, 100).await,- Err(BillingError::InvalidOverageLimit)+ Err(BillingError::DirectUsageBillingDisabled)));let url = svc.create_credit_checkout(&owner, 2_500, "s".into(), "c".into())@@ -1547,12 +1399,16 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {#[tokio::test]async fn overage_invoice_webhooks_update_suspension() {- let (svc, repo, payments, _) = premium_service(3_500);+ let (svc, repo, _, _) = premium_service(3_500);let payer = user("[email protected]");- repo.pause_reloads();- payments.set_pay(PayOutcome::Declined);- svc.update_overage(&payer, true, 5_000).await.unwrap();- let invoice = repo.charges()[0].invoice.clone().unwrap();+ let invoice = "in_legacy".to_string();+ repo.state.lock().unwrap().charges.push(FakeCharge {+ id: macro_uuid::generate_uuid_v7(),+ period_start: BillingPeriod::current(None, Utc::now()).start,+ amount_cents: 1_575,+ status: OverageChargeStatus::Pending,+ invoice: Some(invoice.clone()),+ });svc.mark_overage_invoice(&invoice, false).await.unwrap();assert!(svc.snapshot(&payer).await.unwrap().overage_suspended);@@ -1577,21 +1433,18 @@ async fn overage_invoice_webhooks_update_suspension() {#[tokio::test]async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {- let (svc, repo, payments, usage) = premium_service(4_000);+ let (svc, repo, _, _) = premium_service(5_500);let payer = user("[email protected]");- repo.pause_reloads();- payments.set_pay(PayOutcome::Declined);- // Charge A: 2_000 cost over, 2_100 owed, declined, awaiting Stripe.- svc.update_overage(&payer, true, 10_000).await.unwrap();- // Charge B: another 1_500 cost, 1_575 owed, also declined.- *usage.cents.lock().unwrap() = 5_500;- svc.settle(&payer).await.unwrap();- let charges = repo.charges();- assert_eq!(charges.len(), 2);- let (a, b) = (- charges[0].invoice.clone().unwrap(),- charges[1].invoice.clone().unwrap(),- );+ let (a, b) = ("in_legacy_a".to_string(), "in_legacy_b".to_string());+ for (invoice, amount) in [(&a, 2_100), (&b, 1_575)] {+ repo.state.lock().unwrap().charges.push(FakeCharge {+ id: macro_uuid::generate_uuid_v7(),+ period_start: BillingPeriod::current(None, Utc::now()).start,+ amount_cents: amount,+ status: OverageChargeStatus::Pending,+ invoice: Some(invoice.clone()),+ });+ }// B fails: suspended.svc.mark_overage_invoice(&b, false).await.unwrap();@@ -1609,17 +1462,9 @@ async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {// The mirror image: a late failure for an older invoice after the newest// charge went through does not re-suspend.- let (svc, repo, payments, usage) = premium_service(4_000);- repo.pause_reloads();- payments.set_pay(PayOutcome::Declined);- svc.update_overage(&payer, true, 10_000).await.unwrap();- *usage.cents.lock().unwrap() = 5_500;- svc.settle(&payer).await.unwrap();- let charges = repo.charges();- let (a, b) = (- charges[0].invoice.clone().unwrap(),- charges[1].invoice.clone().unwrap(),- );+ for charge in &mut repo.state.lock().unwrap().charges {+ charge.status = OverageChargeStatus::Pending;+ }svc.mark_overage_invoice(&b, true).await.unwrap();svc.mark_overage_invoice(&a, false).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();@@ -1736,7 +1581,7 @@ async fn reload_amount_covers_the_usage_about_to_be_consumed() {#[tokio::test]async fn monthly_spend_limit_caps_reloads() {- let (svc, repo, payments, _) = premium_service(0);+ let (svc, repo, payments, usage) = premium_service(0);let payer = user("[email protected]");repo.set_balance(500);@@ -1750,15 +1595,22 @@ async fn monthly_spend_limit_caps_reloads() {// The month's limit is spent: draining the balance reloads nothing more.repo.set_balance(500);+ *usage.cents.lock().unwrap() = 10_000;svc.settle(&payer).await.unwrap();assert_eq!(repo.reloads().len(), 1);assert_eq!(payments.opened_reloads().len(), 1);- assert_eq!(repo.state.lock().unwrap().balance, 500);+ assert_eq!(repo.state.lock().unwrap().balance, 0);+ assert!(repo.charges().is_empty());+ assert!(payments.opened().is_empty());+ assert_eq!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Deny(DenyReason::AllowanceExhausted)+ );}#[tokio::test]async fn a_declined_reload_stays_pending_for_the_webhook() {- let (svc, repo, payments, _) = premium_service(0);+ let (svc, repo, payments, _) = premium_service(3_500);let payer = user("[email protected]");repo.set_balance(500);payments.set_pay(PayOutcome::Declined);@@ -1770,7 +1622,11 @@ async fn a_declined_reload_stays_pending_for_the_webhook() {// Not suspended: Stripe retries, the webhook decides.assert!(snap.auto_reload.active);assert!(!snap.auto_reload.suspended);- assert_eq!(snap.credit_balance_cents, 500);+ assert_eq!(snap.credit_balance_cents, 0);+ assert_eq!(snap.uncovered_cents, 1_075);+ assert_eq!(snap.remaining_cents, 0);+ assert!(repo.charges().is_empty());+ assert!(payments.opened().is_empty());let reloads = repo.reloads();assert_eq!(reloads.len(), 1);assert_eq!(reloads[0].status, CreditReloadStatus::Pending);@@ -1783,51 +1639,31 @@ async fn a_declined_reload_stays_pending_for_the_webhook() {}#[tokio::test]-async fn a_failed_reload_pauses_reloads_and_falls_back_to_overage() {- let (svc, repo, payments, _) = premium_service(3_500);- let payer = user("[email protected]");- payments.set_pay(PayOutcome::Error);-- // The reload fails first; the 1_575 owed still goes to an overage chunk,- // which fails on the same card. Neither failure fails the call.- let snap = svc- .update_auto_reload(&payer, true, AutoReloadThresholds::default())- .await- .unwrap();- let reloads = repo.reloads();- assert_eq!(reloads.len(), 1);- assert_eq!(reloads[0].status, CreditReloadStatus::Failed);- // The invoice stays on the row because Stripe may still collect it.- assert!(reloads[0].invoice.is_some());- assert!(snap.auto_reload.suspended);- assert!(!snap.auto_reload.active);- assert!(snap.overage_suspended);- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].amount_cents, 1_575);- assert_eq!(charges[0].status, OverageChargeStatus::Failed);- assert_eq!(payments.payments().len(), 2);-- // Re-enabling overage alone retries the chunk but leaves reloads paused.- payments.set_pay(PayOutcome::Paid);- let snap = svc.update_overage(&payer, true, 10_000).await.unwrap();- assert_eq!(repo.charges()[0].status, OverageChargeStatus::Paid);- assert_eq!(snap.overage_charged_cents, 1_575);- assert!(snap.auto_reload.suspended);- assert_eq!(repo.reloads().len(), 1);- assert_eq!(payments.opened_reloads().len(), 1);-- // Saving the reload settings clears the pause and reloads right away.- let snap = svc- .update_auto_reload(&payer, true, AutoReloadThresholds::default())- .await- .unwrap();- assert!(snap.auto_reload.active);- let reloads = repo.reloads();- assert_eq!(reloads.len(), 2);- assert_eq!(reloads[1].status, CreditReloadStatus::Paid);- assert_eq!(reloads[1].amount_cents, 10_000);- assert_eq!(snap.credit_balance_cents, 10_000);+async fn a_failed_reload_blocks_unfunded_usage_without_a_direct_charge() {+ for fail_open in [false, true] {+ let (svc, repo, payments, _) = premium_service(3_500);+ let payer = user("[email protected]");+ payments.set_pay(PayOutcome::Error);+ *payments.fail_open.lock().unwrap() = fail_open;+ let snap = svc+ .update_auto_reload(&payer, true, AutoReloadThresholds::default())+ .await+ .unwrap();+ assert_eq!(repo.reloads().len(), 1);+ assert_eq!(repo.reloads()[0].status, CreditReloadStatus::Failed);+ assert!(snap.auto_reload.suspended);+ assert!(!snap.auto_reload.active);+ assert_eq!(snap.uncovered_cents, 1_575);+ assert_eq!(snap.remaining_cents, 0);+ assert_eq!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Deny(DenyReason::OveragePaymentFailed)+ );+ svc.settle(&payer).await.unwrap();+ assert!(repo.charges().is_empty());+ assert!(payments.opened().is_empty());+ assert_eq!(payments.payments().len(), usize::from(!fail_open));+ }}#[tokio::test]@@ -1868,7 +1704,7 @@ async fn enabling_auto_reload_validates_the_thresholds() {}#[tokio::test]-async fn enabling_auto_reload_turns_overage_on_clears_suspensions_and_settles() {+async fn enabling_auto_reload_clears_suspensions_and_settles_without_a_direct_charge_cap() {let (svc, repo, _, _) = premium_service(0);let payer = user("[email protected]");repo.set_balance(500);@@ -1878,7 +1714,7 @@ async fn enabling_auto_reload_turns_overage_on_clears_suspensions_and_settles()state.auto_reload_suspended = true;}- // No monthly limit: the overage cap is the most the dialog allows.+ // Reloads do not authorize a direct-charge cap, even without a monthly limit.let snap = svc.update_auto_reload(&payer, true, thresholds(2_000, 20_000, None)).await@@ -1890,27 +1726,19 @@ async fn enabling_auto_reload_turns_overage_on_clears_suspensions_and_settles()assert_eq!(snap.auto_reload.monthly_spend_limit_cents, None);assert!(!snap.auto_reload.suspended);assert!(snap.auto_reload.active);- assert_eq!(- repo.settings(&payer).await.unwrap().overage_limit_cents,- OVERAGE_LIMIT_MAX_CENTS- );+ assert_eq!(repo.settings(&payer).await.unwrap().overage_limit_cents, 0);// Enabling settled, so the low balance reloaded at once.assert_eq!(repo.reloads().len(), 1);assert_eq!(repo.reloads()[0].amount_cents, 19_500);assert_eq!(snap.credit_balance_cents, 20_000);- // A monthly limit becomes the overage cap, within the offered range; one- // under the cap minimum is rejected rather than raised.+ // The monthly limit applies only to reload purchases; keep the offered minimum.assert!(matches!(svc.update_auto_reload(&payer, true, thresholds(2_000, 20_000, Some(100))).await,Err(BillingError::InvalidAutoReload(_))));- for (monthly_limit, overage_limit) in [- (OVERAGE_LIMIT_MIN_CENTS, OVERAGE_LIMIT_MIN_CENTS),- (25_000, 25_000),- (1_000_000, OVERAGE_LIMIT_MAX_CENTS),- ] {+ for monthly_limit in [OVERAGE_LIMIT_MIN_CENTS, 25_000, 1_000_000] {let snap = svc.update_auto_reload(&payer, true, thresholds(2_000, 20_000, Some(monthly_limit))).await@@ -1919,10 +1747,7 @@ async fn enabling_auto_reload_turns_overage_on_clears_suspensions_and_settles()snap.auto_reload.monthly_spend_limit_cents,Some(monthly_limit));- assert_eq!(- repo.settings(&payer).await.unwrap().overage_limit_cents,- overage_limit- );+ assert_eq!(repo.settings(&payer).await.unwrap().overage_limit_cents, 0);}assert_eq!(repo.reloads().len(), 1);}@@ -2049,12 +1874,12 @@ async fn snapshot_reports_whether_automatic_reload_is_active() {.unwrap();assert!(snap.auto_reload.active);- // Reloads ride on overage: an overage suspension stops them too.+ // Historical overage suspensions do not stop automatic reloads.repo.suspend_overage(&payer).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();assert!(snap.overage_suspended);assert!(!snap.auto_reload.suspended);- assert!(!snap.auto_reload.active);+ assert!(snap.auto_reload.active);svc.update_auto_reload(&payer, false, AutoReloadThresholds::default()).await@@ -2178,9 +2003,10 @@ async fn snapshot_freezes_the_open_period_allowance_and_refreshes_it() {}#[tokio::test]-async fn previous_period_overage_uses_the_frozen_allowance_not_the_live_one() {+async fn previous_period_credits_use_the_frozen_allowance_not_the_live_one() {let (svc, repo, payments, usage, _, payer, previous, current) = anchored_premium(0);repo.pause_reloads();+ repo.set_balance(10_000);svc.sync_period(&payer, current.start, current.end, None).await.unwrap();@@ -2194,16 +2020,15 @@ async fn previous_period_overage_uses_the_frozen_allowance_not_the_live_one() {}],},);- svc.update_overage(&payer, true, 10_000).await.unwrap();+ repo.update_overage(&payer, true, 10_000).await.unwrap();usage.add(&payer, previous.start + chrono::Duration::days(2), 2_500);svc.settle(&payer).await.unwrap();- let opened = payments.opened();- assert_eq!(opened.len(), 1);- // 2_500 cost against the frozen 1_000, not the live 2_000: 1_500 over, 1_575 owed.- assert_eq!(opened[0].amount_cents, 1_575);- assert_eq!(repo.charges()[0].status, OverageChargeStatus::Paid);+ // 2_500 cost against the frozen 1_000: 1_500 over, 1_575 prepaid credits.+ assert_eq!(repo.state.lock().unwrap().consumed[&previous.start], 1_575);+ assert!(payments.opened().is_empty());+ assert!(repo.charges().is_empty());// The closed period keeps its freeze; the open one reflects the live allowance.assert_eq!(repo.allowance(previous.start).unwrap().seats[0].included_cents,@@ -2232,7 +2057,7 @@ async fn previous_period_does_not_charge_usage_its_frozen_allowance_included() {}],},);- svc.update_overage(&payer, true, 10_000).await.unwrap();+ repo.update_overage(&payer, true, 10_000).await.unwrap();// Over the live 2_000, but inside the frozen 5_000.usage.add(&payer, previous.start + chrono::Duration::days(2), 4_000);@@ -2256,12 +2081,9 @@ async fn previous_period_usage_never_triggers_a_reload() {.await.unwrap();- // The closed period is collected as overage, not topped up with a- // reload; only the open period reloads, and only for its own usage.- let opened = payments.opened();- assert_eq!(opened.len(), 1);- assert_eq!(opened[0].amount_cents, 2_100);- assert_eq!(repo.charges()[0].period_start, previous.start);+ // Unfunded closed-period usage stays uncovered; only the open period reloads.+ assert!(payments.opened().is_empty());+ assert!(repo.charges().is_empty());let reloads = repo.reloads();assert_eq!(reloads.len(), 1);assert_eq!(reloads[0].amount_cents, 10_000);@@ -2333,17 +2155,17 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {);ents.set(new_team);repo.pause_reloads();- svc.update_overage(&owner, true, 10_000).await.unwrap();+ repo.set_balance(10_000);+ repo.update_overage(&owner, true, 10_000).await.unwrap();svc.settle(&owner).await.unwrap();- let opened = payments.opened();- assert_eq!(opened.len(), 1);+ assert!(payments.opened().is_empty());+ assert!(repo.charges().is_empty());// Member A gets only their own $20 at-cost allowance, so 5_200 cost is// chargeable: 5_460 at the markup. The owner's unused allowance does not// offset it. Member B's usage is ignored because they were not a billed// user in that period.- assert_eq!(opened[0].amount_cents, 5_460);- assert_eq!(opened[0].scope, SubscriptionScope::Team { team_id });+ assert_eq!(repo.state.lock().unwrap().consumed[&previous.start], 5_460);}#[tokio::test]@@ -2363,7 +2185,7 @@ async fn current_period_uses_the_live_allowance_not_a_stale_freeze() {}],},);- svc.update_overage(&payer, true, 10_000).await.unwrap();+ repo.update_overage(&payer, true, 10_000).await.unwrap();// Current-period usage over the stale 1_000 but inside the live 2_000.*usage.cents.lock().unwrap() = 1_500;svc.settle(&payer).await.unwrap();diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rsindex 74c70c1367..3f5b263972 100644--- a/crates/ai_billing/src/inbound/axum_router.rs+++ b/crates/ai_billing/src/inbound/axum_router.rs@@ -90,8 +90,7 @@ pub struct UpdateOverageRequest {#[derive(Debug, Deserialize, ToSchema)]#[serde(rename_all = "camelCase")]pub struct UpdateAutoReloadRequest {- /// Reload credits automatically, billing usage past allowance and- /// credits to the payer's card. Turning this off also turns off overage.+ /// Purchase prepaid credits automatically using the payer's card.pub enabled: bool,/// Reload once the balance drops below this, cents. Must be positive.pub minimum_balance_cents: i64,@@ -99,9 +98,7 @@ pub struct UpdateAutoReloadRequest {/// minimum and no more than the catalog's `auto_reload_target_max_cents`.pub target_balance_cents: i64,/// Most to reload per calendar month, cents. Omit or `null` for no limit.- /// Also serves as the per-period overage cap, so it must be at least the- /// catalog's `overage_limit_min_cents`; larger values are capped at- /// `overage_limit_max_cents`.+ /// Must be at least the catalog's `overage_limit_min_cents` (legacy name).#[serde(default)]pub monthly_spend_limit_cents: Option<i64>,}@@ -327,6 +324,7 @@ fn error_response(e: BillingError) -> Response {BillingError::FreePlan => StatusCode::PAYMENT_REQUIRED,BillingError::InvalidCreditAmount| BillingError::InvalidOverageLimit+ | BillingError::DirectUsageBillingDisabled| BillingError::InvalidAutoReload(_)| BillingError::NoStripeCustomer => StatusCode::BAD_REQUEST,BillingError::Payment(_) | BillingError::Storage(_) | BillingError::Entitlement(_) => {@@ -408,7 +406,7 @@ pub async fn get_plans_handler(State(pricing): State<AiPricing>) -> Json<PlanCat})}-/// Turn overage billing on or off and set the per-period cap. Payer only.+/// Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.#[utoipa::path(patch,path = "/ai-billing/overage",@@ -443,7 +441,7 @@ pub async fn update_overage_handler<B: BillingService, Auth: MacroAuthorizationS}}-/// Turn automatic credit reloads (and with them overage) on with the given+/// Turn automatic credit reloads on with the given/// thresholds, or off. Payer only. Enabling settles right away, so a balance/// already under the minimum reloads immediately.#[utoipa::path(diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rsindex 8f5d625385..7612422a26 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs@@ -517,7 +517,8 @@ impl BillingRepo for PgBillingRepo {.map_err(funding_storage)?;let legacy_limit = legacy_cap_remaining(account.overage_limit_cents, committed_postpaid);let ledger = read_period_ledger(&mut tx, payer, period_start).await?;- let overage_active = account.overage_enabled+ let overage_active = policy.overage_active+ && account.overage_enabled&& account.overage_suspended_at.is_none()&& account.overage_limit_cents > 0;@@ -583,7 +584,9 @@ impl BillingRepo for PgBillingRepo {.fetch_all(&mut *tx).await.map_err(storage)?;- let orphaned = owed.iter().find(|row| row.status == "pending");+ let orphaned = owed+ .iter()+ .find(|row| policy.overage_active && row.status == "pending");let retryable = owed.iter().find(|row| {row.status == "failed"&& overage_activediff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rsindex 92795be85d..e8e6e1903c 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs@@ -673,7 +673,7 @@ async fn update_auto_reload_persists_thresholds_and_clears_both_suspensions(pool}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn reserve_credit_reload_requires_active_overage_and_unsuspended_reloads(pool: PgPool) {+async fn reserve_credit_reload_requires_opt_in_and_unsuspended_reloads(pool: PgPool) {let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());let now = Utc::now();let period_start = now - chrono::Duration::days(10);@@ -688,15 +688,13 @@ async fn reserve_credit_reload_requires_active_overage_and_unsuspended_reloads(p.unwrap().is_none());- // Overage on but suspended.- enable_auto_reload(&repo, &thresholds(None)).await;+ // Historical direct-charge suspension does not affect reload eligibility.+ // Saving with a zero direct-charge cap still allows reloads.+ repo.update_auto_reload(&payer(), true, 0, Some(&thresholds(None)))+ .await+ .unwrap();repo.suspend_overage(&payer()).await.unwrap();- assert!(- repo.reserve_credit_reload(&payer(), period_start, 0, now)- .await- .unwrap()- .is_none()- );+ assert!(repo.settings(&payer()).await.unwrap().auto_reload_active());// Reloads suspended after a failed collection.enable_auto_reload(&repo, &thresholds(None)).await;repo.suspend_auto_reload(&payer()).await.unwrap();@@ -1507,3 +1505,49 @@ async fn rows_frozen_before_the_cost_column_read_as_the_current_allowance(pool:assert_eq!(raw.included_cents_by_user, vec![4_000]);assert_eq!(raw.included_cost_cents_by_user, None);}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn credit_only_settlement_never_reserves_or_retries_direct_charges(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let period_start = Utc::now() - chrono::Duration::days(10);+ repo.update_overage(&payer(), true, 10_000).await.unwrap();+ let mut credit_only = policy(false);+ credit_only.overage_active = false;+ let outcome = repo+ .apply_settlement(&payer(), period_start, 5_000, credit_only)+ .await+ .unwrap();+ assert!(outcome.pending_charge.is_none());+ assert_eq!(charge_rows(&pool).await, 0);++ // Seed historical rows through the legacy policy, then retire collection.+ let historical = repo+ .apply_settlement(&payer(), period_start, 5_000, policy(false))+ .await+ .unwrap()+ .pending_charge+ .unwrap();+ for (status, invoice) in [+ (OverageChargeStatus::Pending, None),+ (OverageChargeStatus::Failed, None),+ (OverageChargeStatus::Failed, Some("in_legacy")),+ ] {+ repo.finish_overage_charge(historical.id, invoice, status)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE ai_overage_charge SET updated_at = NOW() - INTERVAL '1 hour' WHERE id = $1",+ historical.id,+ )+ .execute(&pool)+ .await+ .unwrap();+ repo.update_overage(&payer(), true, 10_000).await.unwrap();+ let outcome = repo+ .apply_settlement(&payer(), period_start, 8_000, credit_only)+ .await+ .unwrap();+ assert!(outcome.pending_charge.is_none());+ assert_eq!(charge_rows(&pool).await, 1);+ }+}diff --git a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs b/crates/ai_billing/src/outbound/pg_funding_repo/test.rsindex d27176fa51..776c508498 100644--- a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_funding_repo/test.rs@@ -487,8 +487,8 @@ async fn allocated(}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn threshold_split_is_credit_first_and_not_double_billed(pool: PgPool) {- let (repo, billing) = setup(&pool, 1_000, true, 5_000).await;+async fn allowance_and_credits_are_not_double_billed(pool: PgPool) {+ let (repo, billing) = setup(&pool, 1_050, true, 5_000).await;let invocation = admit(&repo, 30 * DOLLAR).await;let record = completed(invocation.clone(), 30 * DOLLAR);repo.finalize(record.clone()).await.unwrap();@@ -511,9 +511,9 @@ async fn threshold_split_is_credit_first_and_not_double_billed(pool: PgPool) {assert_eq!(allocation.extra_public.units(), 10 * DOLLAR);assert_eq!(allocation.prepaid,- CustomerMoney::from_cents(1_000).unwrap()+ CustomerMoney::from_cents(1_050).unwrap());- assert_eq!(allocation.postpaid, CustomerMoney::from_cents(50).unwrap());+ assert_eq!(allocation.postpaid.units(), 0);assert_eq!(allocation.macro_absorbed.units(), 0);assert_eq!(allocation.extra_money().unwrap(),@@ -560,6 +560,16 @@ async fn opt_out_credit_only_and_exhaustion(pool: PgPool) {.await.is_err());+ // The retired opt-in cannot fund even a fresh request.+ assert!(+ repo.authorize(request(&denied_rate, 1), denied_rate.clone())+ .await+ .is_err()+ );+ billing+ .record_credit_purchase(&user("payer"), 1_050, "cs_replenished")+ .await+ .unwrap();let fresh = request(&denied_rate, 1);assert!(repo.authorize(fresh, denied_rate.clone()).await.is_ok());let unknown = AuthorizedInvocation {@@ -576,7 +586,7 @@ async fn opt_out_credit_only_and_exhaustion(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn reversed_completions_release_allowance_before_pricing(pool: PgPool) {- let (repo, billing) = setup(&pool, 0, true, 5_000).await;+ let (repo, billing) = setup(&pool, 1_050, true, 5_000).await;let first = admit(&repo, 20 * DOLLAR).await;let second = admit(&repo, 10 * DOLLAR).await;let second_id = second.request.invocation_id;@@ -594,26 +604,32 @@ async fn reversed_completions_release_allowance_before_pricing(pool: PgPool) {}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn earlier_credit_releases_replace_only_eligible_postpaid(pool: PgPool) {- let (repo, billing) = setup(&pool, 1_050, true, 5_000).await;+async fn earlier_credit_releases_remain_available_to_eligible_invocations(pool: PgPool) {+ let (repo, billing) = setup(&pool, 2_100, true, 5_000).await;let included = admit(&repo, 20 * DOLLAR).await;allocated(&repo, included, 20 * DOLLAR).await;let first = admit(&repo, 10 * DOLLAR).await;let second = admit(&repo, 10 * DOLLAR).await;let second_id = second.request.invocation_id;allocated(&repo, first, 0).await;- // Released money is still owed to second, not spendable by newer attempts.+ // Released money remains committed until the next earlier allocation completes.+ let pending_rate = rate();+ assert!(+ repo.authorize(request(&pending_rate, 10 * DOLLAR), pending_rate)+ .await+ .is_err()+ );+ allocated(&repo, second, 10 * DOLLAR).await;let third = admit(&repo, 10 * DOLLAR).await;let third_id = third.request.invocation_id;- repo.finalize(completed(third, 10 * DOLLAR)).await.unwrap();- allocated(&repo, second, 10 * DOLLAR).await;+ allocated(&repo, third, 10 * DOLLAR).await;let second = repo.allocation(second_id).await.unwrap().unwrap();let third = repo.allocation(third_id).await.unwrap().unwrap();assert_eq!(second.prepaid, CustomerMoney::from_cents(1_050).unwrap());- assert_eq!(second.reclaimed_prepaid, second.prepaid);+ assert_eq!(second.reclaimed_prepaid.units(), 0);assert_eq!(second.postpaid.units(), 0);- assert_eq!(third.prepaid.units(), 0);- assert_eq!(third.postpaid, CustomerMoney::from_cents(1_050).unwrap());+ assert_eq!(third.prepaid, CustomerMoney::from_cents(1_050).unwrap());+ assert_eq!(third.postpaid.units(), 0);assert_eq!(billing.credit_balance_cents(&user("payer")).await.unwrap(),0@@ -622,7 +638,7 @@ async fn earlier_credit_releases_replace_only_eligible_postpaid(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn later_purchase_and_disable_do_not_reclassify_authorized_liability(pool: PgPool) {- let (repo, billing) = setup(&pool, 0, true, 2_000).await;+ let (repo, billing) = setup(&pool, 1_050, true, 2_000).await;let invocation = admit(&repo, 30 * DOLLAR).await;billing.update_overage(&user("payer"), false, 0)@@ -633,11 +649,11 @@ async fn later_purchase_and_disable_do_not_reclassify_authorized_liability(pool:.await.unwrap();let allocation = allocated(&repo, invocation, 30 * DOLLAR).await;- assert_eq!(allocation.prepaid.units(), 0);assert_eq!(- allocation.postpaid,+ allocation.prepaid,CustomerMoney::from_cents(1_050).unwrap());+ assert_eq!(allocation.postpaid.units(), 0);assert_eq!(billing.credit_balance_cents(&user("payer")).await.unwrap(),2_500@@ -659,7 +675,7 @@ async fn unfunded_overshoot_is_absorbed_not_debt(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn pending_evidence_blocks_watermark_and_is_discoverable(pool: PgPool) {- let (repo, _) = setup(&pool, 0, true, 5_000).await;+ let (repo, _) = setup(&pool, 105, true, 5_000).await;let first = admit(&repo, 20 * DOLLAR).await;let first_id = first.request.invocation_id;let second = admit(&repo, DOLLAR).await;@@ -847,11 +863,12 @@ async fn duplicate_admissions_reserve_once_even_after_lost_acknowledgement(pool:}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn collected_new_liability_is_neither_legacy_coverage_nor_a_second_cap_debit(pool: PgPool) {- let (repo, billing) = setup(&pool, 0, true, 210).await;+async fn historical_v1_charges_are_not_legacy_coverage(pool: PgPool) {+ let (repo, billing) = setup(&pool, 210, true, 210).await;let first = admit(&repo, 21 * DOLLAR).await;let allocation = allocated(&repo, first, 21 * DOLLAR).await;- assert_eq!(allocation.postpaid, CustomerMoney::from_cents(105).unwrap());+ assert_eq!(allocation.prepaid, CustomerMoney::from_cents(105).unwrap());+ assert_eq!(allocation.postpaid.units(), 0);let payer = user("payer");sqlx::query!("INSERT INTO ai_overage_charge (id, user_id, period_start, amount_cents, status, accounting_policy)@@ -865,13 +882,13 @@ async fn collected_new_liability_is_neither_legacy_coverage_nor_a_second_cap_debassert_eq!(ledger.overage_charged_cents, 0);let next = admit(&repo, DOLLAR).await;assert_eq!(- allocated(&repo, next, DOLLAR).await.postpaid,+ allocated(&repo, next, DOLLAR).await.prepaid,CustomerMoney::from_cents(105).unwrap());}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn racing_postpaid_admissions_never_exceed_the_cap(pool: PgPool) {+async fn racing_admissions_never_use_a_legacy_postpaid_cap(pool: PgPool) {let (repo, _) = setup(&pool, 0, true, 105).await;let included = admit(&repo, 20 * DOLLAR).await;allocated(&repo, included, 20 * DOLLAR).await;@@ -887,15 +904,15 @@ async fn racing_postpaid_admissions_never_exceed_the_cap(pool: PgPool) {while let Some(result) = tasks.join_next().await {admitted += usize::from(result.unwrap());}- assert_eq!(admitted, 1);+ assert_eq!(admitted, 0);}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn legacy_settlement_cannot_spend_new_holds_or_cap(pool: PgPool) {let (repo, billing) = setup(&pool, 1_050, true, 1_050).await;- let _held = admit(&repo, 40 * DOLLAR).await;+ let _held = admit(&repo, 30 * DOLLAR).await;let policy = SettlementPolicy {- overage_active: true,+ overage_active: false,overage_limit_cents: 1_050,charge_threshold_cents: 1_000,period_ended: false,@@ -991,10 +1008,7 @@ async fn purchases_toggles_cap_reductions_and_admission_use_the_same_lock(pool:admitted.request.invocation_id.as_uuid(),).fetch_one(&pool).await.unwrap().admission;assert_eq!(captured.policy, UsagePolicy::PublicAllowanceV1);- assert_eq!(- captured.overage_enabled,- matches!(captured.postpaid, PostpaidData::Enabled(_))- );+ assert!(matches!(captured.postpaid, PostpaidData::Disabled));assert!(captured.revision <= 3);billing.update_overage(&user("payer"), false, 0)diff --git a/crates/ai_billing/src/outbound/stripe_gateway.rs b/crates/ai_billing/src/outbound/stripe_gateway.rsindex 0ee943d681..8d42eef5c5 100644--- a/crates/ai_billing/src/outbound/stripe_gateway.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway.rs@@ -1,5 +1,5 @@//! Stripe adapter: one-off Checkout for credit packs, immediate invoices for-//! overage chunks and automatic credit reloads, and the current subscription+//! automatic credit reloads, and the current subscription//! period.#[cfg(test)]@@ -39,7 +39,6 @@ pub const PAYER_METADATA_KEY: &str = "macro_user_id";pub const CHARGE_METADATA_KEY: &str = "macro_charge_id";/// Metadata key carrying the `ai_credit_reload` id on reload invoices.pub const RELOAD_METADATA_KEY: &str = "macro_reload_id";-const OVERAGE_INVOICE_DESCRIPTION: &str = "Macro AI usage beyond plan";const CREDIT_RELOAD_INVOICE_DESCRIPTION: &str = "Macro AI credits (automatic reload)";const BILLING_SCOPE_METADATA_KEY: &str = "macro_billing_scope";const PERSONAL_SCOPE_STAMP: &str = "personal";@@ -226,16 +225,6 @@ struct OneOffInvoice<'a> {line_description: &'a str,}-fn overage_metadata(charge_id: Uuid) -> HashMap<String, String> {- HashMap::from([- (- PURPOSE_METADATA_KEY.to_string(),- PURPOSE_AI_OVERAGE.to_string(),- ),- (CHARGE_METADATA_KEY.to_string(), charge_id.to_string()),- ])-}-fn credit_reload_metadata(reload_id: Uuid, payer: &MacroUserIdStr<'_>) -> HashMap<String, String> {HashMap::from([(@@ -467,19 +456,7 @@ impl PaymentGateway for StripePaymentGateway {#[tracing::instrument(skip(self, request), fields(charge = %request.charge_id, cents = request.amount_cents), err)]async fn open_overage_invoice(&self, request: OverageChargeRequest) -> Result<String> {- let customer = parse_customer(&request.customer_id)?;- self.open_one_off_invoice(- customer,- request.scope,- OneOffInvoice {- idempotency_prefix: format!("ai_overage:{}", request.charge_id),- metadata: overage_metadata(request.charge_id),- invoice_description: OVERAGE_INVOICE_DESCRIPTION,- amount_cents: request.amount_cents,- line_description: &request.description,- },- )- .await+ Err(BillingError::DirectUsageBillingDisabled)}#[tracing::instrument(skip(self, request), fields(reload = %request.reload_id, payer = %request.payer, cents = request.amount_cents), err)]@@ -512,6 +489,15 @@ impl PaymentGateway for StripePaymentGateway {let invoice = Invoice::retrieve(&self.client, &invoice_id, &[]).await.map_err(payment)?;+ if invoice+ .metadata+ .as_ref()+ .and_then(|metadata| metadata.get(PURPOSE_METADATA_KEY))+ .map(String::as_str)+ == Some(PURPOSE_AI_OVERAGE)+ {+ return Err(BillingError::DirectUsageBillingDisabled);+ }if invoice.status == Some(InvoiceStatus::Paid) {return Ok(true);}diff --git a/crates/ai_billing/src/outbound/stripe_gateway/test.rs b/crates/ai_billing/src/outbound/stripe_gateway/test.rsindex fc500bfb48..faec9574c3 100644--- a/crates/ai_billing/src/outbound/stripe_gateway/test.rs+++ b/crates/ai_billing/src/outbound/stripe_gateway/test.rs@@ -16,7 +16,7 @@ const INVOICE_ID: &str = "in_overage";const TEAM_ID: Uuid = Uuid::from_u128(7);#[tokio::test]-async fn open_overage_invoice_keeps_create_stable_and_updates_current_routing() {+async fn open_credit_reload_invoice_keeps_create_stable_and_updates_current_routing() {let invoice = stripe_response(&draft_invoice());let invoice_item = stripe_response(&draft_invoice_item());let server = MockServer::start().await;@@ -60,15 +60,16 @@ async fn open_overage_invoice_keeps_create_stable_and_updates_current_routing().await;gateway(&server)- .open_overage_invoice(OverageChargeRequest {+ .open_credit_reload_invoice(CreditReloadRequest {customer_id: CUSTOMER_ID.to_string(),- charge_id: Uuid::from_u128(1),+ reload_id: Uuid::from_u128(1),+ payer: payer(),amount_cents: 2_500,- description: "Macro AI usage beyond plan".to_string(),+ description: "Macro AI credits, automatic reload".to_string(),scope: SubscriptionScope::Personal,}).await- .expect("open overage invoice");+ .expect("open reload invoice");let requests = server.received_requests().await.expect("recorded requests");@@ -86,15 +87,15 @@ async fn open_overage_invoice_keeps_create_stable_and_updates_current_routing());assert_eq!(form_value(create_body, &format!("metadata[{PURPOSE_METADATA_KEY}]")),- Some(PURPOSE_AI_OVERAGE)+ Some(PURPOSE_AI_CREDIT_RELOAD));assert_eq!(- form_value(create_body, &format!("metadata[{CHARGE_METADATA_KEY}]")),+ form_value(create_body, &format!("metadata[{RELOAD_METADATA_KEY}]")),Some("00000000-0000-0000-0000-000000000001"));assert_eq!(idempotency_key(create),- Some("ai_overage:00000000-0000-0000-0000-000000000001:invoice")+ Some("ai_credit_reload:00000000-0000-0000-0000-000000000001:invoice"));let update = post_request(&requests, &format!("/v1/invoices/{INVOICE_ID}"));@@ -125,15 +126,15 @@ async fn open_overage_invoice_keeps_create_stable_and_updates_current_routing()assert_eq!(form_value(item_body, "subscription"), None);assert_eq!(form_value(item_body, &format!("metadata[{PURPOSE_METADATA_KEY}]")),- Some(PURPOSE_AI_OVERAGE)+ Some(PURPOSE_AI_CREDIT_RELOAD));assert_eq!(- form_value(item_body, &format!("metadata[{CHARGE_METADATA_KEY}]")),+ form_value(item_body, &format!("metadata[{RELOAD_METADATA_KEY}]")),Some("00000000-0000-0000-0000-000000000001"));assert_eq!(idempotency_key(item),- Some("ai_overage:00000000-0000-0000-0000-000000000001:item")+ Some("ai_credit_reload:00000000-0000-0000-0000-000000000001:item"));let create_at = request_position(&requests, "POST", "/v1/invoices");@@ -209,7 +210,7 @@ async fn pay_overage_invoice_updates_a_stale_open_invoice_before_paying() {}#[tokio::test]-async fn open_overage_invoice_rejects_distinct_subscription_methods_without_posting() {+async fn open_credit_reload_invoice_rejects_distinct_subscription_methods_without_posting() {let server = MockServer::start().await;mount_customer(&server).await;Mock::given(method("GET"))@@ -244,11 +245,12 @@ async fn open_overage_invoice_rejects_distinct_subscription_methods_without_post.await;let error = gateway(&server)- .open_overage_invoice(OverageChargeRequest {+ .open_credit_reload_invoice(CreditReloadRequest {customer_id: CUSTOMER_ID.to_string(),- charge_id: Uuid::from_u128(2),+ reload_id: Uuid::from_u128(2),+ payer: payer(),amount_cents: 2_500,- description: "Macro AI usage beyond plan".to_string(),+ description: "Macro AI credits, automatic reload".to_string(),scope: SubscriptionScope::Personal,}).await@@ -324,7 +326,7 @@ async fn pay_overage_invoice_skips_the_update_when_the_open_invoice_already_matc}#[tokio::test]-async fn open_overage_invoice_selects_the_subscription_for_the_requested_scope() {+async fn open_credit_reload_invoice_selects_the_subscription_for_the_requested_scope() {let invoice = stripe_response(&draft_invoice());let invoice_item = stripe_response(&draft_invoice_item());let server = MockServer::start().await;@@ -357,13 +359,13 @@ async fn open_overage_invoice_selects_the_subscription_for_the_requested_scope()let gateway = gateway(&server);gateway- .open_overage_invoice(charge(SubscriptionScope::Personal, 4))+ .open_credit_reload_invoice(reload(SubscriptionScope::Personal, 4)).await- .expect("personal overage invoice");+ .expect("personal reload invoice");gateway- .open_overage_invoice(charge(SubscriptionScope::Team { team_id: TEAM_ID }, 5))+ .open_credit_reload_invoice(reload(SubscriptionScope::Team { team_id: TEAM_ID }, 5)).await- .expect("team overage invoice");+ .expect("team reload invoice");let requests = server.received_requests().await.expect("recorded requests");let creates: Vec<_> = requests@@ -415,7 +417,7 @@ async fn open_overage_invoice_selects_the_subscription_for_the_requested_scope()}#[tokio::test]-async fn open_overage_invoice_replay_uses_the_retrieved_scope_and_stored_method() {+async fn open_credit_reload_invoice_replay_uses_the_retrieved_scope_and_stored_method() {let cached_invoice = stripe_response(&draft_invoice());let mut current_invoice = draft_invoice();current_invoice.default_payment_method = Some(stripe::Expandable::Id(@@ -458,7 +460,7 @@ async fn open_overage_invoice_replay_uses_the_retrieved_scope_and_stored_method(.await;gateway(&server)- .open_overage_invoice(charge(SubscriptionScope::Team { team_id: TEAM_ID }, 7))+ .open_credit_reload_invoice(reload(SubscriptionScope::Team { team_id: TEAM_ID }, 7)).await.expect("replay overage invoice");@@ -488,7 +490,7 @@ async fn open_overage_invoice_replay_uses_the_retrieved_scope_and_stored_method(}#[tokio::test]-async fn open_overage_invoice_replay_returns_an_already_paid_invoice() {+async fn open_credit_reload_invoice_replay_returns_an_already_paid_invoice() {let cached_invoice = stripe_response(&draft_invoice());let paid_invoice = stripe_response(&paid_invoice(CURRENT_PAYMENT_METHOD,@@ -520,7 +522,7 @@ async fn open_overage_invoice_replay_returns_an_already_paid_invoice() {.await;let invoice_id = gateway(&server)- .open_overage_invoice(charge(SubscriptionScope::Personal, 12))+ .open_credit_reload_invoice(reload(SubscriptionScope::Personal, 12)).await.expect("already paid invoice");assert_eq!(invoice_id, INVOICE_ID);@@ -542,7 +544,7 @@ async fn open_overage_invoice_replay_returns_an_already_paid_invoice() {}#[tokio::test]-async fn open_overage_invoice_leaves_a_safe_draft_when_scope_has_no_match() {+async fn open_credit_reload_invoice_leaves_a_safe_draft_when_scope_has_no_match() {let invoice = stripe_response(&draft_invoice());let server = MockServer::start().await;mount_customer_and_subscriptions(&server, team_subscription()).await;@@ -558,7 +560,7 @@ async fn open_overage_invoice_leaves_a_safe_draft_when_scope_has_no_match() {.await;let error = gateway(&server)- .open_overage_invoice(charge(SubscriptionScope::Personal, 9))+ .open_credit_reload_invoice(reload(SubscriptionScope::Personal, 9)).await.expect_err("missing personal subscription");assert!(matches!(error, BillingError::Payment(_)));@@ -576,7 +578,7 @@ async fn open_overage_invoice_leaves_a_safe_draft_when_scope_has_no_match() {);assert_eq!(idempotency_key(create),- Some("ai_overage:00000000-0000-0000-0000-000000000009:invoice")+ Some("ai_credit_reload:00000000-0000-0000-0000-000000000009:invoice"));assert_eq!(requests@@ -971,21 +973,6 @@ fn credit_reload_metadata_stamps_purpose_reload_and_payer() {assert!(!metadata.contains_key(CHARGE_METADATA_KEY));}-#[test]-fn overage_metadata_stamps_purpose_and_charge_only() {- let metadata = overage_metadata(Uuid::from_u128(1));-- assert_eq!(metadata.len(), 2);- assert_eq!(- metadata.get(PURPOSE_METADATA_KEY).map(String::as_str),- Some(PURPOSE_AI_OVERAGE)- );- assert_eq!(- metadata.get(CHARGE_METADATA_KEY).map(String::as_str),- Some("00000000-0000-0000-0000-000000000001")- );-}-#[tokio::test]async fn subscription_period_reports_provider_errors() {let server = MockServer::start().await;@@ -1178,12 +1165,13 @@ fn team_subscription() -> Value {)}-fn charge(scope: SubscriptionScope, charge_id: u128) -> OverageChargeRequest {- OverageChargeRequest {+fn reload(scope: SubscriptionScope, reload_id: u128) -> CreditReloadRequest {+ CreditReloadRequest {customer_id: CUSTOMER_ID.to_string(),- charge_id: Uuid::from_u128(charge_id),+ reload_id: Uuid::from_u128(reload_id),+ payer: payer(),amount_cents: 2_500,- description: "Macro AI usage beyond plan".to_string(),+ description: "Macro AI credits, automatic reload".to_string(),scope,}}@@ -1268,3 +1256,50 @@ fn fill_missing_field(value: &mut Value, field: &str) {Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}}}++#[tokio::test]+async fn direct_usage_invoices_are_disabled_without_contacting_stripe() {+ let server = MockServer::start().await;+ let result = gateway(&server)+ .open_overage_invoice(OverageChargeRequest {+ customer_id: CUSTOMER_ID.to_string(),+ charge_id: Uuid::from_u128(1),+ amount_cents: 2_500,+ description: "Retired usage charge".to_string(),+ scope: SubscriptionScope::Personal,+ })+ .await;+ assert!(matches!(+ result,+ Err(BillingError::DirectUsageBillingDisabled)+ ));+ assert!(server.received_requests().await.unwrap().is_empty());+}++fn payer() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++#[tokio::test]+async fn historical_direct_usage_invoices_are_never_paid_by_the_gateway() {+ let server = MockServer::start().await;+ let mut invoice = open_invoice(Some(CURRENT_PAYMENT_METHOD), Some(PERSONAL_SCOPE_STAMP));+ invoice.metadata.as_mut().unwrap().insert(+ PURPOSE_METADATA_KEY.to_string(),+ PURPOSE_AI_OVERAGE.to_string(),+ );+ Mock::given(method("GET"))+ .and(path(format!("/v1/invoices/{INVOICE_ID}")))+ .respond_with(ResponseTemplate::new(200).set_body_json(stripe_response(&invoice)))+ .expect(1)+ .mount(&server)+ .await;+ let result = gateway(&server)+ .pay_overage_invoice(Uuid::from_u128(1), INVOICE_ID, SubscriptionScope::Personal)+ .await;+ assert!(matches!(+ result,+ Err(BillingError::DirectUsageBillingDisabled)+ ));+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 041984a499..a6b50eb626 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -566,7 +566,7 @@ documents:Quota admission uses the backend's default-off `ENABLE_AI_USAGE_ENFORCEMENT`policy once configured by the host; it is independent of environment. Settlement-(credit consumption and Stripe overage collection) is gated by the separate+(credit consumption and automatic credit reloads) is gated by the separatedefault-off `ENABLE_AI_USAGE_BILLING` policy, also independent of environment.With admission enabled, cognition chatand structured completion return 402 for exhausted allowance or 503 withdiff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex dc9ae596ad..f67d6b326b 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2301,16 +2301,19 @@ The **Automatic reload** switch opens **Auto-Reload** without toggling directly.It contains Minimum balance (default `$10`), Target balance (default `$100`),optional Maximum monthly spend (`No limit`), a payment-method management link,and the automatic-charge warning. The dialog saves for paid payers:-`Turn on auto-reload` enables usage billing with those thresholds (the monthly-limit also caps usage billing per period), `Save` updates them while on, and-`Turn off` disables usage billing. The **Automatic reload** switch reflects the-saved state. Paid team members who are not the payer see+`Turn on auto-reload` enables automatic credit purchases with those thresholds,+`Save` updates them while on, and `Turn off` disables automatic reload. The monthly+limit caps reload purchases per UTC calendar month. The **Automatic reload**+switch reflects the saved state. Paid team members who are not the payer see`Only the account that pays for this plan can change automatic reload.` andcannot save. After a failed automatic reload the dialog shows `Your lastautomatic reload could not be charged. Update your payment method, then save to-try again.`; saving retries. Existing postpaid usage billing is shown separately-and can be turned off by the payer; while it is on, credits reload automatically-when the balance drops below the minimum. Local **Developer tools** offer+try again.`; saving retries. Extra usage is funded entirely by prepaid credits.+If the reload budget runs out or payment fails, uncovered usage cannot trigger a+direct usage charge; with quota enforcement enabled, exhausted credits and+allowance block further AI requests. Historical direct-charge invoices are still+recognized by webhooks, but settlement never creates or retries them. Local+**Developer tools** offer`Preview Free plan` and `Preview paid plan` to display either Usage page withsample usage, regardless of the signed-in account's tier.`Open Free usage-limit dialog` and `Open paid usage-limit dialog` open thediff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.mdindex bbe8f34202..0109c1574b 100644--- a/docs/AI_QUOTA_ENFORCEMENT.md+++ b/docs/AI_QUOTA_ENFORCEMENT.md@@ -42,7 +42,7 @@ counted usage per UTC calendar month: past it, admission answersor overage. Model-access and resource permissions remain independent. Countingeligibility is not a claim that a particular user owes money; it does notspecial-case their plan. Existing paid allowance, per-seat usage, payer credits,-overage opt-in/cap, and denial decisions remain in the legacy ledger.+automatic reload opt-in, and denial decisions remain in the legacy ledger.### Persistence@@ -65,8 +65,9 @@ backfilled into counted usage or financial authorizations.## Settlement: `ENABLE_AI_USAGE_BILLING``ENABLE_AI_USAGE_BILLING` enables **legacy settlement of counted usage past a-payer's allowance**: prepaid credits are consumed and opt-in overage is reserved-and collected through Stripe. The [startup loader](../crates/ai_billing/src/config.rs)+payer's allowance**: prepaid credits are consumed and optional automatic reloads+purchase more credits through Stripe. Direct usage charges are disabled. The+[startup loader](../crates/ai_billing/src/config.rs)parses it exactly like the enforcement flag (absent means false; only raw `true`or `false`; malformed present values fail startup) and hosts load it once. It isindependent of `ENABLE_AI_USAGE_ENFORCEMENT` and of the deployment environment:@@ -81,7 +82,7 @@ hard cap, per user per UTC calendar month), `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`(Premium, per seat per subscription period), and `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`(Max, per seat per subscription period) — and `AI_USAGE_OVERAGE_MARKUP_PERCENT`,the whole-percent markup over cost applied to paid usage beyond the allowance before-credits are consumed or overage is charged. There is no default in code: a missing,+credits are consumed. There is no default in code: a missing,malformed, or out-of-range value fails startup and the Doppler CI validator. The values live in `shared_ai` (`lcl`,`dev`, `prd`), which every participating service inherits except the authenticationservice, whose `dev` and `prd` configs carry them directly; the no-Doppler local@@ -106,15 +107,15 @@ Every other host composes admission throughsettles regardless of configuration. The authentication service's policy isauthoritative: a request from document cognition is a no-op there while its flagis false, and with document cognition false the authentication service still-settles on summary reads, overage changes, and credit purchases. Enable both+settles on summary reads, automatic reload changes, and credit purchases. Enable bothtogether. Settlement without `ENABLE_AI_USAGE_ENFORCEMENT` finds nothing tosettle, because only counted rows are chargeable.Automatic credit reload is part of the same settlement. It fires only inside`BillingServiceImpl::settle`, so it shares the `ENABLE_AI_USAGE_BILLING` gate,-and only for the current period, before an overage chunk is reserved: while-overage is active (enabled, not suspended, cap above zero) and reloads are not-reload-suspended, settlement compares the credit balance net of the period's+and only for the current period, before prepaid credits are consumed: while+automatic reload is enabled and not reload-suspended, settlement compares the+credit balance net of the period'suncovered usage with the payer's minimum balance and, below it, reloads up to thetarget balance. The minimum, target, and optional monthly spend limit are storedper payer on `ai_billing_account` (defaults `$10`, `$100`, and no limit). The@@ -126,19 +127,22 @@ payer lock and collected as a one-off Stripe invoice stampedpurchase, idempotent on the invoice id. A declined invoice stays pending, whichblocks further reloads, until the Stripe webhook reports it paid (credits arebooked) or failed (reloads are suspended). A provider failure marks the reload-failed and sets `auto_reload_suspended_at`; overage remains the fallback until-the payer saves their settings again. A failed reload whose invoice reached+failed and sets `auto_reload_suspended_at` until the payer saves their settings+again. Exhausted reload budgets, declined payments, and provider failures leave+unfunded usage uncovered. There is no direct-charge fallback or headroom from a+historical overage cap; when quota enforcement is enabled, exhausted allowance+and prepaid credits block new AI requests. A failed reload whose invoice reachedStripe keeps that invoice, and the next reservation after reloads are re-enabledretries it rather than opening a second one. `PATCH /ai-billing/auto-reload`-(payer on a paid plan only) is how overage is turned on: enabling validates and-stores the thresholds, sets `overage_enabled`, uses the monthly limit as the-per-period overage cap (the offered maximum when there is no limit), clears both-suspensions, and settles at once; disabling behaves like turning overage off and-keeps the stored thresholds. A monthly limit must be at least the overage cap-minimum (`$5`) so the cap is never raised above what the payer entered. The-monthly limit bounds reload purchases per calendar month; the overage cap it-seeds bounds how far *over* credits usage may run per Stripe period. They are-not a combined budget. `GET /ai-billing/summary`+(payer on a paid plan only) enables automatic reloads: enabling validates and+stores the thresholds, sets the legacy `overage_enabled` reload opt-in field,+zeros the direct-charge cap, clears suspensions, and settles at once. Disabling+keeps the stored thresholds. The monthly reload budget must be at least `$5`.+`PATCH /ai-billing/overage` rejects attempts to enable direct billing; disabling+remains supported for older clients. New V1 funding snapshots also disable+postpaid authorization. Historical invoices retain their accounting and webhook+handling, but settlement never creates or retries direct charges.+`GET /ai-billing/summary`reports `auto_reload` with the thresholds, `suspended`, and `active`.The frontend is not tied to this flag. Settings → Usage and the shared usage-limitdiff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex aac1c514a8..a293127c15 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -58,7 +58,7 @@ export class Sdk extends HeyApiClient {}/**- * Turn automatic credit reloads (and with them overage) on with the given+ * Turn automatic credit reloads on with the given* thresholds, or off. Payer only. Enabling settles right away, so a balance* already under the minimum reloads immediately.*/@@ -88,7 +88,7 @@ export class Sdk extends HeyApiClient {}/**- * Turn overage billing on or off and set the per-period cap. Payer only.+ * Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.*/public updateAiBillingOverage<ThrowOnError extends boolean = false>(options: Options<UpdateAiBillingOverageData, ThrowOnError>): RequestResult<UpdateAiBillingOverageResponses, UpdateAiBillingOverageErrors, ThrowOnError> {return (options.client ?? this.client).patch<UpdateAiBillingOverageResponses, UpdateAiBillingOverageErrors, ThrowOnError>({diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 64e8e1e58f..f885205646 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -40,7 +40,7 @@ export type AutoReloadDefaults = {*/export type AutoReloadSnapshot = {/**- * Whether reloads will fire: overage is on and reloads are not suspended.+ * Whether reloads will fire: the payer opted in and reloads are not suspended.*/active: boolean;/**@@ -1547,8 +1547,7 @@ export type ToggleNonAdminInvitesResponse = {*/export type UpdateAutoReloadRequest = {/**- * Reload credits automatically, billing usage past allowance and- * credits to the payer's card. Turning this off also turns off overage.+ * Purchase prepaid credits automatically using the payer's card.*/enabled: boolean;/**@@ -1557,9 +1556,7 @@ export type UpdateAutoReloadRequest = {minimumBalanceCents: number;/*** Most to reload per calendar month, cents. Omit or `null` for no limit.- * Also serves as the per-period overage cap, so it must be at least the- * catalog's `overage_limit_min_cents`; larger values are capped at- * `overage_limit_max_cents`.+ * Must be at least the catalog's `overage_limit_min_cents` (legacy name).*/monthlySpendLimitCents?: number | null;/**@@ -1589,7 +1586,7 @@ export type UpdateOverageRequest = {*/export type UsageSnapshot = {/**- * Automatic credit reload settings. `active` means overage is on and+ * Automatic credit reload settings. `active` means the payer opted in and* reloads are not suspended.*/auto_reload: AutoReloadSnapshot;@@ -1615,7 +1612,7 @@ export type UsageSnapshot = {*/overage_charged_cents: number;/**- * Whether overage billing is on.+ * Legacy API name for the automatic reload opt-in. Never authorizes direct charges.*/overage_enabled: boolean;/**diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex cf38f9e762..23c9831b11 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -13,7 +13,7 @@"/ai-billing/auto-reload": {"patch": {"tags": ["ai_billing"],- "summary": "Turn automatic credit reloads (and with them overage) on with the given\nthresholds, or off. Payer only. Enabling settles right away, so a balance\nalready under the minimum reloads immediately.",+ "summary": "Turn automatic credit reloads on with the given\nthresholds, or off. Payer only. Enabling settles right away, so a balance\nalready under the minimum reloads immediately.","operationId": "update_ai_billing_auto_reload","requestBody": {"content": {@@ -157,7 +157,7 @@"/ai-billing/overage": {"patch": {"tags": ["ai_billing"],- "summary": "Turn overage billing on or off and set the per-period cap. Payer only.",+ "summary": "Retired direct-usage opt-in. Enabling is rejected; disabling remains supported.","operationId": "update_ai_billing_overage","requestBody": {"content": {@@ -4886,7 +4886,7 @@"properties": {"active": {"type": "boolean",- "description": "Whether reloads will fire: overage is on and reloads are not suspended."+ "description": "Whether reloads will fire: the payer opted in and reloads are not suspended."},"minimum_balance_cents": {"type": "integer",@@ -6814,7 +6814,7 @@"properties": {"enabled": {"type": "boolean",- "description": "Reload credits automatically, billing usage past allowance and\ncredits to the payer's card. Turning this off also turns off overage."+ "description": "Purchase prepaid credits automatically using the payer's card."},"minimumBalanceCents": {"type": "integer",@@ -6824,7 +6824,7 @@"monthlySpendLimitCents": {"type": ["integer", "null"],"format": "int64",- "description": "Most to reload per calendar month, cents. Omit or `null` for no limit.\nAlso serves as the per-period overage cap, so it must be at least the\ncatalog's `overage_limit_min_cents`; larger values are capped at\n`overage_limit_max_cents`."+ "description": "Most to reload per calendar month, cents. Omit or `null` for no limit.\nMust be at least the catalog's `overage_limit_min_cents` (legacy name)."},"targetBalanceCents": {"type": "integer",@@ -6875,7 +6875,7 @@"properties": {"auto_reload": {"$ref": "#/components/schemas/AutoReloadSnapshot",- "description": "Automatic credit reload settings. `active` means overage is on and\nreloads are not suspended."+ "description": "Automatic credit reload settings. `active` means the payer opted in and\nreloads are not suspended."},"blocked_reason": {"oneOf": [@@ -6914,7 +6914,7 @@},"overage_enabled": {"type": "boolean",- "description": "Whether overage billing is on."+ "description": "Legacy API name for the automatic reload opt-in. Never authorizes direct charges."},"overage_limit_cents": {"type": "integer",