Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai-billing): load AI pricing from mandatory Doppler values (#7508)

Will Hutchinsonbdb445fec908
diff --git a/Cargo.lock b/Cargo.lock
index c8363ca39d..0039f03211 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11866,6 +11866,7 @@ name = "memory"
version = "0.1.0"
dependencies = [
"agent",
+ "ai_billing",
"ai_tools",
"ai_toolset",
"ai_usage",
diff --git a/crates/ai_billing/src/composition.rs b/crates/ai_billing/src/composition.rs
index 7c5daa99db..9dca22c67a 100644
--- a/crates/ai_billing/src/composition.rs
+++ b/crates/ai_billing/src/composition.rs
@@ -1,7 +1,7 @@
//! Composition helpers for quota admission without payment collection.
use crate::{
- AiAdmissionService, AiUsageEnforcement, BillingAdmissionService,
+ AiAdmissionService, AiPricing, AiUsageEnforcement, BillingAdmissionService,
domain::BillingServiceImpl,
outbound::{NoOpPaymentGateway, PgBillingRepo, PgUsageReader, RolesTeamsEntitlementSource},
};
@@ -14,11 +14,13 @@ use teams::domain::team_repo::TeamRepository;
mod test;
/// Compose quota admission for hosts without an existing billing service.
-/// Adapter construction stays in this owning-domain composition root.
+/// Adapter construction stays in this owning-domain composition root. `pricing`
+/// is the host's mandatory startup configuration.
#[cfg(feature = "pg-admission")]
pub fn pg_admission_service(
pool: PgPool,
enforcement: AiUsageEnforcement,
+ pricing: AiPricing,
) -> Arc<dyn AiAdmissionService> {
admission_service(
pool.clone(),
@@ -28,6 +30,7 @@ pub fn pg_admission_service(
),
teams::outbound::team_repo::TeamRepositoryImpl::new(pool),
enforcement,
+ pricing,
)
}
@@ -42,6 +45,7 @@ pub fn admission_service<P, T>(
permissions: P,
teams: T,
enforcement: AiUsageEnforcement,
+ pricing: AiPricing,
) -> Arc<dyn AiAdmissionService>
where
P: UserRolesAndPermissionsService,
@@ -50,8 +54,9 @@ where
let billing = BillingServiceImpl::new(
RolesTeamsEntitlementSource::new(permissions, teams),
PgUsageReader::new(pool.clone()),
- PgBillingRepo::new(pool),
+ PgBillingRepo::new(pool, pricing),
NoOpPaymentGateway,
+ pricing,
)
.with_enforcement(enforcement);
Arc::new(BillingAdmissionService::new(Arc::new(billing), enforcement))
diff --git a/crates/ai_billing/src/composition/test.rs b/crates/ai_billing/src/composition/test.rs
index 2d176c7d24..fa7524d1ec 100644
--- a/crates/ai_billing/src/composition/test.rs
+++ b/crates/ai_billing/src/composition/test.rs
@@ -73,10 +73,18 @@ async fn configured_composition_skips_billing_only_for_disabled_or_exempt_work()
.unwrap();
pool.close().await;
let user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
- let disabled = pg_admission_service(pool.clone(), AiUsageEnforcement::Disabled);
+ let disabled = pg_admission_service(
+ pool.clone(),
+ AiUsageEnforcement::Disabled,
+ AiPricing::testing(),
+ );
assert_eq!(disabled.admit(&user, AiFeature::Chat).await, Ok(()));
- let enabled = pg_admission_service(pool.clone(), AiUsageEnforcement::Enabled);
+ let enabled = pg_admission_service(
+ pool.clone(),
+ AiUsageEnforcement::Enabled,
+ AiPricing::testing(),
+ );
for feature in ai_usage::NON_BILLABLE_AI_FEATURES {
assert_eq!(enabled.admit(&user, feature).await, Ok(()));
}
diff --git a/crates/ai_billing/src/config.rs b/crates/ai_billing/src/config.rs
index 1639f6a868..2c8a9204b2 100644
--- a/crates/ai_billing/src/config.rs
+++ b/crates/ai_billing/src/config.rs
@@ -1,10 +1,31 @@
-//! Startup configuration for AI usage settlement.
+//! Startup configuration for AI usage settlement and pricing.
+//!
+//! Pricing is two mandatory Doppler values, read once at startup by every
+//! host that composes this crate:
+//!
+//! | Key | Meaning |
+//! | --- | --- |
+//! | `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` | In-plan AI per paid seat per period, cents at provider cost |
+//! | `AI_USAGE_OVERAGE_MARKUP_PERCENT` | Markup on usage past the allowance, a whole percent (0-99) |
+//!
+//! Hosts on MacroConfig declare them as required fields of their `Config`
+//! using [`IncludedAllowanceCents`] and [`OverageMarkupPercent`] directly, so a
+//! missing, malformed or out-of-range value fails config loading (and the
+//! Doppler CI validator) rather than a request. Hosts reading plain env vars
+//! parse the raw strings with [`parse_ai_pricing`].
-use crate::domain::AiUsageBilling;
+use crate::domain::{AiPricing, AiUsageBilling, IncludedAllowanceCents, OverageMarkupPercent};
+use rootcause::prelude::ResultExt as _;
+use serde::de::Error as _;
#[cfg(test)]
mod test;
+/// Doppler key for the in-plan allowance.
+pub const AI_USAGE_INCLUDED_ALLOWANCE_CENTS: &str = "AI_USAGE_INCLUDED_ALLOWANCE_CENTS";
+/// Doppler key for the overage markup.
+pub const AI_USAGE_OVERAGE_MARKUP_PERCENT: &str = "AI_USAGE_OVERAGE_MARKUP_PERCENT";
+
// Keep configuration deserialization outside the domain policy. MacroConfig
// parses the raw Doppler/environment value as a strict boolean.
impl<'de> serde::Deserialize<'de> for AiUsageBilling {
@@ -18,6 +39,54 @@ impl<'de> serde::Deserialize<'de> for AiUsageBilling {
}
}
+// The pricing newtypes deserialize from the raw Doppler number. MacroConfig
+// parses the string value as an integer; anything malformed or out of range
+// fails config loading, and so startup.
+impl<'de> serde::Deserialize<'de> for IncludedAllowanceCents {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let cents = i64::deserialize(deserializer)?;
+ Self::new(cents).map_err(|error| {
+ D::Error::custom(format!("{AI_USAGE_INCLUDED_ALLOWANCE_CENTS}: {error}"))
+ })
+ }
+}
+
+impl<'de> serde::Deserialize<'de> for OverageMarkupPercent {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let percent = i64::deserialize(deserializer)?;
+ Self::new(percent).map_err(|error| {
+ D::Error::custom(format!("{AI_USAGE_OVERAGE_MARKUP_PERCENT}: {error}"))
+ })
+ }
+}
+
+/// Build the pricing from the raw `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and
+/// `AI_USAGE_OVERAGE_MARKUP_PERCENT` values a host read itself. Hosts on
+/// MacroConfig declare the typed fields instead and need no parsing.
+///
+/// Both values are mandatory; the host must propagate an error to fail startup.
+pub fn parse_ai_pricing(
+ included_allowance_cents: &str,
+ overage_markup_percent: &str,
+) -> Result<AiPricing, rootcause::Report> {
+ let cents = included_allowance_cents
+ .trim()
+ .parse::<i64>()
+ .context(format!(
+ "{AI_USAGE_INCLUDED_ALLOWANCE_CENTS} must be a whole number of cents"
+ ))?;
+ let allowance =
+ IncludedAllowanceCents::new(cents).context(AI_USAGE_INCLUDED_ALLOWANCE_CENTS)?;
+ let percent = overage_markup_percent
+ .trim()
+ .parse::<i64>()
+ .context(format!(
+ "{AI_USAGE_OVERAGE_MARKUP_PERCENT} must be a whole percent"
+ ))?;
+ let markup = OverageMarkupPercent::new(percent).context(AI_USAGE_OVERAGE_MARKUP_PERCENT)?;
+ Ok(AiPricing::new(allowance, markup))
+}
+
/// Load `ENABLE_AI_USAGE_BILLING` once at service startup.
///
/// Missing means disabled. Only `true` and `false` are accepted when present;
diff --git a/crates/ai_billing/src/config/test.rs b/crates/ai_billing/src/config/test.rs
index 83508a3e2b..23f0e1e36c 100644
--- a/crates/ai_billing/src/config/test.rs
+++ b/crates/ai_billing/src/config/test.rs
@@ -25,3 +25,61 @@ fn default_policy_is_disabled() {
assert!(!AiUsageBilling::Disabled.is_enabled());
assert!(AiUsageBilling::Enabled.is_enabled());
}
+
+#[test]
+fn pricing_values_deserialize_from_integers_and_validate() {
+ let allowance: IncludedAllowanceCents =
+ serde_json::from_value(serde_json::json!(2_000)).unwrap();
+ assert_eq!(allowance.cents(), 2_000);
+ let markup: OverageMarkupPercent = serde_json::from_value(serde_json::json!(5)).unwrap();
+ assert_eq!(markup.percent(), 5);
+
+ let negative = serde_json::from_value::<IncludedAllowanceCents>(serde_json::json!(-1))
+ .unwrap_err()
+ .to_string();
+ assert!(
+ negative.contains(AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
+ "{negative}"
+ );
+ let too_high = serde_json::from_value::<OverageMarkupPercent>(serde_json::json!(100))
+ .unwrap_err()
+ .to_string();
+ assert!(
+ too_high.contains(AI_USAGE_OVERAGE_MARKUP_PERCENT),
+ "{too_high}"
+ );
+
+ // Absent, null, or non-integer values are configuration errors, never defaults.
+ for value in [
+ serde_json::json!(null),
+ serde_json::json!("2000"),
+ serde_json::json!(20.5),
+ serde_json::json!(true),
+ ] {
+ assert!(serde_json::from_value::<IncludedAllowanceCents>(value.clone()).is_err());
+ assert!(serde_json::from_value::<OverageMarkupPercent>(value).is_err());
+ }
+}
+
+#[test]
+fn raw_pricing_values_parse_and_validate() {
+ let pricing = parse_ai_pricing(" 2000 ", "5").unwrap();
+ assert_eq!(pricing.included_allowance_cents(), 2_000);
+ assert_eq!(pricing.overage_markup_percent(), 5);
+
+ for (allowance, markup, named) in [
+ ("", "5", AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
+ ("twenty dollars", "5", AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
+ ("-1", "5", AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
+ ("2000", "", AI_USAGE_OVERAGE_MARKUP_PERCENT),
+ ("2000", "5%", AI_USAGE_OVERAGE_MARKUP_PERCENT),
+ ("2000", "100", AI_USAGE_OVERAGE_MARKUP_PERCENT),
+ ("2000", "2.5", AI_USAGE_OVERAGE_MARKUP_PERCENT),
+ ] {
+ let error = parse_ai_pricing(allowance, markup).unwrap_err();
+ assert!(
+ format!("{error:?}").contains(named),
+ "{allowance:?}/{markup:?}: {error:?}"
+ );
+ }
+}
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
index 8b3f6f18a0..f50d3daddb 100644
--- a/crates/ai_billing/src/domain.rs
+++ b/crates/ai_billing/src/domain.rs
@@ -1,5 +1,5 @@
-//! Domain layer: plans and pricing constants, the settlement ledger, ports, and
-//! the billing service.
+//! Domain layer: plans and the configured pricing, the settlement ledger, ports,
+//! and the billing service.
pub mod admission;
pub mod financial;
@@ -29,7 +29,6 @@ pub use ports::{
PaymentGateway, PendingCharge, SettlementOutcome, SettlementTrigger, UsageReader,
};
pub use pricing::{
- INCLUDED_ALLOWANCE_CENTS, OVERAGE_MARKUP_PERCENT, cost_cents, cost_cents_covered_by,
- extra_customer_cents,
+ AiPricing, IncludedAllowanceCents, OverageMarkupPercent, PricingError, cost_cents,
};
pub use service::BillingServiceImpl;
diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rs
index b12187ea69..e90027ac65 100644
--- a/crates/ai_billing/src/domain/ledger.rs
+++ b/crates/ai_billing/src/domain/ledger.rs
@@ -29,7 +29,7 @@ use super::models::{
AllowanceDecision, BillingPeriod, BillingSettings, DenyReason, Entitlement,
MIN_STRIPE_CHARGE_CENTS, PeriodLedger, PlanTier, UsageSnapshot,
};
-use super::pricing::cost_cents_covered_by;
+use super::pricing::AiPricing;
use macro_user_id::user_id::MacroUserIdStr;
/// The overage policy in force for one settlement.
@@ -106,7 +106,8 @@ pub fn plan_settlement(state: SettlementState, policy: SettlementPolicy) -> Sett
/// Assemble the API-facing snapshot from the resolved inputs. `used_cost_cents`
/// is this seat's usage at cost; `shared_chargeable_customer_cents` is the
-/// payer's cumulative usage beyond all seat allowances, already marked up.
+/// payer's cumulative usage beyond all seat allowances, already marked up at
+/// `pricing`.
#[expect(
clippy::too_many_arguments,
reason = "snapshot assembly keeps its resolved billing inputs explicit"
@@ -120,8 +121,9 @@ pub fn build_snapshot(
shared_chargeable_customer_cents: i64,
ledger: PeriodLedger,
credit_balance_cents: i64,
+ pricing: AiPricing,
) -> UsageSnapshot {
- let included_cents = entitlement.included_ai_cents();
+ 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() {
@@ -137,7 +139,7 @@ pub fn build_snapshot(
+ credit_balance_cents.max(0)
+ overage_room)
.max(0);
- seat_remaining.saturating_add(cost_cents_covered_by(shared_headroom))
+ seat_remaining.saturating_add(pricing.cost_cents_covered_by(shared_headroom))
};
let mut snapshot = UsageSnapshot {
diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rs
index a3d35a8425..8b214a38a3 100644
--- a/crates/ai_billing/src/domain/ledger/test.rs
+++ b/crates/ai_billing/src/domain/ledger/test.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::domain::models::{OVERAGE_CHARGE_THRESHOLD_CENTS, PayerScope};
-use crate::domain::pricing::extra_customer_cents;
+use crate::domain::pricing::AiPricing;
use chrono::{TimeZone, Utc};
fn user(email: &str) -> MacroUserIdStr<'static> {
@@ -19,7 +19,8 @@ fn policy(active: bool, limit: i64, ended: bool) -> SettlementPolicy {
/// `used` and `included` are cost cents; the rest is customer money.
fn state(used: i64, included: i64, consumed: i64, charged: i64, balance: i64) -> SettlementState {
SettlementState {
- chargeable_customer_cents: extra_customer_cents((used - included).max(0)),
+ chargeable_customer_cents: AiPricing::testing()
+ .extra_customer_cents((used - included).max(0)),
credits_consumed_cents: consumed,
overage_charged_cents: charged,
credit_balance_cents: balance,
@@ -28,9 +29,18 @@ fn state(used: i64, included: i64, consumed: i64, charged: i64, balance: i64) ->
#[test]
fn included_allowance_is_the_same_at_cost_for_every_paid_seat() {
- assert_eq!(PlanTier::Premium.included_ai_cents_per_seat(), 2_000);
- assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), 2_000);
- assert_eq!(PlanTier::Free.included_ai_cents_per_seat(), 0);
+ assert_eq!(
+ PlanTier::Premium.included_ai_cents_per_seat(AiPricing::testing()),
+ 2_000
+ );
+ assert_eq!(
+ PlanTier::Max.included_ai_cents_per_seat(AiPricing::testing()),
+ 2_000
+ );
+ assert_eq!(
+ PlanTier::Free.included_ai_cents_per_seat(AiPricing::testing()),
+ 0
+ );
let mut team = Entitlement::personal(user("[email protected]"), PlanTier::Premium);
team.billed_users.push(user("[email protected]"));
@@ -41,9 +51,9 @@ fn included_allowance_is_the_same_at_cost_for_every_paid_seat() {
team_id: macro_uuid::generate_uuid_v7(),
};
assert_eq!(team.seats(), 3);
- assert_eq!(team.included_ai_cents(), 2_000);
+ assert_eq!(team.included_ai_cents(AiPricing::testing()), 2_000);
assert_eq!(
- team.seat_allowances()
+ team.seat_allowances(AiPricing::testing())
.into_iter()
.map(|seat| seat.included_cents)
.collect::<Vec<_>>(),
@@ -62,8 +72,8 @@ fn mixed_seat_plans_keep_one_allowance_per_seat() {
team_id: macro_uuid::generate_uuid_v7(),
};
assert_eq!(team.seats(), 3);
- assert_eq!(team.included_ai_cents(), 2_000);
- let allowances = team.seat_allowances();
+ assert_eq!(team.included_ai_cents(AiPricing::testing()), 2_000);
+ let allowances = team.seat_allowances(AiPricing::testing());
assert_eq!(
allowances
.iter()
@@ -159,7 +169,7 @@ fn settling_in_chunks_books_the_same_money_as_settling_once() {
assert_eq!(second.consume_credits_cents, 525);
assert_eq!(
first.consume_credits_cents + second.consume_credits_cents,
- extra_customer_cents(1_500)
+ AiPricing::testing().extra_customer_cents(1_500)
);
}
@@ -173,9 +183,18 @@ fn snapshot_for(
let u = user("[email protected]");
let ent = Entitlement::personal(u.clone(), tier);
let period = BillingPeriod::calendar_month(Utc::now());
- let chargeable = extra_customer_cents((used - ent.included_ai_cents()).max(0));
+ let chargeable = AiPricing::testing()
+ .extra_customer_cents((used - ent.included_ai_cents(AiPricing::testing())).max(0));
build_snapshot(
- &u, &ent, &settings, period, used, chargeable, ledger, balance,
+ &u,
+ &ent,
+ &settings,
+ period,
+ used,
+ chargeable,
+ ledger,
+ balance,
+ AiPricing::testing(),
)
}
@@ -331,9 +350,10 @@ fn free_and_unlimited_are_never_blocked() {
&BillingSettings::default(),
BillingPeriod::calendar_month(Utc::now()),
99_999,
- extra_customer_cents(97_999),
+ AiPricing::testing().extra_customer_cents(97_999),
PeriodLedger::default(),
0,
+ AiPricing::testing(),
);
assert_eq!(decide(&s), AllowanceDecision::Allow);
assert_eq!(s.remaining_cents, i64::MAX);
@@ -362,6 +382,7 @@ fn team_member_is_not_the_payer() {
0,
PeriodLedger::default(),
0,
+ AiPricing::testing(),
);
assert!(!s.can_manage_billing);
assert_eq!(s.seats, 2);
diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rs
index f4c35a1a52..2b5c9a5e80 100644
--- a/crates/ai_billing/src/domain/models.rs
+++ b/crates/ai_billing/src/domain/models.rs
@@ -1,6 +1,6 @@
//! Plans, billing periods, settings, and the API-facing snapshot.
-use super::pricing::INCLUDED_ALLOWANCE_CENTS;
+use super::pricing::AiPricing;
pub use ai_usage::NON_BILLABLE_AI_FEATURES;
use chrono::{DateTime, Datelike, Months, TimeZone, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -98,11 +98,12 @@ impl PlanTier {
}
}
- /// AI usage included per seat per period, in cents at provider cost
- /// ([`INCLUDED_ALLOWANCE_CENTS`] for every paid plan, nothing for Free).
- pub const fn included_ai_cents_per_seat(self) -> i64 {
+ /// AI usage included per seat per period, in cents at provider cost: the
+ /// configured allowance ([`AiPricing::included_allowance_cents`]) for every
+ /// paid plan, nothing for Free.
+ pub const fn included_ai_cents_per_seat(self, pricing: AiPricing) -> i64 {
if self.is_paid() {
- INCLUDED_ALLOWANCE_CENTS
+ pricing.included_allowance_cents()
} else {
0
}
@@ -357,13 +358,13 @@ impl Entitlement {
}
/// Included AI for this user's seat, in cents at provider cost.
- pub fn included_ai_cents(&self) -> i64 {
- self.tier.included_ai_cents_per_seat()
+ pub fn included_ai_cents(&self, pricing: AiPricing) -> i64 {
+ self.tier.included_ai_cents_per_seat(pricing)
}
/// Each billed seat with its own included AI. Unused allowance never moves
/// between seats; only credits and overage are shared by the payer.
- pub fn seat_allowances(&self) -> Vec<SeatAllowance> {
+ pub fn seat_allowances(&self, pricing: AiPricing) -> Vec<SeatAllowance> {
self.billed_users
.iter()
.enumerate()
@@ -371,7 +372,7 @@ impl Entitlement {
let tier = self.seat_tiers.get(index).copied().unwrap_or(self.tier);
SeatAllowance {
user: user.clone(),
- included_cents: tier.included_ai_cents_per_seat(),
+ included_cents: tier.included_ai_cents_per_seat(pricing),
}
})
.collect()
diff --git a/crates/ai_billing/src/domain/policy.rs b/crates/ai_billing/src/domain/policy.rs
index 4146ccc3a2..6b387cca4c 100644
--- a/crates/ai_billing/src/domain/policy.rs
+++ b/crates/ai_billing/src/domain/policy.rs
@@ -26,7 +26,7 @@ use super::models::{
BillingPeriod, BillingSettings, Entitlement, MIN_STRIPE_CHARGE_CENTS, NON_BILLABLE_AI_FEATURES,
OVERAGE_CHARGE_THRESHOLD_CENTS, PlanTier, UsagePolicy,
};
-use super::pricing::{INCLUDED_ALLOWANCE_CENTS, OVERAGE_MARKUP_PERCENT};
+use super::pricing::AiPricing;
#[cfg(test)]
mod test;
@@ -34,15 +34,22 @@ mod test;
const ZERO_PUBLIC: PublicUsage = PublicUsage::from_units(0);
const ZERO_MONEY: CustomerMoney = CustomerMoney::from_units(0);
const PUBLIC_UNITS_PER_CENT: u64 = CustomerMoney::UNITS_PER_CENT / 100;
-// Both figures come from `pricing`, so this policy and the ledger never disagree.
// A whole-percent markup over 100 prices every public unit exactly.
-const EXTRA_RATE_NUMERATOR: u64 = 100 + OVERAGE_MARKUP_PERCENT as u64;
const EXTRA_RATE_DENOMINATOR: u64 = 100;
/// Non-rolling public-provider-price allowance for each activated seat and
-/// period: [`INCLUDED_ALLOWANCE_CENTS`] of public usage.
-pub const INCLUDED_PUBLIC_USAGE: PublicUsage =
- PublicUsage::from_units(INCLUDED_ALLOWANCE_CENTS as u64 * PUBLIC_UNITS_PER_CENT);
+/// period: the configured allowance ([`AiPricing::included_allowance_cents`])
+/// of public usage. Both accounting paths read the same value, so this policy
+/// and the ledger never disagree.
+pub fn included_public_usage(pricing: AiPricing) -> PublicUsage {
+ // The allowance is validated non-negative at construction.
+ PublicUsage::from_units(pricing.included_allowance_cents() as u64 * PUBLIC_UNITS_PER_CENT)
+}
+
+fn extra_rate_numerator(pricing: AiPricing) -> u64 {
+ // The markup is validated to a whole percent below 100 at construction.
+ EXTRA_RATE_DENOMINATOR + pricing.overage_markup_percent() as u64
+}
/// Accounting path after a trusted caller resolves the recorded policy and entitlement.
/// This is not eligibility detection: a Premium role alone must never activate V1.
@@ -82,7 +89,7 @@ pub enum PricingCategory {
/// Public usage within the allowance: zero additional customer money, no markup.
Included,
/// Beyond the allowance: public usage multiplied by exactly
- /// `(100 + OVERAGE_MARKUP_PERCENT) / 100` (never divided by the complement).
+ /// `(100 + markup percent) / 100` (never divided by the complement).
Extra,
}
@@ -273,6 +280,7 @@ pub enum AllocationState {
/// Bounded admission for one provider attempt. Persist before acknowledging execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reservation {
+ pricing: AiPricing,
authorization: AuthorizationSnapshot,
sequence: AllocationSequence,
maximum_public_usage: PublicUsage,
@@ -351,19 +359,24 @@ impl UsageAllocation {
}
}
-fn remaining_included(used: PublicUsage) -> PublicUsage {
- PublicUsage::from_units(INCLUDED_PUBLIC_USAGE.units().saturating_sub(used.units()))
+fn remaining_included(pricing: AiPricing, used: PublicUsage) -> PublicUsage {
+ PublicUsage::from_units(
+ included_public_usage(pricing)
+ .units()
+ .saturating_sub(used.units()),
+ )
}
-fn extra_price(usage: PublicUsage) -> Result<CustomerMoney, PolicyError> {
+fn extra_price(pricing: AiPricing, usage: PublicUsage) -> Result<CustomerMoney, PolicyError> {
Ok(CustomerMoney::from_public_ratio(
usage,
- EXTRA_RATE_NUMERATOR,
+ extra_rate_numerator(pricing),
EXTRA_RATE_DENOMINATOR,
)?)
}
fn available_holds(
+ pricing: AiPricing,
authorization: &AuthorizationSnapshot,
available: FundingAvailability,
) -> Result<FundingHolds, PolicyError> {
@@ -381,6 +394,7 @@ fn available_holds(
};
Ok(FundingHolds {
included_public: remaining_included(
+ pricing,
available
.seat_public_used
.checked_add(available.seat_public_held)?,
@@ -394,13 +408,14 @@ fn available_holds(
/// admission bound, never actual usage/money. Hosts must lower their execution ceiling
/// before retrying a rejected admission; an oversized token budget is not authorized.
pub fn funded_capacity(
+ pricing: AiPricing,
authorization: &AuthorizationSnapshot,
maximum_public_usage: PublicUsage,
available: FundingAvailability,
) -> Result<PublicUsage, PolicyError> {
- let holds = available_holds(authorization, available)?;
+ let holds = available_holds(pricing, authorization, available)?;
let money = u128::from(holds.prepaid.units()) + u128::from(holds.postpaid.units());
- let money_per_public_unit = extra_price(PublicUsage::from_units(1))?.units();
+ let money_per_public_unit = extra_price(pricing, PublicUsage::from_units(1))?.units();
let public =
u128::from(holds.included_public.units()) + money / u128::from(money_per_public_unit);
Ok(PublicUsage::from_units(
@@ -410,7 +425,9 @@ pub fn funded_capacity(
/// Reserve the complete trusted per-attempt ceiling, credit-first. No partially funded
/// execution is admitted. A rejection carries the maximum affordable smaller ceiling.
+/// The reservation keeps `pricing`, so allocation prices usage as it was admitted.
pub fn reserve(
+ pricing: AiPricing,
authorization: AuthorizationSnapshot,
sequence: AllocationSequence,
maximum_public_usage: PublicUsage,
@@ -419,19 +436,20 @@ pub fn reserve(
if maximum_public_usage == ZERO_PUBLIC {
return Err(PolicyError::EmptyBudget);
}
- let capacity = funded_capacity(&authorization, maximum_public_usage, available)?;
+ let capacity = funded_capacity(pricing, &authorization, maximum_public_usage, available)?;
if maximum_public_usage > capacity {
return Err(PolicyError::InsufficientFunding {
maximum_public_usage: capacity,
});
}
let prior_prepaid_held = available.prepaid_held;
- let available = available_holds(&authorization, available)?;
+ let available = available_holds(pricing, &authorization, available)?;
let included_public = maximum_public_usage.min(available.included_public);
- let extra = extra_price(maximum_public_usage.checked_sub(included_public)?)?;
+ let extra = extra_price(pricing, maximum_public_usage.checked_sub(included_public)?)?;
let prepaid = extra.min(available.prepaid);
let postpaid = extra.checked_sub(prepaid)?;
Ok(Reservation {
+ pricing,
authorization,
sequence,
maximum_public_usage,
@@ -446,6 +464,11 @@ pub fn reserve(
}
impl Reservation {
+ /// The pricing captured when this attempt was admitted.
+ pub fn pricing(&self) -> AiPricing {
+ self.pricing
+ }
+
/// Captured facts, never a live settings lookup.
pub fn authorization(&self) -> &AuthorizationSnapshot {
&self.authorization
@@ -507,9 +530,10 @@ impl Reservation {
}
// Check the total the repository will persist before changing any state.
position.seat_public_used.checked_add(actual)?;
- let included_public = actual.min(remaining_included(position.seat_public_used));
+ let included_public =
+ actual.min(remaining_included(self.pricing, position.seat_public_used));
let extra_public = actual.checked_sub(included_public)?;
- let extra = extra_price(extra_public)?;
+ let extra = extra_price(self.pricing, extra_public)?;
let prepaid = extra.min(self.holds.prepaid);
let remainder = extra.checked_sub(prepaid)?;
let postpaid_budget = remainder.min(self.holds.postpaid);
diff --git a/crates/ai_billing/src/domain/policy/test.rs b/crates/ai_billing/src/domain/policy/test.rs
index f9a6bdf5a6..f64bd2d3cd 100644
--- a/crates/ai_billing/src/domain/policy/test.rs
+++ b/crates/ai_billing/src/domain/policy/test.rs
@@ -57,6 +57,7 @@ fn allocate_call(
enabled: bool,
) -> UsageAllocation {
let mut reservation = reserve(
+ AiPricing::testing(),
authorization(enabled),
AllocationSequence::from_raw(0),
actual,
@@ -94,17 +95,23 @@ fn pricing_table_and_enabled_does_not_mean_consumed() {
#[test]
fn opt_out_stops_at_exact_funded_capacity() {
let available = availability(ZERO_PUBLIC, money(1_000));
- let capacity = funded_capacity(&authorization(false), public_cents(3_000), available).unwrap();
+ let capacity = funded_capacity(
+ AiPricing::testing(),
+ &authorization(false),
+ public_cents(3_000),
+ available,
+ )
+ .unwrap();
assert_eq!(capacity.units(), 29_523_809_523_809);
assert!(matches!(
- reserve(authorization(false), AllocationSequence::from_raw(0), public_cents(3_000), available),
+ reserve(AiPricing::testing(), authorization(false), AllocationSequence::from_raw(0), public_cents(3_000), available),
Err(PolicyError::InsufficientFunding { maximum_public_usage }) if maximum_public_usage == capacity
));
let allocation = allocate_call(ZERO_PUBLIC, capacity, money(1_000), false);
assert!(allocation.prepaid <= money(1_000));
assert_eq!(allocation.postpaid, ZERO_MONEY);
assert!(matches!(
- reserve(authorization(false), AllocationSequence::from_raw(0), PublicUsage::from_units(1), availability(public_cents(2_000), ZERO_MONEY)),
+ reserve(AiPricing::testing(), authorization(false), AllocationSequence::from_raw(0), PublicUsage::from_units(1), availability(public_cents(2_000), ZERO_MONEY)),
Err(PolicyError::InsufficientFunding { maximum_public_usage }) if maximum_public_usage == ZERO_PUBLIC
));
}
@@ -122,7 +129,7 @@ fn threshold_crossing_and_fractional_credit_boundary_are_lossless() {
assert_eq!(allocation.prepaid.units(), 1);
assert_eq!(allocation.postpaid.units(), 1_050_000_000_000 - 1);
let tiny = allocate_call(
- PublicUsage::from_units(INCLUDED_PUBLIC_USAGE.units() - 1),
+ PublicUsage::from_units(included_public_usage(AiPricing::testing()).units() - 1),
PublicUsage::from_units(2),
ZERO_MONEY,
true,
@@ -141,8 +148,9 @@ fn threshold_crossing_and_fractional_credit_boundary_are_lossless() {
fn unused_holds_never_turn_included_usage_into_extra() {
for credits in [ZERO_MONEY, money(1_050)] {
let mut available = availability(ZERO_PUBLIC, credits);
- available.seat_public_held = INCLUDED_PUBLIC_USAGE;
+ available.seat_public_held = included_public_usage(AiPricing::testing());
let mut later = reserve(
+ AiPricing::testing(),
authorization(true),
AllocationSequence::from_raw(1),
public_cents(1_000),
@@ -172,6 +180,7 @@ fn unused_holds_never_turn_included_usage_into_extra() {
#[test]
fn release_is_terminal_and_unresolved_attempts_must_keep_their_holds() {
let mut reservation = reserve(
+ AiPricing::testing(),
authorization(false),
AllocationSequence::from_raw(0),
public_cents(100),
@@ -199,6 +208,7 @@ fn release_is_terminal_and_unresolved_attempts_must_keep_their_holds() {
#[test]
fn overshoot_is_macro_absorbed_not_unauthorized_debt() {
let mut reservation = reserve(
+ AiPricing::testing(),
authorization(false),
AllocationSequence::from_raw(0),
public_cents(2_000),
@@ -217,10 +227,11 @@ fn overshoot_is_macro_absorbed_not_unauthorized_debt() {
fn holds_and_incurred_liability_reduce_only_postpaid_cap_not_prepaid() {
let mut auth = authorization(true);
auth.postpaid = PostpaidAuthorization::Enabled { limit: money(500) };
- let mut available = availability(INCLUDED_PUBLIC_USAGE, money(105));
+ let mut available = availability(included_public_usage(AiPricing::testing()), money(105));
available.postpaid_incurred = money(300);
available.postpaid_held = money(200);
let mut reservation = reserve(
+ AiPricing::testing(),
auth,
AllocationSequence::from_raw(0),
public_cents(100),
@@ -230,7 +241,10 @@ fn holds_and_incurred_liability_reduce_only_postpaid_cap_not_prepaid() {
assert_eq!(reservation.holds().prepaid, money(105));
assert_eq!(reservation.holds().postpaid, ZERO_MONEY);
let allocation = reservation
- .allocate(position(0, INCLUDED_PUBLIC_USAGE), public_cents(200))
+ .allocate(
+ position(0, included_public_usage(AiPricing::testing())),
+ public_cents(200),
+ )
.unwrap();
assert_eq!(allocation.prepaid, money(105));
assert_eq!(allocation.postpaid, ZERO_MONEY);
@@ -241,23 +255,28 @@ fn holds_and_incurred_liability_reduce_only_postpaid_cap_not_prepaid() {
fn captured_authorization_survives_toggle_changes_without_retroactive_funding() {
let mut auth = authorization(true);
let mut reservation = reserve(
+ AiPricing::testing(),
auth.clone(),
AllocationSequence::from_raw(0),
public_cents(100),
- availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY),
+ availability(included_public_usage(AiPricing::testing()), ZERO_MONEY),
)
.unwrap();
auth.postpaid = PostpaidAuthorization::Disabled;
let allocation = reservation
- .allocate(position(0, INCLUDED_PUBLIC_USAGE), public_cents(100))
+ .allocate(
+ position(0, included_public_usage(AiPricing::testing())),
+ public_cents(100),
+ )
.unwrap();
assert_eq!(allocation.postpaid, money(105));
assert!(matches!(
reserve(
+ AiPricing::testing(),
auth,
AllocationSequence::from_raw(1),
public_cents(100),
- availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY)
+ availability(included_public_usage(AiPricing::testing()), ZERO_MONEY)
),
Err(PolicyError::InsufficientFunding { .. })
));
@@ -269,9 +288,10 @@ fn captured_authorization_survives_toggle_changes_without_retroactive_funding()
#[test]
fn released_earlier_credits_replace_provisional_postpaid_not_finalized_liability() {
- let mut available = availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY);
+ let mut available = availability(included_public_usage(AiPricing::testing()), ZERO_MONEY);
available.prepaid_held = money(105);
let mut later = reserve(
+ AiPricing::testing(),
authorization(true),
AllocationSequence::from_raw(1),
public_cents(100),
@@ -280,7 +300,7 @@ fn released_earlier_credits_replace_provisional_postpaid_not_finalized_liability
.unwrap();
assert_eq!(later.holds().postpaid, money(105));
assert_eq!(later.prepaid_reclaim_limit(), money(105));
- let mut at_turn = position(1, INCLUDED_PUBLIC_USAGE);
+ let mut at_turn = position(1, included_public_usage(AiPricing::testing()));
at_turn.prepaid_released_before = money(105);
let allocation = later.allocate(at_turn, public_cents(200)).unwrap();
assert_eq!(allocation.prepaid, money(105));
@@ -304,15 +324,16 @@ fn released_earlier_credits_replace_provisional_postpaid_not_finalized_liability
#[test]
fn new_credits_cannot_reclassify_captured_or_settled_sources() {
let mut reservation = reserve(
+ AiPricing::testing(),
authorization(true),
AllocationSequence::from_raw(0),
public_cents(100),
- availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY),
+ availability(included_public_usage(AiPricing::testing()), ZERO_MONEY),
)
.unwrap();
// No earlier credits existed at admission, so even an erroneous release input
// cannot use a subsequent purchase to displace the captured postpaid funding.
- let mut at_turn = position(0, INCLUDED_PUBLIC_USAGE);
+ let mut at_turn = position(0, included_public_usage(AiPricing::testing()));
at_turn.prepaid_released_before = money(105);
let allocation = reservation.allocate(at_turn, public_cents(100)).unwrap();
assert_eq!(allocation.prepaid, ZERO_MONEY);
@@ -340,18 +361,20 @@ fn captured_suspension_and_zero_cap_deny_only_new_postpaid() {
assert_eq!(auth.postpaid, PostpaidAuthorization::Suspended);
assert!(matches!(
reserve(
+ AiPricing::testing(),
auth.clone(),
AllocationSequence::from_raw(0),
public_cents(100),
- availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY)
+ availability(included_public_usage(AiPricing::testing()), ZERO_MONEY)
),
Err(PolicyError::InsufficientFunding { .. })
));
let prepaid = reserve(
+ AiPricing::testing(),
auth,
AllocationSequence::from_raw(0),
public_cents(100),
- availability(INCLUDED_PUBLIC_USAGE, money(105)),
+ availability(included_public_usage(AiPricing::testing()), money(105)),
)
.unwrap();
assert_eq!(prepaid.holds().prepaid, money(105));
@@ -418,6 +441,7 @@ fn checked_arithmetic_fails_without_partial_allocation_or_collection() {
));
assert!(matches!(
reserve(
+ AiPricing::testing(),
authorization(true),
AllocationSequence::from_raw(0),
ZERO_PUBLIC,
@@ -426,22 +450,23 @@ fn checked_arithmetic_fails_without_partial_allocation_or_collection() {
Err(PolicyError::EmptyBudget)
));
let mut reservation = reserve(
+ AiPricing::testing(),
authorization(true),
AllocationSequence::from_raw(0),
public_cents(1),
- availability(INCLUDED_PUBLIC_USAGE, ZERO_MONEY),
+ availability(included_public_usage(AiPricing::testing()), ZERO_MONEY),
)
.unwrap();
assert!(matches!(
reservation.allocate(
- position(0, INCLUDED_PUBLIC_USAGE),
+ position(0, included_public_usage(AiPricing::testing())),
PublicUsage::from_units(u64::MAX)
),
Err(PolicyError::Arithmetic(_))
));
assert_eq!(reservation.state(), ReservationState::Held);
assert!(matches!(
- extra_price(PublicUsage::from_units(u64::MAX)),
+ extra_price(AiPricing::testing(), PublicUsage::from_units(u64::MAX)),
Err(PolicyError::Arithmetic(_))
));
let mut collection =
@@ -450,7 +475,10 @@ fn checked_arithmetic_fails_without_partial_allocation_or_collection() {
assert_eq!(collection.exact_total().units(), u64::MAX);
// Measured zero is allocated, not silently treated as non-execution.
let zero = reservation
- .allocate(position(0, INCLUDED_PUBLIC_USAGE), ZERO_PUBLIC)
+ .allocate(
+ position(0, included_public_usage(AiPricing::testing())),
+ ZERO_PUBLIC,
+ )
.unwrap();
assert_eq!(zero.extra_money().unwrap(), ZERO_MONEY);
assert_eq!(reservation.state(), ReservationState::Consumed);
@@ -556,15 +584,23 @@ fn legacy_free_enterprise_and_exempt_features_keep_their_paths() {
AccountingRoute::Unmetered
);
assert_eq!(PlanTier::Premium.monthly_price_cents(), 4_000);
- // Both accounting paths read the same allowance constant.
- let allowance = super::super::pricing::INCLUDED_ALLOWANCE_CENTS;
- assert_eq!(PlanTier::Premium.included_ai_cents_per_seat(), allowance);
- assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), allowance);
- assert_eq!(INCLUDED_PUBLIC_USAGE, public_cents(allowance as u64));
+ // Both accounting paths read the same configured allowance.
+ let pricing = AiPricing::testing();
+ let allowance = pricing.included_allowance_cents();
+ assert_eq!(
+ PlanTier::Premium.included_ai_cents_per_seat(pricing),
+ allowance
+ );
+ assert_eq!(PlanTier::Max.included_ai_cents_per_seat(pricing), allowance);
+ assert_eq!(
+ included_public_usage(pricing),
+ public_cents(allowance as u64)
+ );
let mut auth = authorization(true);
auth.policy = UsagePolicy::Legacy;
assert!(matches!(
reserve(
+ AiPricing::testing(),
auth,
AllocationSequence::from_raw(0),
public_cents(100),
diff --git a/crates/ai_billing/src/domain/pricing.rs b/crates/ai_billing/src/domain/pricing.rs
index 1f5a71243d..1f88636433 100644
--- a/crates/ai_billing/src/domain/pricing.rs
+++ b/crates/ai_billing/src/domain/pricing.rs
@@ -1,35 +1,133 @@
-//! The two numbers GTM owns, and the conversions between provider cost and
+//! The two numbers GTM owns and the conversions between provider cost and
//! customer money that every billing path shares.
//!
//! Usage and the in-plan allowance are measured in **cost cents**: the
//! provider's public price for what was consumed, in whole cents. Credits,
//! overage charges, caps and credit packs are **customer cents**: what the
//! customer actually pays. The two meet only where usage runs past the
-//! allowance, which is marked up by [`OVERAGE_MARKUP_PERCENT`].
+//! allowance, which is marked up by [`AiPricing::overage_markup_percent`].
//!
-//! Change a constant and redeploy to change pricing. The exact-money
-//! public-allowance policy in [`super::policy`] derives its figures from the
-//! same two constants, so the ledger and that policy can never disagree.
+//! Neither number lives in code. Every host reads the mandatory
+//! `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and `AI_USAGE_OVERAGE_MARKUP_PERCENT`
+//! from Doppler at startup (see [`crate::config`]) and injects one
+//! [`AiPricing`] into each billing component it composes. Change the values in
+//! Doppler and redeploy to change pricing. The exact-money public-allowance
+//! policy in [`super::policy`] derives its figures from the same value, so the
+//! ledger and that policy can never disagree.
#[cfg(test)]
mod test;
+use thiserror::Error;
+
+/// Why a pricing value was refused.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
+pub enum PricingError {
+ /// The allowance must be zero or more cents.
+ #[error("included allowance must be at least 0 cents, got {0}")]
+ NegativeAllowance(i64),
+ /// The markup must be a whole percent from 0 to 99.
+ #[error("overage markup must be a whole percent from 0 to 99, got {0}")]
+ MarkupOutOfRange(i64),
+}
+
/// In-plan AI allowance per paid seat per billing period, in cents at
/// provider cost. The same for every paid plan until GTM defines otherwise.
-pub const INCLUDED_ALLOWANCE_CENTS: i64 = 2_000;
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct IncludedAllowanceCents(i64);
+
+impl IncludedAllowanceCents {
+ /// Validate an allowance: any non-negative number of cents.
+ pub const fn new(cents: i64) -> Result<Self, PricingError> {
+ if cents < 0 {
+ Err(PricingError::NegativeAllowance(cents))
+ } else {
+ Ok(Self(cents))
+ }
+ }
+
+ /// The allowance in cost cents.
+ pub const fn cents(self) -> i64 {
+ self.0
+ }
+}
/// Markup on usage beyond the allowance, as a whole percent of provider cost.
///
-/// Whole percents only: the exact-money path prices public usage over a
-/// denominator of 100 (`CustomerMoney::from_public_ratio`) and rejects finer
-/// rates at runtime.
-pub const OVERAGE_MARKUP_PERCENT: i64 = 5;
+/// Whole percents below 100 only: the exact-money path prices public usage
+/// over a denominator of 100 (`CustomerMoney::from_public_ratio`) and rejects
+/// finer rates at runtime.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct OverageMarkupPercent(i64);
-const _: () = assert!(INCLUDED_ALLOWANCE_CENTS >= 0);
-const _: () = assert!(OVERAGE_MARKUP_PERCENT >= 0 && OVERAGE_MARKUP_PERCENT < 100);
+impl OverageMarkupPercent {
+ /// Validate a markup: a whole percent from 0 to 99.
+ pub const fn new(percent: i64) -> Result<Self, PricingError> {
+ if percent < 0 || percent >= PERCENT {
+ Err(PricingError::MarkupOutOfRange(percent))
+ } else {
+ Ok(Self(percent))
+ }
+ }
+
+ /// The markup as a whole percent.
+ pub const fn percent(self) -> i64 {
+ self.0
+ }
+}
+
+/// The configured pricing. Allowance and markup travel together so no
+/// component can be composed with one and not the other.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct AiPricing {
+ included_allowance: IncludedAllowanceCents,
+ overage_markup: OverageMarkupPercent,
+}
const PERCENT: i64 = 100;
+impl AiPricing {
+ /// Combine two validated values.
+ pub const fn new(
+ included_allowance: IncludedAllowanceCents,
+ overage_markup: OverageMarkupPercent,
+ ) -> Self {
+ Self {
+ included_allowance,
+ overage_markup,
+ }
+ }
+
+ /// In-plan AI allowance per paid seat per period, in cents at provider cost.
+ pub const fn included_allowance_cents(self) -> i64 {
+ self.included_allowance.cents()
+ }
+
+ /// Markup on usage beyond the allowance, as a whole percent of provider cost.
+ pub const fn overage_markup_percent(self) -> i64 {
+ self.overage_markup.percent()
+ }
+
+ /// Customer cents owed for `cost_cents` of usage beyond the allowance.
+ ///
+ /// Apply this to a period's *cumulative* chargeable cost and book the
+ /// difference from what was already covered, never to each increment:
+ /// at 5%, `extra(1) + extra(1)` is 4 but `extra(2)` is 3.
+ pub fn extra_customer_cents(self, cost_cents: i64) -> i64 {
+ let marked_up = cost_cents
+ .max(0)
+ .saturating_mul(PERCENT + self.overage_markup_percent());
+ // Ceiling division; `i64::div_ceil` is not stable.
+ marked_up.saturating_add(PERCENT - 1) / PERCENT
+ }
+
+ /// The most cost cents of usage that `customer_cents` pays for at the
+ /// markup: the largest `cost` with `extra_customer_cents(cost) <= customer_cents`.
+ pub fn cost_cents_covered_by(self, customer_cents: i64) -> i64 {
+ customer_cents.max(0).saturating_mul(PERCENT) / (PERCENT + self.overage_markup_percent())
+ }
+}
+
/// Provider cost in USD to whole cents at cost, rounded up so fractions of a
/// cent never accrue in the customer's favour. Non-finite and non-positive
/// amounts are zero.
@@ -45,21 +143,13 @@ pub fn cost_cents(provider_cost_usd: f64) -> i64 {
(micro_cents / 1_000_000.0).ceil() as i64
}
-/// Customer cents owed for `cost_cents` of usage beyond the allowance.
-///
-/// Apply this to a period's *cumulative* chargeable cost and book the
-/// difference from what was already covered, never to each increment:
-/// `extra(1) + extra(1)` is 4 but `extra(2)` is 3.
-pub fn extra_customer_cents(cost_cents: i64) -> i64 {
- let marked_up = cost_cents
- .max(0)
- .saturating_mul(PERCENT + OVERAGE_MARKUP_PERCENT);
- // Ceiling division; `i64::div_ceil` is not stable.
- marked_up.saturating_add(PERCENT - 1) / PERCENT
-}
-
-/// The most cost cents of usage that `customer_cents` pays for at the markup:
-/// the largest `cost` with `extra_customer_cents(cost) <= customer_cents`.
-pub fn cost_cents_covered_by(customer_cents: i64) -> i64 {
- customer_cents.max(0).saturating_mul(PERCENT) / (PERCENT + OVERAGE_MARKUP_PERCENT)
+#[cfg(test)]
+impl AiPricing {
+ /// The $20 allowance and 5% markup the crate's tests assume.
+ pub(crate) fn testing() -> Self {
+ Self::new(
+ IncludedAllowanceCents::new(2_000).unwrap(),
+ OverageMarkupPercent::new(5).unwrap(),
+ )
+ }
}
diff --git a/crates/ai_billing/src/domain/pricing/test.rs b/crates/ai_billing/src/domain/pricing/test.rs
index 80d5f0bc99..bc75ec92b2 100644
--- a/crates/ai_billing/src/domain/pricing/test.rs
+++ b/crates/ai_billing/src/domain/pricing/test.rs
@@ -13,59 +13,125 @@ fn cost_cents_rounds_fractions_up_and_ignores_junk() {
assert_eq!(cost_cents(f64::INFINITY), 0);
}
+#[test]
+fn allowance_must_be_non_negative() {
+ assert_eq!(IncludedAllowanceCents::new(0).unwrap().cents(), 0);
+ assert_eq!(IncludedAllowanceCents::new(2_000).unwrap().cents(), 2_000);
+ assert_eq!(
+ IncludedAllowanceCents::new(-1),
+ Err(PricingError::NegativeAllowance(-1))
+ );
+}
+
+#[test]
+fn markup_must_be_a_whole_percent_below_one_hundred() {
+ assert_eq!(OverageMarkupPercent::new(0).unwrap().percent(), 0);
+ assert_eq!(OverageMarkupPercent::new(5).unwrap().percent(), 5);
+ assert_eq!(OverageMarkupPercent::new(99).unwrap().percent(), 99);
+ assert_eq!(
+ OverageMarkupPercent::new(100),
+ Err(PricingError::MarkupOutOfRange(100))
+ );
+ assert_eq!(
+ OverageMarkupPercent::new(-5),
+ Err(PricingError::MarkupOutOfRange(-5))
+ );
+}
+
+#[test]
+fn pricing_exposes_both_configured_values() {
+ let pricing = AiPricing::new(
+ IncludedAllowanceCents::new(3_500).unwrap(),
+ OverageMarkupPercent::new(12).unwrap(),
+ );
+ assert_eq!(pricing.included_allowance_cents(), 3_500);
+ assert_eq!(pricing.overage_markup_percent(), 12);
+ // A different markup prices the same cost differently.
+ assert_eq!(pricing.extra_customer_cents(1_000), 1_120);
+ assert_eq!(AiPricing::testing().extra_customer_cents(1_000), 1_050);
+}
+
#[test]
fn markup_rounds_up_on_the_cumulative_total() {
- assert_eq!(extra_customer_cents(0), 0);
- assert_eq!(extra_customer_cents(1), 2);
- assert_eq!(extra_customer_cents(19), 20);
- assert_eq!(extra_customer_cents(20), 21);
- assert_eq!(extra_customer_cents(1_000), 1_050);
- assert_eq!(extra_customer_cents(1_500), 1_575);
- assert_eq!(extra_customer_cents(-5), 0);
+ let pricing = AiPricing::testing();
+ assert_eq!(pricing.extra_customer_cents(0), 0);
+ assert_eq!(pricing.extra_customer_cents(1), 2);
+ assert_eq!(pricing.extra_customer_cents(19), 20);
+ assert_eq!(pricing.extra_customer_cents(20), 21);
+ assert_eq!(pricing.extra_customer_cents(1_000), 1_050);
+ assert_eq!(pricing.extra_customer_cents(1_500), 1_575);
+ assert_eq!(pricing.extra_customer_cents(-5), 0);
+}
+
+#[test]
+fn zero_markup_charges_cost_exactly() {
+ let pricing = AiPricing::new(
+ IncludedAllowanceCents::new(0).unwrap(),
+ OverageMarkupPercent::new(0).unwrap(),
+ );
+ for cost in [0, 1, 7, 1_000, 123_456] {
+ assert_eq!(pricing.extra_customer_cents(cost), cost);
+ assert_eq!(pricing.cost_cents_covered_by(cost), cost);
+ }
}
#[test]
fn cumulative_conversion_books_exact_increments() {
+ let pricing = AiPricing::testing();
// Settle at cost 1_000, then again at 1_500: the increments sum to extra(1_500).
- let first = extra_customer_cents(1_000);
- let second = extra_customer_cents(1_500) - first;
+ let first = pricing.extra_customer_cents(1_000);
+ let second = pricing.extra_customer_cents(1_500) - first;
assert_eq!((first, second), (1_050, 525));
- assert_eq!(first + second, extra_customer_cents(1_500));
+ assert_eq!(first + second, pricing.extra_customer_cents(1_500));
// Converting each increment on its own would overcharge.
- assert_eq!(extra_customer_cents(1) + extra_customer_cents(1), 4);
- assert_eq!(extra_customer_cents(2), 3);
+ assert_eq!(
+ pricing.extra_customer_cents(1) + pricing.extra_customer_cents(1),
+ 4
+ );
+ assert_eq!(pricing.extra_customer_cents(2), 3);
}
#[test]
fn covered_cost_is_the_exact_inverse_of_the_markup() {
- assert_eq!(cost_cents_covered_by(0), 0);
- assert_eq!(cost_cents_covered_by(1), 0);
- assert_eq!(cost_cents_covered_by(2), 1);
- assert_eq!(cost_cents_covered_by(104), 99);
- assert_eq!(cost_cents_covered_by(105), 100);
- assert_eq!(cost_cents_covered_by(-1), 0);
- for cost in 0..10_000 {
- assert_eq!(cost_cents_covered_by(extra_customer_cents(cost)), cost);
- }
- for customer in 0..10_000 {
- let covered = cost_cents_covered_by(customer);
- assert!(extra_customer_cents(covered) <= customer);
- assert!(customer < extra_customer_cents(covered + 1));
+ for markup in [0, 5, 17, 99] {
+ let pricing = AiPricing::new(
+ IncludedAllowanceCents::new(2_000).unwrap(),
+ OverageMarkupPercent::new(markup).unwrap(),
+ );
+ assert_eq!(pricing.cost_cents_covered_by(0), 0);
+ assert_eq!(pricing.cost_cents_covered_by(-1), 0);
+ for cost in 0..10_000 {
+ assert_eq!(
+ pricing.cost_cents_covered_by(pricing.extra_customer_cents(cost)),
+ cost
+ );
+ }
+ for customer in 0..10_000 {
+ let covered = pricing.cost_cents_covered_by(customer);
+ assert!(pricing.extra_customer_cents(covered) <= customer);
+ assert!(customer < pricing.extra_customer_cents(covered + 1));
+ }
}
+ let pricing = AiPricing::testing();
+ assert_eq!(pricing.cost_cents_covered_by(1), 0);
+ assert_eq!(pricing.cost_cents_covered_by(2), 1);
+ assert_eq!(pricing.cost_cents_covered_by(104), 99);
+ assert_eq!(pricing.cost_cents_covered_by(105), 100);
}
#[test]
-fn constants_feed_the_exact_money_policy() {
- use crate::domain::policy::INCLUDED_PUBLIC_USAGE;
+fn pricing_feeds_the_exact_money_policy() {
+ use crate::domain::policy::included_public_usage;
use ai_usage::domain::financial::{CustomerMoney, PublicUsage};
+ let pricing = AiPricing::testing();
let public_units_per_cent = CustomerMoney::UNITS_PER_CENT / 100;
assert_eq!(
- INCLUDED_PUBLIC_USAGE.units(),
- INCLUDED_ALLOWANCE_CENTS as u64 * public_units_per_cent
+ included_public_usage(pricing).units(),
+ pricing.included_allowance_cents() as u64 * public_units_per_cent
);
// A whole-percent markup over a denominator of 100 prices every public unit exactly.
- let numerator = (PERCENT + OVERAGE_MARKUP_PERCENT) as u64;
+ let numerator = (PERCENT + pricing.overage_markup_percent()) as u64;
let money =
CustomerMoney::from_public_ratio(PublicUsage::from_units(1), numerator, 100).unwrap();
assert_eq!(money.units(), numerator);
diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rs
index dcca3f2708..63ce667200 100644
--- a/crates/ai_billing/src/domain/service.rs
+++ b/crates/ai_billing/src/domain/service.rs
@@ -16,7 +16,7 @@ use super::ports::{
BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,
PaymentGateway, PendingCharge, UsageReader,
};
-use super::pricing::extra_customer_cents;
+use super::pricing::AiPricing;
use ai_usage::AiUsageEnforcement;
use chrono::{DateTime, Utc};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
@@ -31,26 +31,34 @@ pub struct BillingServiceImpl<E, U, R, P> {
usage: U,
repo: R,
payments: P,
+ pricing: AiPricing,
enforcement: AiUsageEnforcement,
billing: AiUsageBilling,
period_sync: Option<Arc<dyn PeriodSync>>,
}
impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {
- /// Construct with quota enforcement and settlement both disabled. Production
- /// composition must explicitly install each configured policy.
- pub fn new(entitlements: E, usage: U, repo: R, payments: P) -> Self {
+ /// Construct over the four ports with the configured pricing, and with quota
+ /// enforcement and settlement both disabled. Production composition must
+ /// explicitly install each configured policy.
+ pub fn new(entitlements: E, usage: U, repo: R, payments: P, pricing: AiPricing) -> Self {
Self {
entitlements,
usage,
repo,
payments,
+ pricing,
enforcement: AiUsageEnforcement::Disabled,
billing: AiUsageBilling::Disabled,
period_sync: None,
}
}
+ /// The pricing this service was composed with.
+ pub const fn pricing(&self) -> AiPricing {
+ self.pricing
+ }
+
/// Configure quota enforcement independently of settlement.
pub fn with_enforcement(mut self, enforcement: AiUsageEnforcement) -> Self {
self.enforcement = enforcement;
@@ -141,10 +149,9 @@ where
.repo
.period_allowance(&first.payer, open.start())
.await?;
- if stored
- .as_ref()
- .is_some_and(|allowance| same_seat_pairs(&allowance.seats, &first.seat_allowances()))
- {
+ if stored.as_ref().is_some_and(|allowance| {
+ same_seat_pairs(&allowance.seats, &first.seat_allowances(self.pricing))
+ }) {
return Ok(Position {
entitlement: first,
settings,
@@ -182,7 +189,7 @@ where
.store_open_allowance(
&entitlement.payer,
open,
- &entitlement.seat_allowances(),
+ &entitlement.seat_allowances(self.pricing),
settings.seat_generation,
)
.await?
@@ -207,7 +214,7 @@ where
} = position;
let (used_cents, chargeable_customer_cents, ledger, credit_balance_cents) =
if entitlement.tier.is_paid() {
- let seats = entitlement.seat_allowances();
+ let seats = entitlement.seat_allowances(self.pricing);
let users: Vec<_> = seats.iter().map(|seat| seat.user.clone()).collect();
let usage = self.usage.usage_cost_cents_by_user(&users, *period).await?;
let seats = self
@@ -219,7 +226,9 @@ where
} else {
0
};
- let chargeable = extra_customer_cents(chargeable_cost_cents(&seats, &usage));
+ let chargeable = self
+ .pricing
+ .extra_customer_cents(chargeable_cost_cents(&seats, &usage));
let ledger = self
.repo
.period_ledger(&entitlement.payer, period.start)
@@ -239,6 +248,7 @@ where
chargeable_customer_cents,
ledger,
credit_balance_cents,
+ self.pricing,
))
}
@@ -268,7 +278,7 @@ where
}
}
}
- Ok(entitlement.seat_allowances())
+ Ok(entitlement.seat_allowances(self.pricing))
}
/// Settle one period for a payer: book uncovered usage from credits, then
@@ -296,7 +306,7 @@ where
}
// Mark up the cumulative total, never an increment: the repository
// books the difference from what earlier settlements already covered.
- let chargeable_customer_cents = extra_customer_cents(chargeable_cost);
+ let chargeable_customer_cents = self.pricing.extra_customer_cents(chargeable_cost);
let outcome = self
.repo
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
index ef8a75fe22..4024f31977 100644
--- a/crates/ai_billing/src/domain/service/test.rs
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -588,9 +588,15 @@ fn premium_service_with(
let repo = FakeRepo::default();
let payments = FakePayments::default();
(
- BillingServiceImpl::new(ents, usage.clone(), repo.clone(), payments.clone())
- .with_enforcement(AiUsageEnforcement::Enabled)
- .with_billing(billing),
+ BillingServiceImpl::new(
+ ents,
+ usage.clone(),
+ repo.clone(),
+ payments.clone(),
+ AiPricing::testing(),
+ )
+ .with_enforcement(AiUsageEnforcement::Enabled)
+ .with_billing(billing),
repo,
payments,
usage,
@@ -642,6 +648,7 @@ async fn policy_activation_during_analytics_read_cannot_double_bill() {
ActivatingUsage(repo.clone()),
repo.clone(),
payments.clone(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
svc.settle(&user("[email protected]")).await.unwrap();
@@ -748,6 +755,7 @@ async fn default_disabled_gate_and_disabled_settlement_do_not_read_entitlements(
FakeUsage::default(),
FakeRepo::default(),
FakePayments::default(),
+ AiPricing::testing(),
);
assert_eq!(
svc.check_allowance(&user("[email protected]")).await.unwrap(),
@@ -1068,6 +1076,7 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {
FakeUsage::default(),
FakeRepo::default(),
FakePayments::default(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
@@ -1129,10 +1138,15 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {
let usage = FakeUsage::default();
usage.add(&member, Utc::now(), 3_000);
let repo = FakeRepo::default();
- let service =
- BillingServiceImpl::new(entitlements, usage, repo.clone(), FakePayments::default())
- .with_billing(AiUsageBilling::Enabled)
- .with_enforcement(AiUsageEnforcement::Enabled);
+ let service = BillingServiceImpl::new(
+ entitlements,
+ usage,
+ repo.clone(),
+ FakePayments::default(),
+ AiPricing::testing(),
+ )
+ .with_billing(AiUsageBilling::Enabled)
+ .with_enforcement(AiUsageEnforcement::Enabled);
let owner_snapshot = service.snapshot(&owner).await.unwrap();
assert_eq!(owner_snapshot.used_cents, 0);
@@ -1289,8 +1303,14 @@ fn anchored_premium(
};
let repo = FakeRepo::default();
let payments = FakePayments::default();
- let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone())
- .with_billing(AiUsageBilling::Enabled);
+ let svc = BillingServiceImpl::new(
+ ents.clone(),
+ usage.clone(),
+ repo.clone(),
+ payments.clone(),
+ AiPricing::testing(),
+ )
+ .with_billing(AiUsageBilling::Enabled);
let current_start = Utc::now() - chrono::Duration::days(3);
let current_end = current_start + chrono::Duration::days(30);
let current = BillingPeriod {
@@ -1435,8 +1455,14 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {
let usage = FakeUsage::default();
let repo = FakeRepo::default();
let payments = FakePayments::default();
- let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone())
- .with_billing(AiUsageBilling::Enabled);
+ let svc = BillingServiceImpl::new(
+ ents.clone(),
+ usage.clone(),
+ repo.clone(),
+ payments.clone(),
+ AiPricing::testing(),
+ )
+ .with_billing(AiUsageBilling::Enabled);
let current_start = Utc::now() - chrono::Duration::days(3);
let current_end = current_start + chrono::Duration::days(30);
let current = BillingPeriod {
@@ -1538,6 +1564,7 @@ async fn release_targets_the_payer_open_period() {
FakeUsage::default(),
repo.clone(),
FakePayments::default(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
@@ -1573,6 +1600,7 @@ async fn release_missing_team_leaves_allowances_unchanged() {
FakeUsage::default(),
repo.clone(),
FakePayments::default(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
@@ -1611,6 +1639,7 @@ async fn release_refuses_to_remove_the_payer() {
FakeUsage::default(),
repo.clone(),
FakePayments::default(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
@@ -1665,6 +1694,7 @@ async fn position_keeps_matching_pairs_in_their_stored_order() {
FakeUsage::default(),
repo.clone(),
FakePayments::default(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
@@ -1728,6 +1758,7 @@ async fn position_does_not_restore_a_member_released_between_entitlement_reads()
FakeUsage::default(),
repo.clone(),
FakePayments::default(),
+ AiPricing::testing(),
)
.with_billing(AiUsageBilling::Enabled);
diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rs
index 278636231f..979d140273 100644
--- a/crates/ai_billing/src/inbound/axum_router.rs
+++ b/crates/ai_billing/src/inbound/axum_router.rs
@@ -2,7 +2,7 @@
//! purchases, the plan catalog, and the internal settle hook.
use crate::domain::{
- BillingError, BillingService, CREDIT_PACKS_CENTS, OVERAGE_LIMIT_MAX_CENTS,
+ AiPricing, BillingError, BillingService, CREDIT_PACKS_CENTS, OVERAGE_LIMIT_MAX_CENTS,
OVERAGE_LIMIT_MIN_CENTS, PlanTier, UsageSnapshot,
};
use axum::{
@@ -167,11 +167,13 @@ pub struct SettleRequest {
pub user_id: String,
}
-/// Router state: the billing service plus the authorization state the
-/// extractors need.
+/// Router state: the billing service, the configured pricing the catalog
+/// publishes, and the authorization state the extractors need.
pub struct AiBillingRouterState<B, Auth> {
/// The billing service.
pub service: Arc<B>,
+ /// The pricing the host composed the billing service with.
+ pub pricing: AiPricing,
/// Authorization state for the request extractors.
pub authorization_state: MacroAuthorizationState<Auth>,
}
@@ -180,11 +182,18 @@ impl<B, Auth> Clone for AiBillingRouterState<B, Auth> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
+ pricing: self.pricing,
authorization_state: self.authorization_state.clone(),
}
}
}
+impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for AiPricing {
+ fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {
+ state.pricing
+ }
+}
+
impl<B, Auth> FromRef<AiBillingRouterState<B, Auth>> for Arc<B> {
fn from_ref(state: &AiBillingRouterState<B, Auth>) -> Self {
state.service.clone()
@@ -283,14 +292,14 @@ pub async fn get_summary_handler<B: BillingService, Auth: MacroAuthorizationServ
),
tag = "ai_billing"
)]
-pub async fn get_plans_handler() -> Json<PlanCatalogResponse> {
+pub async fn get_plans_handler(State(pricing): State<AiPricing>) -> Json<PlanCatalogResponse> {
Json(PlanCatalogResponse {
plans: [PlanTier::Free, PlanTier::Premium, PlanTier::Max]
.into_iter()
.map(|tier| PlanCatalogEntry {
tier,
monthly_price_cents: tier.monthly_price_cents(),
- included_ai_cents_per_seat: tier.included_ai_cents_per_seat(),
+ included_ai_cents_per_seat: tier.included_ai_cents_per_seat(pricing),
purchasable: SeatPlan::PURCHASABLE
.into_iter()
.any(|plan| PlanTier::from(plan) == tier),
diff --git a/crates/ai_billing/src/inbound/axum_router/test.rs b/crates/ai_billing/src/inbound/axum_router/test.rs
index 0e7a7fc165..58f810cf61 100644
--- a/crates/ai_billing/src/inbound/axum_router/test.rs
+++ b/crates/ai_billing/src/inbound/axum_router/test.rs
@@ -1,5 +1,6 @@
use super::{ReturnUrlError, get_plans_handler, validate_return_url};
-use crate::domain::{INCLUDED_ALLOWANCE_CENTS, PlanTier};
+use crate::domain::{AiPricing, PlanTier};
+use axum::extract::State;
#[test]
fn return_urls_must_be_https_on_the_calling_origin() {
@@ -49,7 +50,8 @@ fn return_urls_must_be_https_on_the_calling_origin() {
#[tokio::test]
async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {
- let plans = get_plans_handler().await.0.plans;
+ let pricing = AiPricing::testing();
+ let plans = get_plans_handler(State(pricing)).await.0.plans;
let summary = plans
.iter()
.map(|plan| (plan.tier, plan.purchasable, plan.included_ai_cents_per_seat))
@@ -60,8 +62,8 @@ async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {
summary,
vec![
(PlanTier::Free, false, 0),
- (PlanTier::Premium, true, INCLUDED_ALLOWANCE_CENTS),
- (PlanTier::Max, false, INCLUDED_ALLOWANCE_CENTS),
+ (PlanTier::Premium, true, pricing.included_allowance_cents()),
+ (PlanTier::Max, false, pricing.included_allowance_cents()),
]
);
}
diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rs
index 2bb581af6c..59535f86d0 100644
--- a/crates/ai_billing/src/lib.rs
+++ b/crates/ai_billing/src/lib.rs
@@ -11,26 +11,29 @@
//! in chunks. Both are priced at cost plus a small markup:
//!
//! ```text
-//! allowance = INCLUDED_ALLOWANCE_CENTS ($20 of provider cost per seat per period)
-//! extra = cost x (100 + OVERAGE_MARKUP_PERCENT) / 100 (5% over cost)
+//! allowance = AI_USAGE_INCLUDED_ALLOWANCE_CENTS (provider cost per seat per period)
+//! extra = cost x (100 + AI_USAGE_OVERAGE_MARKUP_PERCENT) / 100
//! ```
//!
-//! Both numbers live in [`domain::pricing`]; change a constant and redeploy.
-//! Usage and allowance are **cost cents**; credits, charges, caps and packs are
-//! **customer cents**. The conversions in that module are the only place the
-//! two units meet.
+//! Neither number lives in code. Both are mandatory Doppler values that every
+//! host loads at startup ([`config`]) into one [`AiPricing`] and injects into
+//! each billing component it composes ([`domain::pricing`]). Change them in
+//! Doppler and redeploy. Usage and allowance are **cost cents**; credits,
+//! charges, caps and packs are **customer cents**. The conversions on
+//! [`AiPricing`] are the only place the two units meet.
//!
//! # Layout
//!
-//! - [`domain`] — plan catalog, pricing constants, the settlement ledger (pure),
-//! ports, and the service.
+//! - [`domain`] — plan catalog, the configured pricing, the settlement ledger
+//! (pure), ports, and the service.
//! - [`outbound`] — Postgres repos over `ai_usage` and the billing tables, the
//! Stripe gateway, the roles + teams entitlement resolver, and the recorder
//! wrapper that triggers settlement after usage lands.
//! - [`inbound`] — the axum router (summary, overage settings, credit
//! checkout, internal settle).
-//! - [`config`] — the startup loader for `ENABLE_AI_USAGE_BILLING`, the
-//! default-off policy that gates settlement in every environment.
+//! - [`config`] — startup configuration: the mandatory pricing values and the
+//! `ENABLE_AI_USAGE_BILLING` loader, the default-off policy that gates
+//! settlement in every environment.
//!
//! The *payer* is the account that owns credits, overage settings, and the
//! Stripe customer: the personal subscriber, or the team owner for members
@@ -45,9 +48,9 @@ pub mod outbound;
pub use ai_usage::{AiFeature, AiUsageEnforcement};
pub use domain::{
- AdmissionFuture, AiAdmissionError, AiAdmissionService, AiUsageBilling, AllowanceDecision,
- BillingAdmissionService, BillingError, BillingPeriod, BillingService, BillingSettings,
- CREDIT_PACKS_CENTS, DenyReason, DisabledAiAdmissionService, Entitlement,
- INCLUDED_ALLOWANCE_CENTS, OVERAGE_MARKUP_PERCENT, PayerScope, PlanTier, UsageSnapshot,
- cost_cents, cost_cents_covered_by, extra_customer_cents,
+ AdmissionFuture, AiAdmissionError, AiAdmissionService, AiPricing, AiUsageBilling,
+ AllowanceDecision, BillingAdmissionService, BillingError, BillingPeriod, BillingService,
+ BillingSettings, CREDIT_PACKS_CENTS, DenyReason, DisabledAiAdmissionService, Entitlement,
+ IncludedAllowanceCents, OverageMarkupPercent, PayerScope, PlanTier, PricingError,
+ UsageSnapshot, cost_cents,
};
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rs
index abea815068..94830e8341 100644
--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs
+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs
@@ -6,7 +6,7 @@
//! model and is still written, with the same values, so a pre-cutover binary keeps
//! working during a deploy; it is never read here. A row whose cost column is
//! missing or does not match its roster was frozen by that older binary, and
-//! every seat in it is priced at the current allowance.
+//! every seat in it is priced at the configured allowance.
#[cfg(test)]
mod test;
@@ -14,10 +14,9 @@ mod test;
use super::pg_funding_repo::{credit_commitments, lock_payer, postpaid_commitments};
use crate::domain::financial::legacy_cap_remaining;
use crate::domain::{
- AllowanceStore, BillingError, BillingRepo, BillingSettings, INCLUDED_ALLOWANCE_CENTS,
- OpenPeriodStart, OverageChargeStatus, PendingCharge, PeriodAllowance, PeriodLedger, Result,
- SeatAllowance, SeatGeneration, SettlementOutcome, SettlementPolicy, SettlementState,
- plan_settlement,
+ AiPricing, AllowanceStore, BillingError, BillingRepo, BillingSettings, OpenPeriodStart,
+ OverageChargeStatus, PendingCharge, PeriodAllowance, PeriodLedger, Result, SeatAllowance,
+ SeatGeneration, SettlementOutcome, SettlementPolicy, SettlementState, plan_settlement,
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -29,12 +28,14 @@ use std::str::FromStr;
#[derive(Clone)]
pub struct PgBillingRepo {
pool: PgPool,
+ pricing: AiPricing,
}
impl PgBillingRepo {
- /// Create a repo over a connection pool.
- pub fn new(pool: PgPool) -> Self {
- Self { pool }
+ /// Create a repo over a connection pool. `pricing` prices frozen rosters
+ /// that predate the per-seat cost column.
+ pub fn new(pool: PgPool, pricing: AiPricing) -> Self {
+ Self { pool, pricing }
}
}
@@ -230,7 +231,11 @@ impl BillingRepo for PgBillingRepo {
.map_err(storage)?;
row.map(|r| {
Ok(PeriodAllowance {
- seats: parse_seat_allowances(r.billed_users, r.included_cost_cents_by_user)?,
+ seats: parse_seat_allowances(
+ r.billed_users,
+ r.included_cost_cents_by_user,
+ self.pricing,
+ )?,
})
})
.transpose()
@@ -727,14 +732,15 @@ async fn read_period_ledger(
/// Pair a frozen roster with its cost-cent allowances. A missing or mismatched
/// cost array means an older binary wrote the row; every seat then gets the
-/// current allowance, which is what that binary's seats are entitled to now.
+/// configured allowance, which is what that binary's seats are entitled to now.
fn parse_seat_allowances(
billed_users: Vec<String>,
included_cost_cents_by_user: Option<Vec<i64>>,
+ pricing: AiPricing,
) -> Result<Vec<SeatAllowance>> {
let included_cents_by_user = match included_cost_cents_by_user {
Some(cents) if cents.len() == billed_users.len() => cents,
- _ => vec![INCLUDED_ALLOWANCE_CENTS; billed_users.len()],
+ _ => vec![pricing.included_allowance_cents(); billed_users.len()],
};
billed_users
.into_iter()
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
index cd0c8025e0..29a706a8c1 100644
--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs
@@ -9,7 +9,7 @@ fn payer() -> MacroUserIdStr<'static> {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn legacy_anchor_accepts_end_corrections_but_not_stale_or_overlapping_starts(pool: PgPool) {
- let repo = PgBillingRepo::new(pool);
+ let repo = PgBillingRepo::new(pool, AiPricing::testing());
let start = DateTime::from_timestamp(1_800_000_000, 0).unwrap();
let end = start + chrono::Duration::days(30);
repo.set_period(&payer(), start, end).await.unwrap();
@@ -71,7 +71,7 @@ async fn charge_rows(pool: &PgPool) -> i64 {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn settings_default_and_roundtrip(pool: PgPool) {
- let repo = PgBillingRepo::new(pool);
+ let repo = PgBillingRepo::new(pool, AiPricing::testing());
assert_eq!(
repo.settings(&payer()).await.unwrap(),
BillingSettings::default()
@@ -120,7 +120,7 @@ async fn settings_default_and_roundtrip(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn credit_purchases_are_idempotent_on_stripe_reference(pool: PgPool) {
- let repo = PgBillingRepo::new(pool);
+ let repo = PgBillingRepo::new(pool, AiPricing::testing());
assert!(
repo.record_credit_purchase(&payer(), 2_500, "cs_a")
.await
@@ -142,7 +142,7 @@ async fn credit_purchases_are_idempotent_on_stripe_reference(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn settlement_consumes_credits_then_reserves_overage(pool: PgPool) {
- let repo = PgBillingRepo::new(pool);
+ let repo = PgBillingRepo::new(pool, AiPricing::testing());
let period_start = Utc::now() - chrono::Duration::days(10);
repo.record_credit_purchase(&payer(), 500, "cs_1")
.await
@@ -205,7 +205,7 @@ async fn settlement_consumes_credits_then_reserves_overage(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn invoice_webhooks_apply_out_of_order_without_unpaying(pool: PgPool) {
- let repo = PgBillingRepo::new(pool);
+ let repo = PgBillingRepo::new(pool, AiPricing::testing());
let period_start = Utc::now() - chrono::Duration::days(10);
repo.update_overage(&payer(), true, 10_000).await.unwrap();
let pending = repo
@@ -270,7 +270,7 @@ async fn invoice_webhooks_apply_out_of_order_without_unpaying(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn settlement_retries_a_failed_charge_instead_of_reserving_a_new_one(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ 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();
@@ -315,7 +315,7 @@ async fn settlement_retries_a_failed_charge_instead_of_reserving_a_new_one(pool:
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn credits_can_replace_a_failed_charge_that_was_never_invoiced(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ 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();
@@ -352,7 +352,7 @@ async fn credits_can_replace_a_failed_charge_that_was_never_invoiced(pool: PgPoo
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn credits_do_not_replace_a_failed_charge_with_a_collectible_invoice(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ 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();
@@ -401,7 +401,7 @@ async fn credits_do_not_replace_a_failed_charge_with_a_collectible_invoice(pool:
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn settlement_collects_a_reservation_whose_collector_died(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ 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();
@@ -440,7 +440,7 @@ async fn settlement_collects_a_reservation_whose_collector_died(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn settlement_uses_stored_overage_policy_and_flushes_at_period_end(pool: PgPool) {
- let repo = PgBillingRepo::new(pool);
+ let repo = PgBillingRepo::new(pool, AiPricing::testing());
let period_start = Utc::now() - chrono::Duration::days(40);
repo.update_overage(&payer(), true, 600).await.unwrap();
@@ -470,7 +470,7 @@ async fn settlement_uses_stored_overage_policy_and_flushes_at_period_end(pool: P
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());
let payer = payer();
let now = Utc::now()
.duration_trunc(chrono::Duration::microseconds(1))
@@ -618,7 +618,7 @@ async fn seat_generation(pool: &PgPool, payer: &str) -> Option<i64> {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn release_open_seat_removes_the_middle_pair_and_leaves_the_closed_row(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());
let payer = payer();
let now = Utc::now();
let open_start = (now - chrono::Duration::days(1))
@@ -735,7 +735,7 @@ async fn release_open_seat_removes_the_middle_pair_and_leaves_the_closed_row(poo
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn store_open_allowance_does_not_write_a_stale_generation(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());
let now = Utc::now();
let open = BillingPeriod {
start: (now - chrono::Duration::days(1))
@@ -814,7 +814,7 @@ async fn store_open_allowance_does_not_write_a_stale_generation(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn release_open_seat_without_an_allowance_row_bumps_generation(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());
let now = Utc::now();
let open = BillingPeriod {
start: (now - chrono::Duration::days(1))
@@ -861,7 +861,7 @@ async fn release_open_seat_without_an_allowance_row_bumps_generation(pool: PgPoo
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn rows_frozen_before_the_cost_column_read_as_the_current_allowance(pool: PgPool) {
- let repo = PgBillingRepo::new(pool.clone());
+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());
let payer = payer();
let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
let users = vec![payer.as_ref().to_string(), member.as_ref().to_string()];
@@ -914,11 +914,11 @@ async fn rows_frozen_before_the_cost_column_read_as_the_current_allowance(pool:
vec![
SeatAllowance {
user: payer.clone(),
- included_cents: INCLUDED_ALLOWANCE_CENTS,
+ included_cents: AiPricing::testing().included_allowance_cents(),
},
SeatAllowance {
user: member.clone(),
- included_cents: INCLUDED_ALLOWANCE_CENTS,
+ included_cents: AiPricing::testing().included_allowance_cents(),
},
]
);
diff --git a/crates/ai_billing/src/outbound/pg_funding_repo.rs b/crates/ai_billing/src/outbound/pg_funding_repo.rs
index 966738bba0..d849c12b47 100644
--- a/crates/ai_billing/src/outbound/pg_funding_repo.rs
+++ b/crates/ai_billing/src/outbound/pg_funding_repo.rs
@@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::{PgConnection, PgPool, types::Json};
+use crate::domain::AiPricing;
use crate::domain::financial::*;
use crate::domain::models::{BillingPeriod, UsagePolicy};
use crate::domain::period::{
@@ -27,12 +28,14 @@ mod test;
#[derive(Clone)]
pub struct PgFundingRepo {
pool: PgPool,
+ pricing: AiPricing,
}
impl PgFundingRepo {
- /// Share the same database/payer account lock as `PgBillingRepo`.
- pub fn new(pool: PgPool) -> Self {
- Self { pool }
+ /// Share the same database/payer account lock as `PgBillingRepo`. New
+ /// admissions are priced at `pricing`.
+ pub fn new(pool: PgPool, pricing: AiPricing) -> Self {
+ Self { pool, pricing }
}
}
@@ -370,6 +373,7 @@ impl FundingRepo for PgFundingRepo {
let available = availability(&mut tx, &period).await?;
let maximum = rate.tokens.price(request.token_budget)?;
let reservation = match reserve(
+ self.pricing,
snapshot,
AllocationSequence::from_raw(units(account.next_sequence)?),
maximum,
@@ -448,7 +452,7 @@ impl FundingRepo for PgFundingRepo {
sqlx::query!("UPDATE ai_funding_reservation SET completion = $2, actual_public = $3 WHERE invocation_id = $1",
id.as_uuid(), completion, actual).execute(&mut *tx).await?;
}
- reconcile_locked(&mut tx, &row.payer_id).await?;
+ reconcile_locked(&mut tx, &row.payer_id, self.pricing).await?;
tx.commit().await?;
Ok(())
})
@@ -491,7 +495,7 @@ impl FundingRepo for PgFundingRepo {
Box::pin(async move {
let mut tx = self.pool.begin().await?;
lock_payer(&mut tx, payer.as_ref()).await?;
- reconcile_locked(&mut tx, payer.as_ref()).await?;
+ reconcile_locked(&mut tx, payer.as_ref(), self.pricing).await?;
tx.commit().await?;
Ok(())
})
@@ -552,7 +556,11 @@ async fn availability(
/// Bounded work makes a large ready backlog restart-safe without unbounded transactions.
/// Unresolved evidence stops the watermark and retains every later hold.
-async fn reconcile_locked(conn: &mut PgConnection, payer: &str) -> FinancialResult<()> {
+async fn reconcile_locked(
+ conn: &mut PgConnection,
+ payer: &str,
+ pricing: AiPricing,
+) -> FinancialResult<()> {
for _ in 0..100 {
let row = sqlx::query!(
r#"SELECT r.invocation_id, r.sequence, r.user_id, r.period_start, r.actual_public,
@@ -582,7 +590,7 @@ async fn reconcile_locked(conn: &mut PgConnection, payer: &str) -> FinancialResu
.try_fold(CustomerMoney::from_units(0), |total, r| {
total.checked_add(CustomerMoney::from_units(units(r.units)?))
})?;
- let mut reservation = row.admission.reservation()?;
+ let mut reservation = row.admission.reservation(pricing)?;
let allocation = reservation
.allocate(
AllocationPosition {
@@ -723,9 +731,10 @@ impl AdmissionData {
})
}
- fn reservation(&self) -> FinancialResult<Reservation> {
+ fn reservation(&self, pricing: AiPricing) -> FinancialResult<Reservation> {
let [used, held, prepaid, prepaid_held, incurred, postpaid_held] = self.available;
reserve(
+ pricing,
AuthorizationSnapshot {
id: self.id.try_into()?,
invocation_id: self.invocation_id.try_into()?,
diff --git a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs b/crates/ai_billing/src/outbound/pg_funding_repo/test.rs
index 4188e0ac3e..d27176fa51 100644
--- a/crates/ai_billing/src/outbound/pg_funding_repo/test.rs
+++ b/crates/ai_billing/src/outbound/pg_funding_repo/test.rs
@@ -56,8 +56,8 @@ fn next_renewal(mut observation: SeatPeriodObservation) -> SeatPeriodObservation
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn verified_renewal_freezes_history_and_preserves_shared_money(pool: PgPool) {
- let repo = PgFundingRepo::new(pool.clone());
- let billing = PgBillingRepo::new(pool);
+ let repo = PgFundingRepo::new(pool.clone(), AiPricing::testing());
+ let billing = PgBillingRepo::new(pool, AiPricing::testing());
let (rollout, baseline) = rollout_observation();
billing
.update_overage(&user("payer"), true, 5000)
@@ -141,8 +141,8 @@ async fn verified_renewal_freezes_history_and_preserves_shared_money(pool: PgPoo
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn cancellation_departure_and_rejoin_cannot_replenish_allowance(pool: PgPool) {
- let repo = PgFundingRepo::new(pool.clone());
- let billing = PgBillingRepo::new(pool);
+ let repo = PgFundingRepo::new(pool.clone(), AiPricing::testing());
+ let billing = PgBillingRepo::new(pool, AiPricing::testing());
let (rollout, baseline) = rollout_observation();
repo.observe(&rollout, baseline.clone(), true)
.await
@@ -195,8 +195,8 @@ async fn cancellation_departure_and_rejoin_cannot_replenish_allowance(pool: PgPo
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn activation_exceptions_are_durable_and_mixed_policy_seats_stay_separate(pool: PgPool) {
- let repo = PgFundingRepo::new(pool.clone());
- let billing = PgBillingRepo::new(pool.clone());
+ let repo = PgFundingRepo::new(pool.clone(), AiPricing::testing());
+ let billing = PgBillingRepo::new(pool.clone(), AiPricing::testing());
let (rollout, baseline) = rollout_observation();
let mut delayed = baseline.clone();
delayed.subscription.event_id = "evt_pre_rollout".parse().unwrap();
@@ -261,7 +261,7 @@ async fn activation_exceptions_are_durable_and_mixed_policy_seats_stay_separate(
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn late_seat_uses_existing_item_proof_but_cannot_renew_it(pool: PgPool) {
- let repo = PgFundingRepo::new(pool);
+ let repo = PgFundingRepo::new(pool, AiPricing::testing());
let (rollout, baseline) = rollout_observation();
repo.observe(&rollout, baseline.clone(), true)
.await
@@ -297,8 +297,8 @@ async fn late_seat_uses_existing_item_proof_but_cannot_renew_it(pool: PgPool) {
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn delayed_renewal_does_not_convert_a_legacy_period_already_in_use(pool: PgPool) {
- let repo = PgFundingRepo::new(pool.clone());
- let billing = PgBillingRepo::new(pool);
+ let repo = PgFundingRepo::new(pool.clone(), AiPricing::testing());
+ let billing = PgBillingRepo::new(pool, AiPricing::testing());
let (rollout, baseline) = rollout_observation();
repo.observe(&rollout, baseline.clone(), true)
.await
@@ -432,8 +432,8 @@ async fn setup(
enabled: bool,
cap: i64,
) -> (PgFundingRepo, PgBillingRepo) {
- let funding = PgFundingRepo::new(pool.clone());
- let billing = PgBillingRepo::new(pool.clone());
+ let funding = PgFundingRepo::new(pool.clone(), AiPricing::testing());
+ let billing = PgBillingRepo::new(pool.clone(), AiPricing::testing());
funding.record_period(period()).await.unwrap();
billing
.update_overage(&user("payer"), enabled, cap)
@@ -704,7 +704,7 @@ async fn bounded_reconciliation_resumes_after_restart(pool: PgPool) {
repo.finalize(completed(admission, 1)).await.unwrap();
}
assert!(repo.allocation(last).await.unwrap().is_none());
- let restarted = PgFundingRepo::new(pool);
+ let restarted = PgFundingRepo::new(pool, AiPricing::testing());
let pending = restarted
.pending(PendingInvocations {
after: None,
diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rs
index 5f62c85f4d..f770e68f8f 100644
--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs
+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::domain::{
- AllowanceDecision, BillingPeriod, BillingSettings, Entitlement, PlanTier, Result,
+ AiPricing, AllowanceDecision, BillingPeriod, BillingSettings, Entitlement, PlanTier, Result,
UsageSnapshot, ledger::build_snapshot,
};
use ai_usage::domain::{Result as UsageResult, UsageError};
@@ -164,6 +164,7 @@ async fn record_with_policy(
chargeable_cents,
Default::default(),
0,
+ AiPricing::testing(),
),
});
let trigger = FakeTrigger::default();
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index e2b20699ce..e3aea8151e 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -132,6 +132,8 @@ pub fn build_image_generator_from_env() -> Arc<dyn ImageGenerator> {
///
/// `enforcement` is validated by the host at startup and shared with all other
/// AI entry points. It configures both quota admission and prospective counting.
+/// `pricing` is the host's mandatory AI pricing configuration, shared with every
+/// other billing component it composes.
///
/// `event_task_tracker` tracks event publishes started by the context. Callers
/// must retain the original tracker, pass a clone here, and close and drain the
@@ -141,6 +143,7 @@ pub async fn build_tool_service_context_from_env(
pool: sqlx::PgPool,
event_task_tracker: TaskTracker,
enforcement: ai_usage::AiUsageEnforcement,
+ pricing: ai_billing::AiPricing,
) -> anyhow::Result<ToolServiceContext> {
let env = ToolContextEnvVars::new()?;
let maybe_env = ToolContextMaybeEnvVars::new();
@@ -527,7 +530,11 @@ pub async fn build_tool_service_context_from_env(
skill_tool_context,
schedule_tool_context: crate::build_routine_tool_context()?,
anthropic_tool_context,
- admission: ai_billing::composition::pg_admission_service(pool.clone(), enforcement),
+ admission: ai_billing::composition::pg_admission_service(
+ pool.clone(),
+ enforcement,
+ pricing,
+ ),
recorder,
usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
})
diff --git a/crates/memory/Cargo.toml b/crates/memory/Cargo.toml
index 5220b5474d..9c7e31e5a9 100644
--- a/crates/memory/Cargo.toml
+++ b/crates/memory/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dependencies]
+ai_billing = { path = "../ai_billing" }
rootcause = { workspace = true }
agent = { path = "../agent" }
ai_usage = { path = "../ai_usage" }
diff --git a/crates/memory/src/config.rs b/crates/memory/src/config.rs
index d5e8621230..9f355ce914 100644
--- a/crates/memory/src/config.rs
+++ b/crates/memory/src/config.rs
@@ -3,6 +3,8 @@ use macro_env_var::env_var;
pub struct Config {
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// The mandatory AI pricing shared with every other billing host.
+ pub ai_pricing: ai_billing::AiPricing,
pub environment: Environment,
pub database_url: String,
pub user_id: String,
@@ -12,6 +14,10 @@ env_var!(
pub struct EnvVars {
pub DatabaseUrl,
pub UserId,
+ /// In-plan AI allowance per paid seat per period, cents at provider cost.
+ pub AiUsageIncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, a whole percent of provider cost.
+ pub AiUsageOverageMarkupPercent,
}
);
@@ -25,10 +31,18 @@ impl Config {
let EnvVars {
database_url,
user_id,
+ ai_usage_included_allowance_cents,
+ ai_usage_overage_markup_percent,
} = env_vars;
+ let ai_pricing = ai_billing::config::parse_ai_pricing(
+ &ai_usage_included_allowance_cents,
+ &ai_usage_overage_markup_percent,
+ )
+ .map_err(|error| anyhow::anyhow!("{error}"))?;
Ok(Self {
enable_ai_usage_enforcement,
+ ai_pricing,
environment,
database_url: database_url.to_string(),
user_id: user_id.to_string(),
diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rs
index d1466e70a1..2dc1968250 100644
--- a/crates/memory/src/context.rs
+++ b/crates/memory/src/context.rs
@@ -18,6 +18,7 @@ pub async fn build_tool_service_context(
pool,
event_task_tracker,
config.enable_ai_usage_enforcement,
+ config.ai_pricing,
)
.await
}
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 6533ff7db1..253a44dd27 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -525,9 +525,10 @@ must not make a fallback model call. Managed sessions use their persisted owner
for quota, not a collaborating sender. Externally funded runtimes skip session
quota, but Macro-funded tools and helpers still check independently.
-In dev, paid plans include a monthly AI allowance of $20 per seat, measured at
-provider cost; usage beyond it is billed at a small markup (both are constants in
-`crates/ai_billing/src/domain/pricing.rs`). When it is used up and no credits or usage billing cover the
+Paid plans include a monthly AI allowance per seat, measured at provider cost;
+usage beyond it is billed at a markup. Both numbers come from Doppler
+(`AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and `AI_USAGE_OVERAGE_MARKUP_PERCENT`; $20 and
+5% in dev), never from code. When the allowance is used up and no credits or usage billing cover the
request, sending a message answers HTTP 402 and the app opens the
**AI usage limit** dialog (title `You've used this month's included AI`, or the
spending-limit / failed-charge variants). It shows the same meter and controls
diff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.md
index 4465037a58..0bb6ebb0fc 100644
--- a/docs/AI_QUOTA_ENFORCEMENT.md
+++ b/docs/AI_QUOTA_ENFORCEMENT.md
@@ -69,18 +69,24 @@ independent of `ENABLE_AI_USAGE_ENFORCEMENT` and of the deployment environment:
there is no longer an `Environment::Develop` safeguard, so a true value settles
in production.
-Pricing is two constants in
-[`pricing.rs`](../crates/ai_billing/src/domain/pricing.rs): each paid seat includes
-`INCLUDED_ALLOWANCE_CENTS` ($20) of usage per period measured at provider cost, and
-usage beyond that is converted to customer money at `OVERAGE_MARKUP_PERCENT` (5%)
-over cost before credits are consumed or overage is charged. The markup is applied
-to the period's cumulative chargeable cost, so settling in chunks books the same
-money as settling once. Change a constant and redeploy to change pricing. The
-plan catalog (`GET /ai-billing/plans`) publishes `included_ai_cents_per_seat`
-for every tier, and the frontend reads allowances from it
+Pricing is two mandatory Doppler values, loaded once at startup by every host that
+composes `ai_billing` (see [`config.rs`](../crates/ai_billing/src/config.rs) and
+[`pricing.rs`](../crates/ai_billing/src/domain/pricing.rs)):
+`AI_USAGE_INCLUDED_ALLOWANCE_CENTS`, the usage each paid seat includes per period
+measured at provider cost, and `AI_USAGE_OVERAGE_MARKUP_PERCENT`, the whole-percent
+markup over cost applied to usage beyond it before credits are consumed or overage
+is charged. 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 authentication
+service, whose `dev` and `prd` configs carry them directly; the no-Doppler local
+stack stubs them in `BootStubEnv`. The markup is applied to the period's cumulative
+chargeable cost, so settling in chunks books the same money as settling once.
+Change the values in Doppler and redeploy to change pricing. The plan catalog
+(`GET /ai-billing/plans`) publishes `included_ai_cents_per_seat` for every tier,
+and the frontend reads allowances from it
(`useIncludedAiCentsByTier`) rather than hard-coding them. Frozen per-period
rosters keep their cost amounts in `ai_billing_period_allowance.included_cost_cents_by_user`;
-rows written before that column existed are priced at the current allowance.
+rows written before that column existed are priced at the configured allowance.
Only two hosts participate:
@@ -272,6 +278,9 @@ procedure. Operators must approve and record each release gate.
standalone agent trigger, and scheduled action. Include any separately launched
memory/common-tool host. Use the existing Doppler-backed application config,
not a quoted JSON string, AWS secret indirection, or a second Pulumi flag.
+ The pricing values `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and
+ `AI_USAGE_OVERAGE_MARKUP_PERCENT` are mandatory for these same hosts whatever
+ the flags say; see [Settlement](#settlement-enable_ai_usage_billing).
Verify the effective startup value for every replica/worker. Registration and
hosted access require operator approval; code defaults are not proof of it.
4. **Validate locally, then in an approved staging environment.** Use the checklist
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index a27c47a1d6..f7b7c9a867 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -70,6 +70,12 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// OAuth encryption key; deployments without a key do not advertise sign-in.
pub claude_oauth_kms_key_id: ClaudeOauthKmsKeyId,
/// The environment we are in.
@@ -207,6 +213,15 @@ pub struct Config {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
/// Resolve the deployment-injected encryption key. Local stacks use their
/// existing LocalStack key with a separate Claude encryption context.
pub fn claude_oauth_kms_key_id(&self) -> Option<String> {
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 9e5ddf3718..18f7eff248 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -298,6 +298,7 @@ async fn run() -> anyhow::Result<()> {
let admission = ai_billing::composition::pg_admission_service(
pool.clone(),
config.enable_ai_usage_enforcement,
+ config.ai_pricing(),
);
let recorder =
ai_usage::pg_recorder_with_enforcement(pool.clone(), config.enable_ai_usage_enforcement);
@@ -478,6 +479,7 @@ async fn run() -> anyhow::Result<()> {
pool.clone(),
event_broker_tracker.clone(),
config.enable_ai_usage_enforcement,
+ config.ai_pricing(),
)
.await
.context("failed to build the in-memory agent tool context")?;
diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rs
index 831f5d5239..1006f96c40 100644
--- a/services/agent_trigger_service/src/config.rs
+++ b/services/agent_trigger_service/src/config.rs
@@ -16,6 +16,12 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// MacroDB connection URL.
pub database_url: DatabaseUrl,
/// Kafka bootstrap servers.
@@ -27,6 +33,15 @@ pub struct Config {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
/// Loads configuration from the process environment.
pub fn from_env() -> anyhow::Result<Self> {
let enforcement = ai_usage::config::load_ai_usage_enforcement()
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index 27ffdb8d4d..d21eccf178 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -141,6 +141,7 @@ async fn run() -> anyhow::Result<()> {
let admission = ai_billing::composition::pg_admission_service(
pool.clone(),
config.enable_ai_usage_enforcement,
+ config.ai_pricing(),
);
let task_context = ProjectTaskAssignmentContext::new(
DssTaskAssignmentContext::new(
diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rs
index b2b6eb83b0..893c5aa434 100644
--- a/services/authentication_service/src/api.rs
+++ b/services/authentication_service/src/api.rs
@@ -157,6 +157,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
.merge(ai_billing::inbound::ai_billing_router(
ai_billing::inbound::AiBillingRouterState {
service: state.ai_billing_service.clone(),
+ pricing: state.ai_billing_service.pricing(),
authorization_state: state.authorization_state.clone(),
},
))
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index 11a8923a02..ca5fdd1ba0 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -95,6 +95,12 @@ pub struct Config {
/// its policy decides every settlement, however it was requested.
#[macro_config_default(ai_billing::AiUsageBilling::Disabled)]
pub enable_ai_usage_billing: ai_billing::AiUsageBilling,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
#[allow(dead_code)]
pub base_url: BaseUrl,
/// The connection URL for the Postgres database this application should use.
@@ -202,6 +208,15 @@ pub(crate) struct MicrosoftCredentials {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
pub fn from_env() -> anyhow::Result<Self> {
let enforcement = ai_usage::config::load_ai_usage_enforcement()
.map_err(|error| anyhow::anyhow!("{error}"))?;
diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rs
index 3ce240ac15..7be0ddd989 100644
--- a/services/authentication_service/src/config/test.rs
+++ b/services/authentication_service/src/config/test.rs
@@ -30,9 +30,42 @@ fn config_values() -> serde_json::Value {
] {
values[key] = serde_json::json!("test");
}
+ values["AI_USAGE_INCLUDED_ALLOWANCE_CENTS"] = serde_json::json!(2_000);
+ values["AI_USAGE_OVERAGE_MARKUP_PERCENT"] = serde_json::json!(5);
values
}
+#[test]
+fn ai_pricing_is_mandatory_and_validated() {
+ let config: Config = serde_json::from_value(config_values()).unwrap();
+ let pricing = config.ai_pricing();
+ assert_eq!(pricing.included_allowance_cents(), 2_000);
+ assert_eq!(pricing.overage_markup_percent(), 5);
+
+ for key in [
+ "AI_USAGE_INCLUDED_ALLOWANCE_CENTS",
+ "AI_USAGE_OVERAGE_MARKUP_PERCENT",
+ ] {
+ let mut values = config_values();
+ values.as_object_mut().unwrap().remove(key);
+ assert!(
+ serde_json::from_value::<Config>(values.clone()).is_err(),
+ "{key} must be mandatory"
+ );
+ values[key] = serde_json::json!("2000");
+ assert!(
+ serde_json::from_value::<Config>(values).is_err(),
+ "{key} must be an integer"
+ );
+ }
+ let mut values = config_values();
+ values["AI_USAGE_OVERAGE_MARKUP_PERCENT"] = serde_json::json!(100);
+ assert!(serde_json::from_value::<Config>(values).is_err());
+ let mut values = config_values();
+ values["AI_USAGE_INCLUDED_ALLOWANCE_CENTS"] = serde_json::json!(-1);
+ assert!(serde_json::from_value::<Config>(values).is_err());
+}
+
#[test]
fn billing_enforcement_config_defaults_off_and_requires_a_boolean() {
let mut values = config_values();
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 365b5f232c..bb94f727ee 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -506,6 +506,7 @@ async fn main() -> anyhow::Result<()> {
};
let stripe_client = Arc::new(stripe_client);
+ let ai_pricing = config.ai_pricing();
let ai_billing_service = Arc::new(
ai_billing::domain::BillingServiceImpl::new(
ai_billing::outbound::RolesTeamsEntitlementSource::new(
@@ -513,8 +514,9 @@ async fn main() -> anyhow::Result<()> {
teams_repo_impl.clone(),
),
ai_billing::outbound::PgUsageReader::new(db.clone()),
- ai_billing::outbound::PgBillingRepo::new(db.clone()),
+ ai_billing::outbound::PgBillingRepo::new(db.clone(), ai_pricing),
ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),
+ ai_pricing,
)
.with_enforcement(config.enable_ai_usage_enforcement)
.with_billing(config.enable_ai_usage_billing),
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 3d2387012c..0bfa6fbc7d 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -166,7 +166,9 @@ impl StreamRepo for MockStreamRepo {
pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {
let config = Config::new_empty_for_test();
let enforcement = config.enable_ai_usage_enforcement;
- let admission = ai_billing::composition::pg_admission_service(pool.clone(), enforcement);
+ let pricing = config.ai_pricing();
+ let admission =
+ ai_billing::composition::pg_admission_service(pool.clone(), enforcement, pricing);
let recorder = ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement);
use aws_sdk_sqs;
use channels::{
@@ -647,8 +649,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
teams::outbound::team_repo::TeamRepositoryImpl::new(pool.clone()),
),
ai_billing::outbound::PgUsageReader::new(pool.clone()),
- ai_billing::outbound::PgBillingRepo::new(pool.clone()),
+ ai_billing::outbound::PgBillingRepo::new(pool.clone(), pricing),
ai_billing::outbound::NoOpPaymentGateway,
+ pricing,
)
.with_enforcement(enforcement),
),
diff --git a/services/document_cognition_service/src/config.rs b/services/document_cognition_service/src/config.rs
index 493c2c0c7b..fd45de2354 100644
--- a/services/document_cognition_service/src/config.rs
+++ b/services/document_cognition_service/src/config.rs
@@ -78,6 +78,12 @@ pub struct Config {
/// service's own policy decides whether it does.
#[macro_config_default(ai_billing::AiUsageBilling::Disabled)]
pub enable_ai_usage_billing: ai_billing::AiUsageBilling,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// The connection URL for the Postgres database this application should use.
pub database_url: DatabaseUrl,
/// The port to listen for HTTP requests on.
@@ -154,6 +160,15 @@ fn default_mcp_public_url(environment: Environment) -> &'static str {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
#[tracing::instrument(err, skip_all)]
pub fn from_env() -> anyhow::Result<Self> {
let enforcement = ai_usage::config::load_ai_usage_enforcement()
@@ -177,6 +192,9 @@ impl Config {
Config {
enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement::Disabled,
enable_ai_usage_billing: ai_billing::AiUsageBilling::Disabled,
+ ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents::new(2_000)
+ .unwrap(),
+ ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent::new(5).unwrap(),
environment: Environment::Local,
database_url: DatabaseUrl::Comptime("DATABASE_URL"),
port: Default::default(),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index b8a102b9bb..880c6742c6 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -489,6 +489,7 @@ async fn main() -> anyhow::Result<()> {
// collection (Stripe) lives in the authentication service, which the
// recorder below asks to settle once a payer runs past their allowance
// and ENABLE_AI_USAGE_BILLING is enabled. This instance never settles.
+ let ai_pricing = config.ai_pricing();
let ai_billing = Arc::new(
ai_billing::domain::BillingServiceImpl::new(
ai_billing::outbound::RolesTeamsEntitlementSource::new(
@@ -496,8 +497,9 @@ async fn main() -> anyhow::Result<()> {
teams::outbound::team_repo::TeamRepositoryImpl::new(db.clone()),
),
ai_billing::outbound::PgUsageReader::new(db.clone()),
- ai_billing::outbound::PgBillingRepo::new(db.clone()),
+ ai_billing::outbound::PgBillingRepo::new(db.clone(), ai_pricing),
ai_billing::outbound::NoOpPaymentGateway,
+ ai_pricing,
)
.with_enforcement(config.enable_ai_usage_enforcement),
);
diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rs
index 4a86d06896..46bf59f7e6 100644
--- a/services/document_storage_service/src/config.rs
+++ b/services/document_storage_service/src/config.rs
@@ -90,6 +90,12 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
pub database_url: DatabaseUrl,
pub database_url_readonly: DatabaseUrlReadonly,
pub document_storage_bucket: DocumentStorageBucket,
@@ -198,6 +204,15 @@ pub struct Config {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
pub fn from_env() -> anyhow::Result<Self> {
let enforcement = ai_usage::config::load_ai_usage_enforcement()
.map_err(|error| anyhow::anyhow!("{error}"))?;
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 9eb76810ff..b5b57eeae5 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -1289,6 +1289,7 @@ async fn run() -> anyhow::Result<()> {
db.clone(),
event_broker_tracker.clone(),
config.enable_ai_usage_enforcement,
+ config.ai_pricing(),
)
.await
.context("failed to build Macro agent tool context")?;
diff --git a/services/mcp_service/src/config.rs b/services/mcp_service/src/config.rs
index 6ed0f4aa07..70b3ba7714 100644
--- a/services/mcp_service/src/config.rs
+++ b/services/mcp_service/src/config.rs
@@ -65,6 +65,12 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// The environment we are in.
#[macro_config_default(Environment::new_or_prod())]
pub environment: Environment,
@@ -101,6 +107,15 @@ pub struct Config {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
pub fn from_env() -> anyhow::Result<Self> {
let enforcement = ai_usage::config::load_ai_usage_enforcement()
.map_err(|error| anyhow::anyhow!("{error}"))?;
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index c12e44f08a..c555fa15a1 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -484,6 +484,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
admission: ai_billing::composition::pg_admission_service(
db.clone(),
config.enable_ai_usage_enforcement,
+ config.ai_pricing(),
),
recorder,
usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rs
index 1f973150b2..ccd226c070 100644
--- a/services/scheduled_action/src/bins/service.rs
+++ b/services/scheduled_action/src/bins/service.rs
@@ -95,6 +95,7 @@ async fn main() -> Result<()> {
let ai_admission = ai_billing::composition::pg_admission_service(
db.clone(),
config.enable_ai_usage_enforcement,
+ config.ai_pricing(),
);
let sessions = Arc::new(AgentSessionClient::new(
AgentHarnessServiceUrl::new()?.as_ref(),
diff --git a/services/scheduled_action/src/config.rs b/services/scheduled_action/src/config.rs
index 8e0af01b10..6c27e3fe7c 100644
--- a/services/scheduled_action/src/config.rs
+++ b/services/scheduled_action/src/config.rs
@@ -26,6 +26,12 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
+ /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// cost. Mandatory; set in Doppler.
+ pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// The environment we are in.
#[macro_config_default(Environment::new_or_prod())]
pub environment: Environment,
@@ -48,6 +54,15 @@ pub struct Config {
}
impl Config {
+ /// The AI pricing every billing component is composed with. Both values
+ /// are validated when the configuration loads.
+ pub fn ai_pricing(&self) -> ai_billing::AiPricing {
+ ai_billing::AiPricing::new(
+ self.ai_usage_included_allowance_cents,
+ self.ai_usage_overage_markup_percent,
+ )
+ }
+
pub fn from_env() -> anyhow::Result<Self> {
let enforcement = ai_usage::config::load_ai_usage_enforcement()
.map_err(|error| anyhow::anyhow!("{error}"))?;
diff --git a/services/scheduled_action/src/config/test.rs b/services/scheduled_action/src/config/test.rs
index 1172d93cc3..83a5691b9a 100644
--- a/services/scheduled_action/src/config/test.rs
+++ b/services/scheduled_action/src/config/test.rs
@@ -6,10 +6,33 @@ fn config_values() -> Value {
"ENVIRONMENT": "local",
"DATABASE_URL": "postgres://localhost/macro",
"KAFKA_BROKERS": "existing-broker:9092",
- "INTERNAL_API_KEY": "test"
+ "INTERNAL_API_KEY": "test",
+ "AI_USAGE_INCLUDED_ALLOWANCE_CENTS": 2000,
+ "AI_USAGE_OVERAGE_MARKUP_PERCENT": 5
})
}
+#[test]
+fn ai_pricing_is_mandatory_and_validated() {
+ let config: Config = serde_json::from_value(config_values()).unwrap();
+ assert_eq!(config.ai_pricing().included_allowance_cents(), 2_000);
+ assert_eq!(config.ai_pricing().overage_markup_percent(), 5);
+ for key in [
+ "AI_USAGE_INCLUDED_ALLOWANCE_CENTS",
+ "AI_USAGE_OVERAGE_MARKUP_PERCENT",
+ ] {
+ let mut values = config_values();
+ values.as_object_mut().unwrap().remove(key);
+ assert!(
+ serde_json::from_value::<Config>(values).is_err(),
+ "{key} must be mandatory"
+ );
+ }
+ let mut values = config_values();
+ values["AI_USAGE_OVERAGE_MARKUP_PERCENT"] = json!(100);
+ assert!(serde_json::from_value::<Config>(values).is_err());
+}
+
#[test]
fn ai_usage_enforcement_defaults_off_and_requires_a_boolean() {
let config: Config = serde_json::from_value(config_values()).unwrap();
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index 574d71a5a8..d62e67f8e6 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -718,6 +718,11 @@ impl BootStubEnv {
"STRIPE_WEBHOOK_SECRET_KEY".into(),
"local-stripe-webhook-secret".into(),
);
+ // ai_billing's mandatory pricing (crates/ai_billing/src/config.rs). Every
+ // host that composes billing refuses to boot without both; these are
+ // the same values Doppler's shared_ai configs carry.
+ env.insert("AI_USAGE_INCLUDED_ALLOWANCE_CENTS".into(), "2000".into());
+ env.insert("AI_USAGE_OVERAGE_MARKUP_PERCENT".into(), "5".into());
// macro_auth's `JwtValidationArgs` (used by every service that mounts
// the auth middleware) reads these at boot. The keys are only parsed
// when a Macro API token is actually validated — normal local auth