Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai-billing): settle consistently and reconcile outstanding usage (#7789)
Will Hutchinson591dcc61f69d
diff --git a/.sqlx/query-0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18.json b/.sqlx/query-0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18.jsonnew file mode 100644index 0000000000..9ee884536e--- /dev/null+++ b/.sqlx/query-0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT user_id AS \"user_id!\"\n FROM (\n SELECT user_id\n FROM ai_usage\n WHERE count_usage = TRUE\n AND created_at >= $1\n UNION ALL\n SELECT user_id\n FROM ai_credit_reload\n WHERE status = 'pending'\n AND stripe_invoice_id IS NULL\n AND updated_at < $2::timestamptz - INTERVAL '10 minutes'\n UNION ALL\n SELECT user_id\n FROM ai_billing_account\n WHERE period_start >= $1::timestamptz\n OR (period_end >= $1 AND period_end <= $2)\n ) AS candidates\n ORDER BY user_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "0948e0dd417a4583f79f1146744ad76ae030eacee66aab7caeccf67393106a18"+}diff --git a/.sqlx/query-fbd7bb97a68666b530ec5202ae96c5f157383944a7014b876947958233f4afb3.json b/.sqlx/query-fbd7bb97a68666b530ec5202ae96c5f157383944a7014b876947958233f4afb3.jsonnew file mode 100644index 0000000000..b31ddc0fcb--- /dev/null+++ b/.sqlx/query-fbd7bb97a68666b530ec5202ae96c5f157383944a7014b876947958233f4afb3.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT period_start\n FROM ai_billing_period_allowance\n WHERE user_id = $1\n AND period_start >= $2\n AND period_start < $3\n ORDER BY period_start\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "period_start",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "fbd7bb97a68666b530ec5202ae96c5f157383944a7014b876947958233f4afb3"+}diff --git a/Cargo.lock b/Cargo.lockindex 1640bd1b80..acff885bf0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -416,6 +416,7 @@ dependencies = ["ai_toolset","ai_usage","anyhow",+ "authentication_service_client","aws-sdk-kms","aws-sdk-secretsmanager","aws-sdk-sqs",@@ -11958,6 +11959,7 @@ dependencies = ["anyhow","async-trait","attachment",+ "authentication_service_client","aws-sdk-secretsmanager","aws-sdk-sqs","axum",@@ -16540,6 +16542,7 @@ dependencies = ["ai_billing","ai_usage","anyhow",+ "authentication_service_client","aws-sdk-secretsmanager","axum","bot_id",diff --git a/crates/ai_billing/src/composition.rs b/crates/ai_billing/src/composition.rsindex 9dca22c67a..c7c370db50 100644--- a/crates/ai_billing/src/composition.rs+++ b/crates/ai_billing/src/composition.rs@@ -1,10 +1,17 @@-//! Composition helpers for quota admission without payment collection.+//! Composition helpers for hosts that gate and record AI usage without owning+//! Stripe: quota admission, and the usage recorder that asks the+//! authentication service to settle.use crate::{- AiAdmissionService, AiPricing, AiUsageEnforcement, BillingAdmissionService,- domain::BillingServiceImpl,- outbound::{NoOpPaymentGateway, PgBillingRepo, PgUsageReader, RolesTeamsEntitlementSource},+ AiAdmissionService, AiPricing, AiUsageBilling, AiUsageEnforcement, BillingAdmissionService,+ domain::{BillingServiceImpl, ports::NoOpSettlementTrigger},+ outbound::{+ HttpPaymentGateway, HttpSettlementTrigger, NoOpPaymentGateway, PgBillingRepo,+ PgUsageReader, RolesTeamsEntitlementSource, SettlingUsageRecorder,+ },};+use ai_usage::UsageRecorder;+use authentication_service_client::AuthServiceClient;use roles_and_permissions::domain::port::UserRolesAndPermissionsService;use sqlx::PgPool;use std::sync::Arc;@@ -13,6 +20,51 @@ use teams::domain::team_repo::TeamRepository;#[cfg(all(test, feature = "pg-admission"))]mod test;+/// Where a host's settlement requests go.+///+/// Settlement (credit consumption and automatic reloads) runs in the+/// authentication service, which owns Stripe. A host that records+/// counted usage asks it to settle the payer after each completion so a+/// reload fires when the balance runs low rather than on the next Billing+/// page view. The authentication service's own `ENABLE_AI_USAGE_BILLING`+/// policy decides whether a request does anything, and its reconciliation+/// sweep settles anyone whose request was lost; a host's route only decides+/// whether it asks at all.+#[derive(Clone)]+pub enum SettlementRoute {+ /// Never ask. Usage is still recorded and counted.+ Off,+ /// Ask the authentication service through its internal API.+ AuthService(Arc<AuthServiceClient>),+}++/// A host enabled `ENABLE_AI_USAGE_BILLING` without the authentication+/// service key its settlement requests must present.+#[derive(Debug, thiserror::Error)]+#[error(+ "ENABLE_AI_USAGE_BILLING is true but no authentication service client is configured; set AUTHENTICATION_SERVICE_SECRET_KEY or disable billing"+)]+pub struct MissingSettlementClient;++impl SettlementRoute {+ /// Resolve the route from the host's `ENABLE_AI_USAGE_BILLING` policy and+ /// the authentication service client its configuration could build.+ ///+ /// Billing enabled without a client is a misconfiguration worth failing+ /// startup over: the host would record chargeable usage that only the+ /// sweep ever settles. A client without billing is fine and goes unused.+ pub fn from_policy(+ billing: AiUsageBilling,+ auth_client: Option<Arc<AuthServiceClient>>,+ ) -> Result<Self, MissingSettlementClient> {+ match (billing, auth_client) {+ (AiUsageBilling::Disabled, _) => Ok(Self::Off),+ (AiUsageBilling::Enabled, Some(client)) => Ok(Self::AuthService(client)),+ (AiUsageBilling::Enabled, None) => Err(MissingSettlementClient),+ }+ }+}+/// Compose quota admission for hosts without an existing billing service./// Adapter construction stays in this owning-domain composition root. `pricing`/// is the host's mandatory startup configuration.@@ -61,3 +113,92 @@ where.with_enforcement(enforcement);Arc::new(BillingAdmissionService::new(Arc::new(billing), enforcement))}++/// Compose the production usage recorder for a host without an existing+/// billing service: configured counting and per-attempt tracking, inside the+/// settling wrapper that asks the authentication service to settle after+/// counted usage lands ([`SettlingUsageRecorder`]).+#[cfg(feature = "pg-admission")]+pub fn pg_settling_recorder(+ pool: PgPool,+ enforcement: AiUsageEnforcement,+ pricing: AiPricing,+ route: SettlementRoute,+) -> Arc<dyn UsageRecorder> {+ settling_recorder(+ pool.clone(),+ roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),+ roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),+ ),+ teams::outbound::team_repo::TeamRepositoryImpl::new(pool),+ enforcement,+ pricing,+ route,+ )+}++/// Compose the settling usage recorder from the host's existing roles service,+/// team repository and database pool.+///+/// The wrapper is used whatever the route: it retries a usage write that+/// fails, which the bare recorder does not. With+/// [`SettlementRoute::AuthService`] it reads the payer's position after each+/// counted write and asks the authentication service to settle when usage is+/// uncovered; the position's subscription period is read through the same+/// service, as the document cognition service does. With+/// [`SettlementRoute::Off`] the billing position is never read. Neither+/// settles anything in this process.+pub fn settling_recorder<P, T>(+ pool: PgPool,+ permissions: P,+ teams: T,+ enforcement: AiUsageEnforcement,+ pricing: AiPricing,+ route: SettlementRoute,+) -> Arc<dyn UsageRecorder>+where+ P: UserRolesAndPermissionsService,+ T: TeamRepository,+{+ let usage = Arc::new(+ ai_usage::domain::service::UsageServiceImpl::new(ai_usage::outbound::PgUsageRepo::new(+ pool.clone(),+ ))+ .with_enforcement(enforcement),+ );+ let entitlements = RolesTeamsEntitlementSource::new(permissions, teams);+ let analytics: Arc<dyn UsageRecorder> = match route {+ SettlementRoute::Off => Arc::new(SettlingUsageRecorder::new(+ usage,+ Arc::new(+ BillingServiceImpl::new(+ entitlements,+ PgUsageReader::new(pool.clone()),+ PgBillingRepo::new(pool.clone(), pricing),+ NoOpPaymentGateway,+ pricing,+ )+ .with_enforcement(enforcement),+ ),+ NoOpSettlementTrigger,+ AiUsageBilling::Disabled,+ )),+ SettlementRoute::AuthService(client) => Arc::new(SettlingUsageRecorder::new(+ usage,+ Arc::new(+ BillingServiceImpl::new(+ entitlements,+ PgUsageReader::new(pool.clone()),+ PgBillingRepo::new(pool.clone(), pricing),+ HttpPaymentGateway::new(client.clone()),+ pricing,+ )+ .with_enforcement(enforcement),+ ),+ HttpSettlementTrigger::new(client),+ AiUsageBilling::Enabled,+ )),+ };+ ai_usage::with_tracking(analytics, ai_usage::pg_tracking(pool))+}diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rsindex d6b0b78892..a28364ea6a 100644--- a/crates/ai_billing/src/domain.rs+++ b/crates/ai_billing/src/domain.rs@@ -1,5 +1,5 @@//! Domain layer: plans and the configured pricing, the settlement ledger, ports,-//! and the billing service.+//! the billing service, and the reconciliation sweep.pub mod admission;pub mod financial;@@ -10,6 +10,7 @@ pub mod policy;pub mod ports;pub mod pricing;pub mod service;+pub mod sweep;pub use admission::{AdmissionFuture, AiAdmissionError, AiAdmissionService, BillingAdmissionService,@@ -31,10 +32,11 @@ pub use models::{pub use ports::{BillingRepo, BillingService, CreditCheckoutRequest, CreditReloadRequest, EntitlementSource,OverageChargeRequest, PaymentGateway, PendingCharge, PendingReload, ResolvedReload,- SettlementOutcome, SettlementTrigger, UsageReader,+ SettlementCandidates, SettlementOutcome, SettlementTrigger, UsageReader,};pub use pricing::{AiPricing, IncludedAllowanceCents, OverageMarkupPercent, PlanAllowances, PricingError,cost_cents,};-pub use service::BillingServiceImpl;+pub use service::{BillingServiceImpl, RECONCILED_CLOSED_PERIODS};+pub use sweep::{RECONCILIATION_LOOKBACK, SettlementSweep, SweepReport};diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex ad4143bbe4..7dfada00d3 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -198,6 +198,20 @@ pub trait BillingRepo: Send + Sync + 'static {period_start: DateTime<Utc>,) -> impl Future<Output = Result<Option<PeriodAllowance>>> + Send;+ /// Starts of the periods frozen for this payer that began at or after+ /// `since` and before `before`, oldest first.+ ///+ /// A frozen period is one that was observed while open, so it is keyed+ /// exactly as the ledger entries and charges booked against it. These are+ /// the closed periods settlement can still reconcile without inventing a+ /// period start.+ fn frozen_period_starts(+ &self,+ payer: &MacroUserIdStr<'_>,+ since: DateTime<Utc>,+ before: DateTime<Utc>,+ ) -> impl Future<Output = Result<Vec<DateTime<Utc>>>> + Send;+/// Record each seat's allowance for the open period when `observed` is still/// the payer's seat generation.///@@ -470,6 +484,22 @@ pub trait PaymentGateway: Send + Sync + 'static {) -> impl Future<Output = Result<Option<BillingPeriod>>> + Send;}+/// Finds whose settlement may be outstanding, for the periodic sweep in the+/// service that owns Stripe ([`SettlementSweep`](super::sweep::SettlementSweep)).+pub trait SettlementCandidates: Send + Sync + 'static {+ /// Users and payers worth settling: anyone who recorded counted usage at+ /// or after `since`, payers holding a credit reload that was reserved but+ /// never collected, and payers whose anchored subscription period began+ /// or ended at or after `since` (so a period that just closed is booked+ /// even when nobody uses AI afterwards). Deduplicated; the order is+ /// unspecified.+ fn candidates(+ &self,+ since: DateTime<Utc>,+ now: DateTime<Utc>,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>>> + Send;+}+/// Asks whoever owns Stripe to settle a payer. Fire-and-forget: services that/// only read billing state (the gate in DCS) use this instead of settling.pub trait SettlementTrigger: Send + Sync + 'static {@@ -514,10 +544,13 @@ pub trait BillingService: Send + Sync + 'static {) -> impl Future<Output = Result<UsageSnapshot>> + Send;/// Book each seat's usage beyond its own allowance for the payer of `user`- /// (previous and current period) from shared prepaid credits. Only the- /// current period may trigger an automatic credit reload. The previous- /// period is settled against the per-seat allowances frozen while it was- /// open, not the live plan or seat list.+ /// from shared prepaid credits. Settles the current period and, before+ /// it, every closed period still inside the reconciliation window+ /// ([`RECONCILED_CLOSED_PERIODS`](super::service::RECONCILED_CLOSED_PERIODS)),+ /// so usage that ran past a period boundary is booked without a customer+ /// action. Only the current period may trigger an automatic credit+ /// reload. A closed period is settled against the per-seat allowances+ /// frozen while it was open, not the live plan or seat list.fn settle(&self, user: &MacroUserIdStr<'_>) -> impl Future<Output = Result<()>> + Send;/// Retired direct usage opt-in. Enabling is rejected; disabling remainsdiff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex 9d979a7ff2..293040b4ff 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -32,6 +32,18 @@ use teams::domain::open_seat_release::OpenSeatRelease;/// payer per process while Stripe rolls a period or a provider recovers.const PERIOD_MISS_BACKOFF: chrono::Duration = chrono::Duration::minutes(1);+/// How many closed periods behind the open one a settlement reconciles.+///+/// Every period frozen inside this window is settled against its own freeze+/// before the open period is, so usage left unsettled when a period closed+/// (a tail that ran past the boundary, a settlement request that was lost)+/// is booked from credits by whichever settlement comes next rather than+/// waiting on a customer action. Three periods is a bound on the work a+/// settlement does, not on how long usage stays owed: the periodic sweep+/// settles every recently observed payer, so a closed period normally+/// reconciles within a day of ending.+pub const RECONCILED_CLOSED_PERIODS: u32 = 3;+/// The billing service over its four ports.#[derive(Clone)]pub struct BillingServiceImpl<E, U, R, P> {@@ -405,6 +417,51 @@ where))}+ /// The closed periods to settle before `current`, oldest first.+ ///+ /// Every period frozen within the last [`RECONCILED_CLOSED_PERIODS`]+ /// periods is one of them, keyed exactly as its ledger, and ending where+ /// the next period begins: periods are contiguous, and counted usage only+ /// lands in a period that was observed, so the usage between two freezes+ /// belongs to the earlier one. When nothing was frozen since the derived+ /// previous period began, that derived period is settled instead, as it+ /// always was, so a closed period that was never observed is still+ /// flushed from the live entitlement; the last frozen period then ends+ /// where the derived one begins, so no usage is settled under two keys.+ async fn closed_periods(+ &self,+ payer: &MacroUserIdStr<'_>,+ current: BillingPeriod,+ ) -> Result<Vec<BillingPeriod>> {+ let mut since = current;+ for _ in 0..RECONCILED_CLOSED_PERIODS {+ since = since.previous();+ }+ let starts = self+ .repo+ .frozen_period_starts(payer, since.start, current.start)+ .await?;+ let previous = current.previous();+ let previous_was_frozen = starts.iter().any(|start| *start >= previous.start);+ let last_end = if previous_was_frozen {+ current.start+ } else {+ previous.start+ };+ let mut periods: Vec<BillingPeriod> = starts+ .iter()+ .enumerate()+ .map(|(index, &start)| BillingPeriod {+ start,+ end: starts.get(index + 1).copied().unwrap_or(last_end),+ })+ .collect();+ if !previous_was_frozen {+ periods.push(previous);+ }+ Ok(periods)+ }+/// Per-seat allowances to settle `period` with.////// A closed period uses the freeze recorded while it was open. An open@@ -711,17 +768,17 @@ whereif !position.entitlement.is_metered() {return Ok(());}- // The previous period first, so a tail that ran past the boundary is- // flushed before the current one accrues. Closed-period settlement- // uses the freeze recorded while that period was open, not the live- // plan or seat list.- self.settle_period(- &position.entitlement,- position.period.previous(),- now,- ReloadCheck::Skip,- )- .await?;+ // Closed periods first, oldest to newest, so a tail that ran past a+ // boundary is flushed before the current period accrues. Closed-period+ // settlement uses the freeze recorded while that period was open, not+ // the live plan or seat list.+ for period in self+ .closed_periods(&position.entitlement.payer, position.period)+ .await?+ {+ self.settle_period(&position.entitlement, period, now, ReloadCheck::Skip)+ .await?;+ }self.settle_period(&position.entitlement,position.period,diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex 5ccbb6a18e..7ed0b7c25e 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -334,6 +334,24 @@ impl BillingRepo for FakeRepo {.get(&period_start).cloned())}+ async fn frozen_period_starts(+ &self,+ _payer: &MacroUserIdStr<'_>,+ since: DateTime<Utc>,+ before: DateTime<Utc>,+ ) -> Result<Vec<DateTime<Utc>>> {+ let mut starts: Vec<DateTime<Utc>> = self+ .state+ .lock()+ .unwrap()+ .allowances+ .keys()+ .copied()+ .filter(|start| since <= *start && *start < before)+ .collect();+ starts.sort_unstable();+ Ok(starts)+ }async fn store_open_allowance(&self,_payer: &MacroUserIdStr<'_>,@@ -2090,6 +2108,116 @@ async fn previous_period_usage_never_triggers_a_reload() {assert_eq!(repo.state.lock().unwrap().balance, 10_000);}+fn one_seat(payer: &MacroUserIdStr<'static>, included_cents: i64) -> PeriodAllowance {+ PeriodAllowance {+ seats: vec![SeatAllowance {+ user: payer.clone(),+ included_cents,+ }],+ }+}++/// Credits consumed per period start, oldest first.+fn consumed_by_period(repo: &FakeRepo) -> Vec<(DateTime<Utc>, i64)> {+ let mut consumed: Vec<(DateTime<Utc>, i64)> = repo+ .state+ .lock()+ .unwrap()+ .consumed+ .iter()+ .filter(|(_, cents)| **cents > 0)+ .map(|(start, cents)| (*start, *cents))+ .collect();+ consumed.sort_unstable();+ consumed+}++#[tokio::test]+async fn older_frozen_periods_are_settled_inside_the_reconciliation_window() {+ let (svc, repo, payments, usage, _, payer, previous, current) = anchored_premium(0);+ repo.pause_reloads();+ repo.set_balance(10_000);+ svc.sync_period(&payer, current.start, current.end, None)+ .await+ .unwrap();+ // Three closed periods behind the previous one, each observed while open+ // and each run 1_500 past its frozen allowance; nothing settled them.+ let two_back = previous.previous();+ let three_back = two_back.previous();+ let four_back = three_back.previous();+ for period in [two_back, three_back, four_back] {+ repo.freeze(period.start, one_seat(&payer, 1_000));+ usage.add(&payer, period.start + chrono::Duration::days(2), 2_500);+ }++ svc.settle(&payer).await.unwrap();++ // The two inside the window are booked from credits against their own+ // freeze; the one beyond it is left alone rather than settled from a+ // guessed period.+ assert_eq!(+ consumed_by_period(&repo),+ vec![(three_back.start, 1_575), (two_back.start, 1_575)]+ );+ assert_eq!(repo.state.lock().unwrap().balance, 10_000 - 2 * 1_575);+ assert!(payments.opened().is_empty());++ // Settling again books nothing more.+ svc.settle(&payer).await.unwrap();+ assert_eq!(repo.state.lock().unwrap().balance, 10_000 - 2 * 1_575);+}++#[tokio::test]+async fn an_older_frozen_period_ends_where_the_unfrozen_previous_one_begins() {+ let (svc, repo, _, usage, _, payer, previous, current) = anchored_premium(0);+ repo.pause_reloads();+ repo.set_balance(10_000);+ svc.sync_period(&payer, current.start, current.end, None)+ .await+ .unwrap();+ // The period before the previous one was frozen and ran 1_500 over; the+ // previous one was never observed but still carries 200 of usage over+ // the live allowance.+ let two_back = previous.previous();+ repo.freeze(two_back.start, one_seat(&payer, 1_000));+ usage.add(&payer, two_back.start + chrono::Duration::days(2), 2_500);+ usage.add(&payer, previous.start + chrono::Duration::days(2), 2_200);++ svc.settle(&payer).await.unwrap();++ // Each period's usage is booked once, under its own key: the frozen+ // period stops where the derived previous period starts rather than+ // swallowing (and double billing) the usage after it.+ assert_eq!(+ consumed_by_period(&repo),+ vec![(two_back.start, 1_575), (previous.start, 210)]+ );+}++#[tokio::test]+async fn a_period_frozen_inside_the_previous_window_replaces_the_derived_one() {+ let (svc, repo, _, usage, _, payer, previous, current) = anchored_premium(0);+ repo.pause_reloads();+ repo.set_balance(10_000);+ svc.sync_period(&payer, current.start, current.end, None)+ .await+ .unwrap();+ // The subscription was re-anchored mid-cycle: the period that actually+ // preceded the open one started ten days after the derived previous+ // period would have, and was frozen under that start.+ let shifted = previous.start + chrono::Duration::days(10);+ repo.freeze(shifted, one_seat(&payer, 1_000));+ usage.add(&payer, shifted + chrono::Duration::days(2), 2_500);++ svc.settle(&payer).await.unwrap();++ // Booked once, under the frozen start and its 1_000 allowance: a second+ // settlement under the derived start (live 2_000 allowance, 525 owed)+ // would have consumed credits for the same usage twice.+ assert_eq!(consumed_by_period(&repo), vec![(shifted, 1_575)]);+ assert_eq!(repo.state.lock().unwrap().balance, 10_000 - 1_575);+}+#[tokio::test]async fn previous_period_usage_uses_the_frozen_billed_users() {let owner = user("[email protected]");diff --git a/crates/ai_billing/src/domain/sweep.rs b/crates/ai_billing/src/domain/sweep.rsnew file mode 100644index 0000000000..741fee4c52--- /dev/null+++ b/crates/ai_billing/src/domain/sweep.rs@@ -0,0 +1,106 @@+//! The periodic reconciliation sweep: settles every payer whose settlement+//! nobody asked for.+//!+//! Settlement is otherwise requested after a counted completion, on a Billing+//! page view, and by billing settings and Stripe webhooks. Each of those is a+//! request that can be lost (a host without the trigger, a request that+//! failed its bounded retries, a reload collector that died mid-charge) or+//! that never comes (a period that closed after the payer's last completion).+//! The sweep is the floor under all of them: on a schedule, it settles+//! everyone who recorded counted usage recently, everyone whose period just+//! closed, and everyone with a reload that was never collected, so credits+//! are consumed and reloads fire without a customer action. Settlement is+//! idempotent, so a payer settled twice books nothing twice; replicas may+//! overlap safely.++#[cfg(test)]+mod test;++use super::models::Result;+use super::ports::{BillingService, EntitlementSource, SettlementCandidates};+use chrono::{DateTime, TimeDelta, Utc};+use std::collections::HashSet;+use std::sync::Arc;++/// How far back a sweep looks for counted usage and period boundaries.+///+/// Much wider than the sweep interval on purpose: a sweep that fails, a+/// replica that restarts, or a short outage of the service running it must+/// not leave a payer unsettled until their next completion. Settling an+/// already settled payer costs a handful of reads and books nothing.+pub const RECONCILIATION_LOOKBACK: TimeDelta = TimeDelta::hours(24);++/// What one sweep did.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct SweepReport {+ /// Users and payers the candidate query returned.+ pub candidates: usize,+ /// Distinct metered payers settled (or attempted).+ pub payers: usize,+ /// Candidates whose payer could not be resolved or settled. Each is+ /// logged; the sweep continues with the next.+ pub failed: usize,+}++/// One pass over everyone who may have usage to settle.+pub struct SettlementSweep<B, C, E> {+ billing: Arc<B>,+ candidates: C,+ entitlements: E,+}++impl<B, C, E> SettlementSweep<B, C, E>+where+ B: BillingService,+ C: SettlementCandidates,+ E: EntitlementSource,+{+ /// Build over the billing service that settles, the candidate finder, and+ /// the entitlement source that maps a candidate user to their payer.+ pub fn new(billing: Arc<B>, candidates: C, entitlements: E) -> Self {+ Self {+ billing,+ candidates,+ entitlements,+ }+ }++ /// Settle every payer with a candidate in the last+ /// [`RECONCILIATION_LOOKBACK`], once each.+ ///+ /// Candidates are users, several of whom may bill to the same team+ /// payer, so each is resolved to its payer and a payer is settled once.+ /// Unmetered payers (free or unlimited) have nothing to settle and are+ /// skipped before the billing service is asked. A failure for one payer+ /// is logged and counted, never propagated: the next payer's money does+ /// not depend on it. Only a failure to list candidates fails the sweep.+ #[tracing::instrument(skip(self), err)]+ pub async fn run_once(&self, now: DateTime<Utc>) -> Result<SweepReport> {+ let since = now - RECONCILIATION_LOOKBACK;+ let candidates = self.candidates.candidates(since, now).await?;+ let mut report = SweepReport {+ candidates: candidates.len(),+ ..SweepReport::default()+ };+ let mut seen: HashSet<String> = HashSet::new();+ for user in candidates {+ let entitlement = match self.entitlements.entitlement(&user).await {+ Ok(entitlement) => entitlement,+ Err(error) => {+ tracing::warn!(error = ?error, "settlement sweep could not resolve a payer");+ report.failed += 1;+ continue;+ }+ };+ if !entitlement.is_metered() || !seen.insert(entitlement.payer.to_string()) {+ continue;+ }+ report.payers += 1;+ if let Err(error) = self.billing.settle(&entitlement.payer).await {+ tracing::warn!(error = ?error, "settlement sweep could not settle a payer");+ report.failed += 1;+ }+ }+ Ok(report)+ }+}diff --git a/crates/ai_billing/src/domain/sweep/test.rs b/crates/ai_billing/src/domain/sweep/test.rsnew file mode 100644index 0000000000..9f882fab0a--- /dev/null+++ b/crates/ai_billing/src/domain/sweep/test.rs@@ -0,0 +1,285 @@+use super::*;+use crate::domain::models::{+ AllowanceDecision, AutoReloadThresholds, BillingError, Entitlement, PayerScope, PlanTier,+ UsageSnapshot,+};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use macro_uuid::Uuid;+use std::collections::HashMap;+use std::sync::Mutex;++fn user(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()+}++/// The `(since, now)` window one candidate query was asked for.+type Window = (DateTime<Utc>, DateTime<Utc>);++/// Returns the configured candidates and remembers the window it was asked for.+#[derive(Clone, Default)]+struct FakeCandidates {+ users: Vec<MacroUserIdStr<'static>>,+ fail: bool,+ windows: Arc<Mutex<Vec<Window>>>,+}++impl SettlementCandidates for FakeCandidates {+ async fn candidates(+ &self,+ since: DateTime<Utc>,+ now: DateTime<Utc>,+ ) -> Result<Vec<MacroUserIdStr<'static>>> {+ self.windows.lock().unwrap().push((since, now));+ if self.fail {+ return Err(BillingError::Storage(anyhow::anyhow!(+ "candidates unavailable"+ )));+ }+ Ok(self.users.clone())+ }+}++#[derive(Clone, Default)]+struct FakeEntitlements {+ by_user: HashMap<String, Entitlement>,+ fail_for: Option<String>,+}++impl EntitlementSource for FakeEntitlements {+ async fn entitlement(&self, user: &MacroUserIdStr<'_>) -> Result<Entitlement> {+ if self.fail_for.as_deref() == Some(user.as_ref()) {+ return Err(BillingError::Entitlement(anyhow::anyhow!(+ "roles unavailable"+ )));+ }+ Ok(self+ .by_user+ .get(user.as_ref())+ .cloned()+ .unwrap_or_else(|| Entitlement::personal(user.clone().into_owned(), PlanTier::Free)))+ }+ async fn stripe_customer_id(&self, _user: &MacroUserIdStr<'_>) -> Result<Option<String>> {+ unreachable!()+ }+ async fn team_payer(&self, _team_id: Uuid) -> Result<Option<MacroUserIdStr<'static>>> {+ unreachable!()+ }+}++/// Records who was settled and fails for one configured payer.+#[derive(Default)]+struct FakeBilling {+ settled: Mutex<Vec<String>>,+ fail_for: Option<String>,+}++impl BillingService for FakeBilling {+ async fn settle(&self, user: &MacroUserIdStr<'_>) -> Result<()> {+ self.settled.lock().unwrap().push(user.to_string());+ if self.fail_for.as_deref() == Some(user.as_ref()) {+ return Err(BillingError::NoStripeCustomer);+ }+ Ok(())+ }+ async fn snapshot(&self, _user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {+ unreachable!()+ }+ async fn check_allowance(&self, _user: &MacroUserIdStr<'_>) -> Result<AllowanceDecision> {+ unreachable!()+ }+ async fn update_overage(+ &self,+ _user: &MacroUserIdStr<'_>,+ _enabled: bool,+ _limit_cents: i64,+ ) -> Result<UsageSnapshot> {+ unreachable!()+ }+ async fn update_auto_reload(+ &self,+ _user: &MacroUserIdStr<'_>,+ _enabled: bool,+ _thresholds: AutoReloadThresholds,+ ) -> Result<UsageSnapshot> {+ unreachable!()+ }+ async fn create_credit_checkout(+ &self,+ _user: &MacroUserIdStr<'_>,+ _amount_cents: i64,+ _success_url: String,+ _cancel_url: String,+ ) -> Result<String> {+ unreachable!()+ }+ async fn apply_credit_purchase(+ &self,+ _payer: &MacroUserIdStr<'_>,+ _amount_cents: i64,+ _stripe_reference: &str,+ ) -> Result<()> {+ unreachable!()+ }+ async fn sync_period(+ &self,+ _payer: &MacroUserIdStr<'_>,+ _start: DateTime<Utc>,+ _end: DateTime<Utc>,+ _verified: Option<crate::domain::period::SubscriptionPeriod>,+ ) -> Result<()> {+ unreachable!()+ }+ async fn mark_overage_invoice(&self, _stripe_invoice_id: &str, _paid: bool) -> Result<()> {+ unreachable!()+ }+ async fn mark_credit_reload_invoice(+ &self,+ _stripe_invoice_id: &str,+ _paid: bool,+ ) -> Result<()> {+ unreachable!()+ }+}++fn team_member(member: &MacroUserIdStr<'static>, owner: &MacroUserIdStr<'static>) -> Entitlement {+ let team_id = Uuid::nil();+ Entitlement {+ tier: PlanTier::Premium,+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],+ unlimited: false,+ payer: owner.clone(),+ billed_users: vec![owner.clone(), member.clone()],+ scope: PayerScope::TeamMember { team_id },+ }+}++#[tokio::test]+async fn settles_each_metered_payer_once_over_the_lookback_window() {+ let owner = user("[email protected]");+ let member_a = user("[email protected]");+ let member_b = user("[email protected]");+ let solo = user("[email protected]");+ let free = user("[email protected]");+ let mut unlimited = Entitlement::personal(user("[email protected]"), PlanTier::Max);+ unlimited.unlimited = true;+ let entitlements = FakeEntitlements {+ by_user: HashMap::from([+ (member_a.to_string(), team_member(&member_a, &owner)),+ (member_b.to_string(), team_member(&member_b, &owner)),+ (+ owner.to_string(),+ Entitlement {+ scope: PayerScope::TeamOwner {+ team_id: Uuid::nil(),+ },+ ..team_member(&member_a, &owner)+ },+ ),+ (+ solo.to_string(),+ Entitlement::personal(solo.clone(), PlanTier::Premium),+ ),+ (unlimited.payer.to_string(), unlimited.clone()),+ ]),+ fail_for: None,+ };+ let candidates = FakeCandidates {+ users: vec![+ member_a.clone(),+ solo.clone(),+ member_b.clone(),+ free.clone(),+ owner.clone(),+ unlimited.payer.clone(),+ ],+ ..FakeCandidates::default()+ };+ let billing = Arc::new(FakeBilling::default());+ let sweep = SettlementSweep::new(billing.clone(), candidates.clone(), entitlements);++ let now = Utc::now();+ let report = sweep.run_once(now).await.unwrap();++ assert_eq!(+ report,+ SweepReport {+ candidates: 6,+ payers: 2,+ failed: 0,+ }+ );+ // Three team candidates collapse onto their payer; free and unlimited+ // users are never metered and never reach the billing service.+ assert_eq!(+ *billing.settled.lock().unwrap(),+ vec![owner.to_string(), solo.to_string()]+ );+ assert_eq!(+ *candidates.windows.lock().unwrap(),+ vec![(now - RECONCILIATION_LOOKBACK, now)]+ );+}++#[tokio::test]+async fn a_failing_payer_is_counted_and_does_not_stop_the_sweep() {+ let broken_roles = user("[email protected]");+ let declined = user("[email protected]");+ let fine = user("[email protected]");+ let entitlements = FakeEntitlements {+ by_user: HashMap::from([+ (+ declined.to_string(),+ Entitlement::personal(declined.clone(), PlanTier::Premium),+ ),+ (+ fine.to_string(),+ Entitlement::personal(fine.clone(), PlanTier::Premium),+ ),+ ]),+ fail_for: Some(broken_roles.to_string()),+ };+ let billing = Arc::new(FakeBilling {+ fail_for: Some(declined.to_string()),+ ..FakeBilling::default()+ });+ let sweep = SettlementSweep::new(+ billing.clone(),+ FakeCandidates {+ users: vec![broken_roles, declined.clone(), fine.clone()],+ ..FakeCandidates::default()+ },+ entitlements,+ );++ let report = sweep.run_once(Utc::now()).await.unwrap();++ assert_eq!(+ report,+ SweepReport {+ candidates: 3,+ payers: 2,+ failed: 2,+ }+ );+ assert_eq!(+ *billing.settled.lock().unwrap(),+ vec![declined.to_string(), fine.to_string()]+ );+}++#[tokio::test]+async fn an_unavailable_candidate_list_fails_the_sweep_before_settling_anyone() {+ let billing = Arc::new(FakeBilling::default());+ let sweep = SettlementSweep::new(+ billing.clone(),+ FakeCandidates {+ users: vec![user("[email protected]")],+ fail: true,+ ..FakeCandidates::default()+ },+ FakeEntitlements::default(),+ );++ assert!(sweep.run_once(Utc::now()).await.is_err());+ assert!(billing.settled.lock().unwrap().is_empty());+}diff --git a/crates/ai_billing/src/inbound.rs b/crates/ai_billing/src/inbound.rsindex 88d6a1c13e..93c3c5678b 100644--- a/crates/ai_billing/src/inbound.rs+++ b/crates/ai_billing/src/inbound.rs@@ -1,6 +1,10 @@-//! Inbound adapters: the axum router.+//! Inbound adapters: the axum router and the scheduled reconciliation sweep.pub mod admission;pub mod axum_router;+pub mod sweep_worker;pub use axum_router::{AiBillingRouterState, ai_billing_router};+pub use sweep_worker::{+ SETTLEMENT_SWEEP_INITIAL_DELAY, SETTLEMENT_SWEEP_INTERVAL, run_settlement_sweep,+};diff --git a/crates/ai_billing/src/inbound/sweep_worker.rs b/crates/ai_billing/src/inbound/sweep_worker.rsnew file mode 100644index 0000000000..8b20c692f8--- /dev/null+++ b/crates/ai_billing/src/inbound/sweep_worker.rs@@ -0,0 +1,49 @@+//! Runs the reconciliation sweep on a schedule, for the service that owns+//! Stripe.++use crate::domain::{BillingService, EntitlementSource, SettlementCandidates, SettlementSweep};+use chrono::Utc;+use std::time::Duration;++/// How long after boot the first sweep runs. Short, so a deploy that lands+/// while usage is owed recovers it without waiting out a full interval, and+/// so rolling restarts cannot keep pushing the first sweep ahead of them.+pub const SETTLEMENT_SWEEP_INITIAL_DELAY: Duration = Duration::from_secs(60);++/// How often the sweep runs after that. Every host also requests settlement+/// after a counted completion, so an hour bounds how long a lost request or+/// a closed period waits, not how long usage normally takes to settle.+pub const SETTLEMENT_SWEEP_INTERVAL: Duration = Duration::from_secs(60 * 60);++/// Sweep forever: once after `initial_delay`, then every `interval`.+///+/// A sweep that fails is logged and tried again at the next tick; one that+/// runs long delays the next tick rather than overlapping it. The caller+/// spawns this and drops or aborts the task to stop it: settlement is+/// idempotent and every step commits on its own, so stopping mid-sweep+/// leaves nothing half done.+pub async fn run_settlement_sweep<B, C, E>(+ sweep: SettlementSweep<B, C, E>,+ initial_delay: Duration,+ interval: Duration,+) where+ B: BillingService,+ C: SettlementCandidates,+ E: EntitlementSource,+{+ tokio::time::sleep(initial_delay).await;+ loop {+ match sweep.run_once(Utc::now()).await {+ Ok(report) => tracing::info!(+ candidates = report.candidates,+ payers = report.payers,+ failed = report.failed,+ "ai billing settlement sweep finished"+ ),+ Err(error) => {+ tracing::warn!(error = ?error, "ai billing settlement sweep failed");+ }+ }+ tokio::time::sleep(interval).await;+ }+}diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rsindex a7d85993c9..db98cef6d0 100644--- a/crates/ai_billing/src/lib.rs+++ b/crates/ai_billing/src/lib.rs@@ -29,12 +29,16 @@//! # Layout//!//! - [`domain`] — plan catalog, the configured pricing, the settlement ledger-//! (pure), ports, and the service.+//! (pure), ports, the service, and the reconciliation sweep that settles+//! whoever nobody asked to settle.//! - [`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.+//! Stripe gateway, the roles + teams entitlement resolver, the sweep's+//! candidate finder, and the recorder wrapper that triggers settlement after+//! usage lands.//! - [`inbound`] — the axum router (summary, overage settings, credit-//! checkout, internal settle).+//! checkout, internal settle) and the scheduled sweep worker.+//! - [`composition`] — how a host that does not own Stripe composes admission+//! and the settling recorder.//! - [`config`] — startup configuration: the mandatory pricing values and the//! `ENABLE_AI_USAGE_BILLING` loader, the default-off policy that gates//! settlement in every environment.diff --git a/crates/ai_billing/src/outbound.rs b/crates/ai_billing/src/outbound.rsindex ca248aa77a..5eed0823bc 100644--- a/crates/ai_billing/src/outbound.rs+++ b/crates/ai_billing/src/outbound.rs@@ -1,12 +1,13 @@//! Outbound adapters: Postgres, Stripe, the roles + teams entitlement resolver,-//! the internal settlement trigger and subscription-period reader, and the-//! settling usage recorder.+//! the internal settlement trigger and subscription-period reader, the+//! sweep's candidate finder, and the settling usage recorder.pub mod entitlement;pub mod http_payment_gateway;pub mod http_settlement_trigger;pub mod pg_billing_repo;pub mod pg_funding_repo;+pub mod pg_settlement_candidates;pub mod pg_usage_reader;pub mod settling_recorder;pub mod stripe_gateway;@@ -16,6 +17,7 @@ pub use http_payment_gateway::HttpPaymentGateway;pub use http_settlement_trigger::HttpSettlementTrigger;pub use pg_billing_repo::PgBillingRepo;pub use pg_funding_repo::PgFundingRepo;+pub use pg_settlement_candidates::PgSettlementCandidates;pub use pg_usage_reader::PgUsageReader;pub use settling_recorder::SettlingUsageRecorder;pub use stripe_gateway::{NoOpPaymentGateway, StripePaymentGateway};diff --git a/crates/ai_billing/src/outbound/http_settlement_trigger.rs b/crates/ai_billing/src/outbound/http_settlement_trigger.rsindex 583256e2dc..74ab316a66 100644--- a/crates/ai_billing/src/outbound/http_settlement_trigger.rs+++ b/crates/ai_billing/src/outbound/http_settlement_trigger.rs@@ -14,9 +14,11 @@ const RETRY_BACKOFF: [Duration; 2] = [Duration::from_secs(1), Duration::from_sec/// [`SettlementTrigger`] over the internal auth-service API. Runs on a/// background task with a short bounded retry. Settlement is idempotent and-/// is requested again by the payer's next completion and by every Billing-/// page view (the summary endpoint settles first), so a request that still-/// fails after the retries is picked up there rather than queued durably.+/// is requested again by the payer's next completion, by every Billing page+/// view (the summary endpoint settles first), and by the authentication+/// service's own reconciliation sweep, which settles everyone with recent+/// counted usage on a schedule; a request that still fails after the retries+/// is picked up there rather than queued durably.#[derive(Clone)]pub struct HttpSettlementTrigger {client: Arc<AuthServiceClient>,@@ -47,7 +49,7 @@ impl SettlementTrigger for HttpSettlementTrigger {tracing::error!(error = ?e,attempts = RETRY_BACKOFF.len() + 1,- "ai billing settlement request failed; the next completion or billing page view retries"+ "ai billing settlement request failed; the next completion, billing page view, or reconciliation sweep retries");return;}diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rsindex 7612422a26..84c0ac9c93 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs@@ -280,6 +280,30 @@ impl BillingRepo for PgBillingRepo {.transpose()}+ async fn frozen_period_starts(+ &self,+ payer: &MacroUserIdStr<'_>,+ since: DateTime<Utc>,+ before: DateTime<Utc>,+ ) -> Result<Vec<DateTime<Utc>>> {+ sqlx::query_scalar!(+ r#"+ SELECT period_start+ FROM ai_billing_period_allowance+ WHERE user_id = $1+ AND period_start >= $2+ AND period_start < $3+ ORDER BY period_start+ "#,+ payer.as_ref(),+ since,+ before,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(storage)+ }+async fn store_open_allowance(&self,payer: &MacroUserIdStr<'_>,diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rsindex e8e6e1903c..4dd6312c46 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs@@ -468,6 +468,72 @@ async fn settlement_uses_stored_overage_policy_and_flushes_at_period_end(pool: Passert!(outcome.pending_charge.is_none());}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn frozen_period_starts_lists_the_payers_periods_in_the_window(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());+ let payer = payer();+ let other = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();+ let now = Utc::now()+ .duration_trunc(chrono::Duration::microseconds(1))+ .unwrap();+ let month = chrono::Duration::days(30);+ let seats = |user: &MacroUserIdStr<'static>| {+ vec![SeatAllowance {+ user: user.clone(),+ included_cents: 2_000,+ }]+ };+ // Four consecutive periods frozen for the payer, out of order, and one+ // for someone else in the middle of them.+ let starts = [now - month * 3, now - month, now - month * 2, now];+ for start in starts {+ let period = BillingPeriod {+ start,+ end: start + month,+ };+ repo.store_open_allowance(+ &payer,+ period.open_start(start).unwrap(),+ &seats(&payer),+ SeatGeneration::from_raw(0),+ )+ .await+ .unwrap();+ }+ let other_period = BillingPeriod {+ start: now - month * 2,+ end: now - month,+ };+ repo.store_open_allowance(+ &other,+ other_period.open_start(other_period.start).unwrap(),+ &seats(&other),+ SeatGeneration::from_raw(0),+ )+ .await+ .unwrap();++ // Inclusive of `since`, exclusive of `before`, oldest first.+ assert_eq!(+ repo.frozen_period_starts(&payer, now - month * 2, now)+ .await+ .unwrap(),+ vec![now - month * 2, now - month]+ );+ assert_eq!(+ repo.frozen_period_starts(&payer, now - month * 3, now + month)+ .await+ .unwrap(),+ vec![now - month * 3, now - month * 2, now - month, now]+ );+ assert!(+ repo.frozen_period_starts(&payer, now + chrono::Duration::days(1), now + month)+ .await+ .unwrap()+ .is_empty()+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {let repo = PgBillingRepo::new(pool.clone(), AiPricing::testing());diff --git a/crates/ai_billing/src/outbound/pg_settlement_candidates.rs b/crates/ai_billing/src/outbound/pg_settlement_candidates.rsnew file mode 100644index 0000000000..23341c00c8--- /dev/null+++ b/crates/ai_billing/src/outbound/pg_settlement_candidates.rs@@ -0,0 +1,73 @@+//! Finds who the reconciliation sweep should settle, from the usage and+//! billing tables.++#[cfg(test)]+mod test;++use crate::domain::{BillingError, Result, SettlementCandidates};+use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;++/// Postgres-backed [`SettlementCandidates`].+#[derive(Clone)]+pub struct PgSettlementCandidates {+ pool: PgPool,+}++impl PgSettlementCandidates {+ /// Create a finder over a connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl SettlementCandidates for PgSettlementCandidates {+ async fn candidates(+ &self,+ since: DateTime<Utc>,+ now: DateTime<Utc>,+ ) -> Result<Vec<MacroUserIdStr<'static>>> {+ // Counted usage is read through `ai_usage_created_at_idx`; the two+ // billing tables are small (one row per payer or reload). A reload+ // whose collector has not reported back in ten minutes was abandoned+ // (the process died between reserving and opening the invoice); the+ // same window `PgBillingRepo` uses to hand it back to the next+ // settlement. Retired direct usage charges are never retried, so+ // their table is not consulted.+ let rows = sqlx::query_scalar!(+ r#"+ SELECT DISTINCT user_id AS "user_id!"+ FROM (+ SELECT user_id+ FROM ai_usage+ WHERE count_usage = TRUE+ AND created_at >= $1+ UNION ALL+ SELECT user_id+ FROM ai_credit_reload+ WHERE status = 'pending'+ AND stripe_invoice_id IS NULL+ AND updated_at < $2::timestamptz - INTERVAL '10 minutes'+ UNION ALL+ SELECT user_id+ FROM ai_billing_account+ WHERE period_start >= $1::timestamptz+ OR (period_end >= $1 AND period_end <= $2)+ ) AS candidates+ ORDER BY user_id+ "#,+ since,+ now,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|e| BillingError::Storage(e.into()))?;+ rows.into_iter()+ .map(|user_id| {+ MacroUserIdStr::try_from(user_id)+ .map_err(|error| BillingError::Storage(error.into()))+ })+ .collect()+ }+}diff --git a/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rs b/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rsnew file mode 100644index 0000000000..c4dad16d76--- /dev/null+++ b/crates/ai_billing/src/outbound/pg_settlement_candidates/test.rs@@ -0,0 +1,199 @@+use super::*;+use ai_usage::outbound::PgUsageRepo;+use ai_usage::{AiFeature, CompletionUsage, ModelPricing, Price, Usage, UsageAmount, UsageRepo};+use chrono::Duration;+use macro_db_migrator::MACRO_DB_MIGRATIONS;++fn user(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()+}++/// One counted (or not) completion for `user`, backdated to `at`.+async fn usage_row(+ pool: &PgPool,+ user: &MacroUserIdStr<'static>,+ at: DateTime<Utc>,+ counted: bool,+) {+ PgUsageRepo::new(pool.clone())+ .insert_usage(+ &CompletionUsage {+ feature: AiFeature::Chat,+ user: user.clone(),+ entity: None,+ cost: Usage {+ amount: UsageAmount::Tokens {+ input: 1_000,+ output: 0,+ cache_read: 0,+ cache_write: 0,+ },+ model: "test-model".to_string(),+ price: Some(Price {+ pricing: ModelPricing::Tokens {+ input: 1.0,+ output: 0.0,+ cache_read: None,+ cache_write: None,+ },+ total: 0.001,+ }),+ created_at: at,+ },+ },+ counted,+ )+ .await+ .unwrap();+ // The insert stamps `NOW()`; the row's own timestamp is what the sweep reads.+ sqlx::query!(+ "UPDATE ai_usage SET created_at = $2 WHERE user_id = $1",+ user.as_ref(),+ at,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn reservation(+ pool: &PgPool,+ user: &MacroUserIdStr<'static>,+ status: &str,+ invoice: Option<&str>,+ updated_at: DateTime<Utc>,+) {+ sqlx::query!(+ r#"+ INSERT INTO ai_credit_reload (id, user_id, amount_cents, stripe_invoice_id, status, updated_at)+ VALUES ($1, $2, 1000, $3, ($4::text)::ai_credit_reload_status, $5)+ "#,+ macro_uuid::generate_uuid_v7(),+ user.as_ref(),+ invoice,+ status,+ updated_at,+ )+ .execute(pool)+ .await+ .unwrap();+}++/// A retired direct usage charge, which settlement never retries.+async fn abandoned_overage_charge(+ pool: &PgPool,+ user: &MacroUserIdStr<'static>,+ updated_at: DateTime<Utc>,+) {+ sqlx::query!(+ r#"+ INSERT INTO ai_overage_charge+ (id, user_id, period_start, amount_cents, stripe_invoice_id, status, updated_at)+ VALUES ($1, $2, $3, 1000, NULL, 'pending', $3)+ "#,+ macro_uuid::generate_uuid_v7(),+ user.as_ref(),+ updated_at,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn anchor(+ pool: &PgPool,+ user: &MacroUserIdStr<'static>,+ start: DateTime<Utc>,+ end: DateTime<Utc>,+) {+ sqlx::query!(+ "INSERT INTO ai_billing_account (user_id, period_start, period_end) VALUES ($1, $2, $3)",+ user.as_ref(),+ start,+ end,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn lists_recent_counted_users_abandoned_reloads_and_period_boundaries(pool: PgPool) {+ let now = Utc::now();+ let since = now - Duration::hours(24);+ let finder = PgSettlementCandidates::new(pool.clone());++ // Usage: only counted rows inside the window qualify.+ let recent_counted = user("[email protected]");+ let recent_uncounted = user("[email protected]");+ let old_counted = user("[email protected]");+ usage_row(&pool, &recent_counted, now - Duration::hours(1), true).await;+ usage_row(&pool, &recent_counted, now - Duration::hours(2), true).await;+ usage_row(&pool, &recent_uncounted, now - Duration::hours(1), false).await;+ usage_row(&pool, &old_counted, since - Duration::minutes(1), true).await;++ // Reservations: only an uninvoiced pending reload older than the+ // collector window is abandoned. Invoiced ones are with Stripe; failed+ // ones wait for the payer; fresh ones may still be collecting. Direct+ // usage charges are retired and never retried.+ let abandoned_reload = user("[email protected]");+ let invoiced_reload = user("[email protected]");+ let failed_reload = user("[email protected]");+ let collecting_reload = user("[email protected]");+ let abandoned_charge = user("[email protected]");+ let stale = now - Duration::minutes(11);+ reservation(&pool, &abandoned_reload, "pending", None, stale).await;+ reservation(&pool, &invoiced_reload, "pending", Some("in_1"), stale).await;+ reservation(&pool, &failed_reload, "failed", None, stale).await;+ reservation(+ &pool,+ &collecting_reload,+ "pending",+ None,+ now - Duration::minutes(2),+ )+ .await;+ abandoned_overage_charge(&pool, &abandoned_charge, stale).await;++ // Period boundaries: a period that began or ended inside the window.+ let just_rolled = user("[email protected]");+ let just_ended = user("[email protected]");+ let mid_period = user("[email protected]");+ let long_ago = user("[email protected]");+ let day = Duration::days(1);+ anchor(+ &pool,+ &just_rolled,+ now - Duration::hours(3),+ now + day * 30,+ )+ .await;+ anchor(&pool, &just_ended, now - day * 30, now - Duration::hours(3)).await;+ anchor(&pool, &mid_period, now - day * 10, now + day * 20).await;+ anchor(&pool, &long_ago, now - day * 60, now - day * 30).await;++ let candidates: Vec<String> = finder+ .candidates(since, now)+ .await+ .unwrap()+ .iter()+ .map(ToString::to_string)+ .collect();++ let mut expected: Vec<String> = [recent_counted, abandoned_reload, just_rolled, just_ended]+ .iter()+ .map(ToString::to_string)+ .collect();+ expected.sort_unstable();+ assert_eq!(candidates, expected);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_empty_window_lists_nobody(pool: PgPool) {+ let now = Utc::now();+ let candidates = PgSettlementCandidates::new(pool)+ .candidates(now - Duration::hours(24), now)+ .await+ .unwrap();+ assert!(candidates.is_empty());+}diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 116dbda2d1..d8b8438658 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -131,19 +131,26 @@ pub fn build_image_generator_from_env() -> Arc<dyn ImageGenerator> {/// - `ENABLE_NOTIFICATION_QUEUE` (if disabled, notification status updates skip push clearing)////// `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.+/// AI entry points. It configures quota admission here and must be the policy+/// `recorder` was composed with. `pricing` is the host's mandatory AI pricing+/// configuration, shared with every other billing component it composes.+///+/// `recorder` is the host's configured usage recorder, shared by every tool in+/// the context that calls a model. The host composes it so that one process+/// records, counts, and requests settlement for usage one way: through+/// [`ai_billing::composition::pg_settling_recorder`] where its usage is+/// chargeable, or [`ai_usage::pg_recorder_with_enforcement`] where it is not.////// `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/// original after the host stops broker-backed work.-#[tracing::instrument(skip(pool, event_task_tracker), err)]+#[tracing::instrument(skip(pool, event_task_tracker, recorder), err)]pub async fn build_tool_service_context_from_env(pool: sqlx::PgPool,event_task_tracker: TaskTracker,enforcement: ai_usage::AiUsageEnforcement,pricing: ai_billing::AiPricing,+ recorder: Arc<dyn ai_usage::UsageRecorder>,) -> anyhow::Result<ToolServiceContext> {let env = ToolContextEnvVars::new()?;let maybe_env = ToolContextMaybeEnvVars::new();@@ -496,8 +503,6 @@ pub async fn build_tool_service_context_from_env(},);- let recorder = ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement);-Ok(ToolServiceContext {connector_tool_context: crate::tool_context::build_connector_tool_context(pool.clone(),diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rsindex 2dc1968250..c58f20ffbb 100644--- a/crates/memory/src/context.rs+++ b/crates/memory/src/context.rs@@ -8,17 +8,22 @@ use crate::config::Config;/// Build memory's tools at startup with the same quota policy as other hosts./// The memory domain binds its exempt `Memory` feature when it starts an operation;/// the shared context must not globally exempt independently initiated AI tools.+/// Memory usage is exempt from counting, so nothing recorded here is ever+/// chargeable and the recorder never requests settlement.#[tracing::instrument(skip_all, err)]pub async fn build_tool_service_context(pool: sqlx::PgPool,config: &Config,event_task_tracker: TaskTracker,) -> anyhow::Result<ToolServiceContext> {+ let recorder =+ ai_usage::pg_recorder_with_enforcement(pool.clone(), config.enable_ai_usage_enforcement);build_tool_service_context_from_env(pool,event_task_tracker,config.enable_ai_usage_enforcement,config.ai_pricing,+ recorder,).await}diff --git a/docs/AI_BILLING_ROLLOUT.md b/docs/AI_BILLING_ROLLOUT.mdindex a610c586b8..a2e8fe88f7 100644--- a/docs/AI_BILLING_ROLLOUT.md+++ b/docs/AI_BILLING_ROLLOUT.md@@ -29,8 +29,10 @@ spawned turn; each session still binds its trusted owner/feature independently.Production composition roots use `ai_usage::pg_recorder_with_enforcement`, whichconstructs configured prospective analytics counting alongside the owning-domain-observation service and adapter. The default-disabled `pg_recorder` remains for-internal/evaluation callers. DCS wraps its configured settling recorder with+observation service and adapter, or `ai_billing::composition::pg_settling_recorder`,+which wraps the same counting in the settling recorder. The default-disabled+`pg_recorder` remains for internal/evaluation callers. DCS, the agent harness,+MCP, and scheduled action wrap their configured settling recorder with`with_tracking(..., pg_tracking(...))`; only enabled, counted usage can requestlegacy settlement, and only when `ENABLE_AI_USAGE_BILLING` is enabled. Theobservation service accepts **no funding or rate-authorization capability**. No@@ -94,15 +96,15 @@ regressions, not live-provider or deployment verification.| Subagent in any common-context host | `crates/ai_tools/src/subagent.rs` replaces shared-context user with `RequestContext.user_id`, retains parent feature/entity | `agent::complete` binds a fresh or matching inherited scope → journal; no shared mutable user | `ai_tools` subagent isolation; `agent` scope/independent recorder tests. Shared system identity is not an authenticated payer || MCP native Anthropic tools and subagent | `AuthenticatedToolService` builds `RequestContext` from authenticated HTTP extensions; `services/mcp_service/src/context.rs` injects the configured recorder; `ToolServiceContext::FromRef` supplies inherited feature/entity and recorder | Independent Anthropic HTTP attempts and subagent attempts → journal, not merely successful tool aggregates; default feature remains Chat | Anthropic authenticated attribution/malformed-result/failure tests; MCP auth tests. MCP client's own model and remote MCP servers are not covered || Anthropic WebSearch, WebFetch, BashCodeExecution, TextEditorCodeExecution in all common hosts | Manual per-operation `FromRef<ToolServiceContext>` copies recorder + feature/entity; tool call always uses authenticated `RequestContext.user_id` | One journal attempt per independent native Messages HTTP execution. Counters recorded before SDK/result parsing, including non-2xx evidence; cancellation retains execution/evidence task. No separate tool fees | `anthropic --features toolset` tests. Native client has no application retry loop; any future retries must create fresh attempt IDs. Server-tool-specific non-token fees are intentionally not priced |-| In-memory harness sessions | `services/agent_harness_service/src/main.rs` common context → `RigTurnEngine`; trusted `TurnRequest.owner`, AgentSession feature | Captured scope carried into spawned turn; AgentLoop binds immutable owner scope; Rig attempts → journal, final analytics retained | `agent` spawned scope/cancellation tests; `agent_inmem` package tests. Non-user owners remain rejected by existing behavior |-| Harness session naming | Independent configured recorder supplied to `HaikuAgentSessionNameGenerator` in harness `main.rs`; session owner, ChatRename feature/entity | One-shot model attempts → journal (feature classification unchanged) | Existing name-generator/host tests plus shared completion tests; not covered merely by common-context injection |-| Harness repository selection | Independent configured recorder passed to `CursorContainerManager` in harness `main.rs`; repository chooser's trusted owner, AgentRepositoryChoice feature | Rust selection completion attempts → journal | Shared completion tests and host tests. Does not cover Cursor's external agent runtime |-| Harness trigger classifier + image captions | Independent recorder in `services/agent_harness_service/src/trigger.rs` passed to `FastModelTriggerJudge` and `VisionImageCaptioner`; authenticated message sender, Automation feature | Structured/image HTTP attempts → journal before existing errors are handled | `agent_trigger` caption tests + `agent` image-budget/cancellation/evidence tests. A non-user sender is not replaced with a system billing identity |+| In-memory harness sessions | `services/agent_harness_service/src/main.rs` settling recorder passed into the common context → `RigTurnEngine`; trusted `TurnRequest.owner`, AgentSession feature | Captured scope carried into spawned turn; AgentLoop binds immutable owner scope; Rig attempts → journal, final analytics retained | `agent` spawned scope/cancellation tests; `agent_inmem` package tests. Non-user owners remain rejected by existing behavior |+| Harness session naming | The harness's settling recorder supplied to `HaikuAgentSessionNameGenerator` in harness `main.rs`; session owner, ChatRename feature/entity | One-shot model attempts → journal (feature classification unchanged) | Existing name-generator/host tests plus shared completion tests; not covered merely by common-context injection |+| Harness repository selection | The harness's settling recorder passed to `CursorContainerManager` in harness `main.rs`; repository chooser's trusted owner, AgentRepositoryChoice feature | Rust selection completion attempts → journal | Shared completion tests and host tests. Does not cover Cursor's external agent runtime |+| Harness trigger classifier + image captions | The harness's settling recorder, handed to `services/agent_harness_service/src/trigger.rs` and passed to `FastModelTriggerJudge` and `VisionImageCaptioner`; authenticated message sender, Automation feature | Structured/image HTTP attempts → journal before existing errors are handled | `agent_trigger` caption tests + `agent` image-budget/cancellation/evidence tests. A non-user sender is not replaced with a system billing identity || Standalone trigger classifier + captions | Same explicit injection in `services/agent_trigger_service/src/main.rs` | Same journal attempt boundary, separate from harness and DCS | Standalone service and shared trigger tests. Caption timeout/error-to-None behavior retained; optional inference skips legacy quota refusal without AI fallback || DSS channel responder | `services/document_storage_service/src/main.rs` builds common context; responder binds requesting user, ChannelBot feature | AgentLoop HTTP attempts, native tools and subagents → journal; legacy aggregate retained | Shared agent/tool tests, DSS package tests || DSS channel classifier | Separate configured recorder supplied to `FastModelTriggerClassifier` in DSS `main.rs`; requesting user, ChannelBot | One-shot classification attempts → journal | Shared completion/structured tests. This is distinct from the responder's common context || DSS call summarizer, system task duplicate judge | Independent configured recorder injections in DSS `main.rs`; existing user/feature supplied by each producer | Calls using shared Rust completion APIs now produce journal attempts | Shared agent tests and DSS tests; this change does not change their attribution policy |-| Scheduled actions | `services/scheduled_action/src/bins/service.rs` common context; executor binds stored authenticated owner, Automation feature | AgentLoop attempts + native tools/subagents → journal | Scheduled-action package and shared scope tests; remote execution outside this process remains separate |+| Scheduled actions | `services/scheduled_action/src/bins/service.rs` settling recorder for the condition classifier; executor binds stored authenticated owner, Automation feature | AgentLoop attempts + native tools/subagents → journal | Scheduled-action package and shared scope tests; remote execution outside this process remains separate || DCS imports | DCS `main.rs` passes wrapped recorder to import service; import `drive_session` binds user, Import feature | Rust gather/Notion AgentLoop attempts → journal | Shared agent tests / DCS tests. Remote connector internals are not local model attempts || Memory and AI projections | Common host recorder (DCS; memory's own context uses the configured common-tool builder), with existing user-specific Memory / AiProjection contexts | Shared completion/AgentLoop attempts → journal, including native tool subcalls where available | Shared agent/tool regressions; no claim of new end-to-end producer deployment tests || Managed harness sandboxes (local/Daytona), external Cursor/Codex/Claude agents | Harness passes provider credentials / external account credentials directly to the runtime | **Not covered** by Rust common-context injection; runtime model calls bypass this HTTP adapter. Rust session naming/selection and calls back to authenticated MCP are the only covered portions | Future runtime-owned producer instrumentation must emit trusted per-attempt provider/model/counter/response IDs and immutable authenticated session attribution to an idempotent journal ingress. Legacy admission now gates Macro-funded managed sessions, but adds no runtime metering or credential/proxy redesign; externally funded runtime execution skips that gate |diff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.mdindex 0109c1574b..f8e439db91 100644--- a/docs/AI_QUOTA_ENFORCEMENT.md+++ b/docs/AI_QUOTA_ENFORCEMENT.md@@ -95,22 +95,62 @@ and the frontend reads allowances from itrosters keep their cost amounts in `ai_billing_period_allowance.included_cost_cents_by_user`;rows written before that column existed are priced at the configured allowance.-Only two hosts participate:+The hosts that participate:| Host | Gate | When disabled || --- | --- | --- |-| Authentication service | [`BillingServiceImpl::settle`](../crates/ai_billing/src/domain/service.rs) guards every caller: summary reads, overage and auto-reload changes, credit-purchase webhooks, and the internal settle endpoint. It also reserves and collects automatic credit reloads | Returns without reading entitlements, consuming credits, reloading credits, or touching Stripe. Credit purchases are still booked and remain unconsumed |-| Document cognition service | [`SettlingUsageRecorder`](../crates/ai_billing/src/outbound/settling_recorder.rs) requests settlement after counted usage lands | Usage is still recorded and counted; no settlement request is sent |--Every other host composes admission through-[`pg_admission_service`](../crates/ai_billing/src/composition.rs), which never-settles regardless of configuration. The authentication service's policy is-authoritative: a request from document cognition is a no-op there while its flag-is false, and with document cognition false the authentication service still-settles on summary reads, automatic reload changes, and credit purchases. Enable both+| Authentication service | [`BillingServiceImpl::settle`](../crates/ai_billing/src/domain/service.rs) guards every caller: summary reads, automatic reload changes, credit-purchase webhooks, the internal settle endpoint, and the [reconciliation sweep](#reconciliation-sweep-and-closed-periods). It also reserves and collects automatic credit reloads | Returns without reading entitlements, consuming credits, reloading credits, or touching Stripe; the sweep is not started. Credit purchases are still booked and remain unconsumed |+| Document cognition, agent harness, MCP, and scheduled action services | [`SettlingUsageRecorder`](../crates/ai_billing/src/outbound/settling_recorder.rs) requests settlement after counted usage lands. Document cognition composes it inline around its admission instance; the other three compose it through [`pg_settling_recorder`](../crates/ai_billing/src/composition.rs) with the [`SettlementRoute`](../crates/ai_billing/src/composition.rs) their configuration resolves | Usage is still recorded and counted; no settlement request is sent |++Every host composes admission through+[`pg_admission_service`](../crates/ai_billing/src/composition.rs) (or document+cognition's inline equivalent), which never settles regardless of+configuration. The authentication service's policy is authoritative: a request+from another host is a no-op there while its flag is false, and with every+other host false the authentication service still settles on summary reads,+automatic reload changes, credit purchases, and the sweep. Enable themtogether. Settlement without `ENABLE_AI_USAGE_ENFORCEMENT` finds nothing tosettle, because only counted rows are chargeable.+A requesting host other than document cognition presents the authentication+service's own internal key, `AUTHENTICATION_SERVICE_SECRET_KEY` (document+cognition already holds it). The key is optional in those hosts' configuration+while `ENABLE_AI_USAGE_BILLING` is false and mandatory once it is true: a host+enabling billing without the key fails startup rather than quietly recording+chargeable usage that only the sweep settles. Hosts without the recorder+(document storage, the standalone trigger service, memory) are covered by the+sweep alone; memory's usage is exempt and never chargeable.++### Reconciliation sweep and closed periods++A settlement request is a request: it can be lost (bounded HTTP retries, a+reload whose collector died between reserving and invoicing) or never come (a+period that closed after the payer's last completion). Two mechanisms in the+authentication service recover such usage without a customer action:++- **The sweep.** [`SettlementSweep`](../crates/ai_billing/src/domain/sweep.rs)+ runs on a schedule+ ([`run_settlement_sweep`](../crates/ai_billing/src/inbound/sweep_worker.rs):+ a minute after boot, then hourly) and settles, once each, every metered+ payer with a candidate in the last 24 hours+ ([`PgSettlementCandidates`](../crates/ai_billing/src/outbound/pg_settlement_candidates.rs)):+ users with counted usage, payers whose anchored subscription period began or+ ended, and payers holding a credit reload reserved more than ten minutes ago+ that was never collected. A failure for one payer is logged and the sweep+ continues. Settlement is idempotent and serialized per payer on the account+ row, so replicas may sweep concurrently and the task is simply aborted at+ shutdown.+- **Closed periods.** `settle` no longer stops at the previous period. Before+ the open period it settles every period frozen within the last+ [`RECONCILED_CLOSED_PERIODS`](../crates/ai_billing/src/domain/service.rs)+ (three) periods, each against its own frozen allowance and keyed exactly as+ its ledger, oldest first. A frozen period ends where the next period+ begins. The derived previous period is settled (from the live entitlement,+ as before) only when nothing was frozen in its place, and the last frozen+ period then ends where it begins, so no usage is ever settled under two+ keys. Closed periods are settled from the credits on hand; automatic reload+ still applies only to the open period.+Automatic credit reload is part of the same settlement. It fires only inside`BillingServiceImpl::settle`, so it shares the `ENABLE_AI_USAGE_BILLING` gate,and only for the current period, before prepaid credits are consumed: while@@ -256,25 +296,27 @@ and local regression suite. They are not evidence of live-provider, browser, ordeployed coverage. Shared factory [R](../crates/ai_usage/src/lib.rs) means`pg_recorder_with_enforcement`: configured analytics plus separate `pg_tracking`.Shared tools [T](../crates/ai_tools/src/build_context.rs) construct configured-admission and R. Admission itself never records usage or calls settlement.+admission and take the host's recorder (R, or+[`pg_settling_recorder`](../crates/ai_billing/src/composition.rs) where the host+requests settlement). Admission itself never records usage or calls settlement.| Surface / feature | Admission boundary | Production recorder / composition | Regression tests || --- | --- | --- | --- || Cognition chat / Chat | [chat handler](../services/document_cognition_service/src/api/stream/chat_message.rs) | [DCS main](../services/document_cognition_service/src/main.rs): configured `UsageServiceImpl` inside `SettlingUsageRecorder`, wrapped with `with_tracking` | [pre-creation refusal and permission precedence](../services/document_cognition_service/src/api/stream/chat_message/test.rs) || Structured completion / DynamicCompletionsApi | [completion handler](../services/document_cognition_service/src/api/structured_completion.rs) | DCS main, same recorder across both phases | [both phases and OpenAPI](../services/document_cognition_service/src/api/structured_completion/test.rs) || Chat naming / ChatRename | [chat renamer](../services/document_cognition_service/src/service/chat_renamer.rs) | DCS main, same recorder | [safe naming skip](../services/document_cognition_service/src/service/chat_renamer/test.rs) |-| Direct subagent / inherited feature | [operations service](../crates/ai_tools/src/ai_operations.rs), [subagent](../crates/ai_tools/src/subagent.rs) | Host common context: T, DCS main, or [MCP context](../services/mcp_service/src/context.rs) using R | [zero provider calls](../crates/ai_tools/src/ai_operations/test.rs), [concurrent caller isolation](../crates/ai_tools/src/subagent/test.rs) |+| Direct subagent / inherited feature | [operations service](../crates/ai_tools/src/ai_operations.rs), [subagent](../crates/ai_tools/src/subagent.rs) | Host common context: T, DCS main, or [MCP context](../services/mcp_service/src/context.rs) using `pg_settling_recorder` | [zero provider calls](../crates/ai_tools/src/ai_operations/test.rs), [concurrent caller isolation](../crates/ai_tools/src/subagent/test.rs) || Native Anthropic WebSearch/WebFetch/code tools / inherited feature | [invoke_server_tool](../crates/anthropic/src/toolset.rs) before both provider branches | Same common contexts via `FromRef`; observation only, **no legacy aggregate producer** | [tool attribution/refusal](../crates/anthropic/src/toolset/test.rs) || AI document editing / AiEditing | [document orchestration](../crates/documents/src/domain/ai_editing.rs) after verified edit receipt | Common context's recorder, existing per-model worker usage | [domain](../crates/documents/src/domain/ai_editing/test.rs), [direct tool and permission precedence](../crates/documents/src/inbound/toolset/edit_document/test.rs) || AI gather/Notion imports / Import | [import admission](../crates/import/src/domain/service/admission.rs), [execution/rechecks](../crates/import/src/domain/service.rs) | DCS main, wrapped recorder | [initial/retry/delayed/deterministic cases](../crates/import/src/domain/service/test/admission.rs), [HTTP](../crates/import/src/inbound/axum_router/test.rs) || Channel responder / ChannelBot | [bot service](../crates/channel_bots/src/domain/service.rs) | [DSS main](../services/document_storage_service/src/main.rs), common context T | [response refusal](../crates/channel_bots/src/domain/service/tests.rs) || Optional channel classification / ChannelBot | [trigger detector](../crates/channel_bots/src/domain/trigger_detector.rs) | DSS main, independent R for classifier | [explicit routing and inference skip](../crates/channel_bots/src/domain/trigger_detector/tests.rs) |-| Trigger inference and image captions / Automation | [trigger service](../crates/agent_trigger/src/domain/service.rs) | [standalone trigger main](../services/agent_trigger_service/src/main.rs) R; [harness trigger](../services/agent_harness_service/src/trigger.rs) receives R from harness main | [classification/caption refusal](../crates/agent_trigger/src/domain/service/test/admission.rs), [no system fallback](../crates/agent_trigger/src/outbound/fast_model_judge/test.rs) |-| Managed session ingress/dispatch/queue / AgentSession | [harness admission](../crates/agent_harness/src/domain/service/admission.rs) | [harness main](../services/agent_harness_service/src/main.rs) T for in-memory; managed sandbox inference has **no `ai_usage` producer** | [owner, authorization, runtime funding, restart, queue rejection/outage](../crates/agent_harness/src/domain/service/test/quota.rs), [HTTP](../crates/agent_session/src/inbound/axum_router/test.rs), [event shape](../crates/agent_session/src/domain/events/test.rs) |-| Direct in-memory ACP/provider commands / AgentSession | [admit_turn](../crates/agent_inmem/src/domain/admission.rs), [agent execution](../crates/agent_inmem/src/domain/agent.rs) | Harness main → manager → `RigTurnEngine`, common-context recorder | [direct ACP, queue, cancel, history](../crates/agent_inmem/src/domain/agent/test.rs), [manager](../crates/agent_inmem/src/outbound/manager/test.rs) |-| Session naming / ChatRename | [name generator gate](../crates/agent_session/src/domain/name_generation.rs) | Harness main, independent R for `HaikuAgentSessionNameGenerator` | [fallback without provider calls](../crates/agent_session/src/domain/name_generation/test.rs) |-| Repository chooser / AgentRepositoryChoice | [repository choice service](../crates/agent_harness/src/domain/repository_choice.rs) | Harness main → `CursorContainerManager`, independent R | [deterministic bypass / typed model refusal](../crates/agent_harness/src/domain/repository_choice/test.rs) |-| Scheduled manual/cron/event model work / Automation | [shared executor](../services/scheduled_action/src/domain/execution.rs) | [scheduled service](../services/scheduled_action/src/bins/service.rs), common context T | [claims, schedules, terminal events](../services/scheduled_action/src/domain/execution/test.rs), [manual HTTP](../services/scheduled_action/src/inbound/axum_router/test.rs) |+| Trigger inference and image captions / Automation | [trigger service](../crates/agent_trigger/src/domain/service.rs) | [standalone trigger main](../services/agent_trigger_service/src/main.rs) R; [harness trigger](../services/agent_harness_service/src/trigger.rs) receives the harness's settling recorder from harness main | [classification/caption refusal](../crates/agent_trigger/src/domain/service/test/admission.rs), [no system fallback](../crates/agent_trigger/src/outbound/fast_model_judge/test.rs) |+| Managed session ingress/dispatch/queue / AgentSession | [harness admission](../crates/agent_harness/src/domain/service/admission.rs) | [harness main](../services/agent_harness_service/src/main.rs): one `pg_settling_recorder` shared with T for in-memory; managed sandbox inference has **no `ai_usage` producer** | [owner, authorization, runtime funding, restart, queue rejection/outage](../crates/agent_harness/src/domain/service/test/quota.rs), [HTTP](../crates/agent_session/src/inbound/axum_router/test.rs), [event shape](../crates/agent_session/src/domain/events/test.rs) |+| Direct in-memory ACP/provider commands / AgentSession | [admit_turn](../crates/agent_inmem/src/domain/admission.rs), [agent execution](../crates/agent_inmem/src/domain/agent.rs) | Harness main → manager → `RigTurnEngine`, the harness's settling recorder passed into T | [direct ACP, queue, cancel, history](../crates/agent_inmem/src/domain/agent/test.rs), [manager](../crates/agent_inmem/src/outbound/manager/test.rs) |+| Session naming / ChatRename | [name generator gate](../crates/agent_session/src/domain/name_generation.rs) | Harness main, the same settling recorder for `HaikuAgentSessionNameGenerator` (exempt, so never counted or settled) | [fallback without provider calls](../crates/agent_session/src/domain/name_generation/test.rs) |+| Repository chooser / AgentRepositoryChoice | [repository choice service](../crates/agent_harness/src/domain/repository_choice.rs) | Harness main → `CursorContainerManager`, the same settling recorder | [deterministic bypass / typed model refusal](../crates/agent_harness/src/domain/repository_choice/test.rs) |+| Scheduled manual/cron/event model work / Automation | [shared executor](../services/scheduled_action/src/domain/execution.rs) | [scheduled service](../services/scheduled_action/src/bins/service.rs): `pg_settling_recorder` for the condition classifier; agent targets are funded and metered by the harness | [claims, schedules, terminal events](../services/scheduled_action/src/domain/execution/test.rs), [manual HTTP](../services/scheduled_action/src/inbound/axum_router/test.rs) || Scheduled agent targets / session funding policy | [target runner](../services/scheduled_action/src/domain/target_runner.rs) → session/harness admission | Target runtime's recorder, not duplicate scheduler metering | [delegation and typed errors](../services/scheduled_action/src/domain/target_runner/test.rs), [routine error transport](../crates/agent_session/src/inbound/routine_sessions/test.rs) || Memory, projection, call summary, dictation, chat rename / exempt | [shared admission policy](../crates/ai_billing/src/domain/admission.rs) skips quota; ordinary permissions still apply | DCS/DSS configured recorders; [memory context](../crates/memory/src/context.rs) uses T; DSS independent call-summary/dictation recorders use R | [all exempt features](../crates/ai_usage/src/domain/counting/test.rs), [no billing I/O](../crates/ai_billing/src/domain/admission/test.rs), [configured recording](../crates/ai_billing/src/composition/test.rs) || Existing system task duplicate judge / Automation | [system attribution](../crates/task_dedup/src/outbound/judge.rs), no user quota gate | DSS main, independent R; system events stay uncounted | [system counting](../crates/ai_usage/src/domain/counting/test.rs), [system recorder behavior](../crates/ai_billing/src/outbound/settling_recorder/test.rs) |@@ -335,6 +377,11 @@ procedure. Operators must approve and record each release gate.`AI_USAGE_INCLUDED_ALLOWANCE_CENTS`, `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`,and `AI_USAGE_OVERAGE_MARKUP_PERCENT` are mandatory for these same hostswhatever the flags say; see [Settlement](#settlement-enable_ai_usage_billing).+ Before `ENABLE_AI_USAGE_BILLING` is turned on for the agent harness, MCP, or+ scheduled action service, register `AUTHENTICATION_SERVICE_SECRET_KEY` (the+ authentication service's internal key, as document cognition already has it)+ in that service's Doppler config; those hosts refuse to start with billing on+ and the key absent.Verify the effective startup value for every replica/worker. Registration andhosted access require operator approval; code defaults are not proof of it.4. **Validate locally, then in an approved staging environment.** Use the checklist@@ -349,7 +396,9 @@ procedure. Operators must approve and record each release gate.startup policy, 402/503 behavior, new counted rows, summaries, and backgroundqueues before declaring activation complete. This enables legacy quotas, **notcredit collection or Stripe settlement**; those need `ENABLE_AI_USAGE_BILLING`- registered and enabled for the authentication and document cognition services.+ registered and enabled for the authentication service (which then also runs+ the reconciliation sweep) and for the document cognition, agent harness, MCP,+ and scheduled action services, with their authentication key registered.### Rollbackdiff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex d425998f49..0a83389d25 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -37,6 +37,7 @@ ai_toolset = { path = "../../crates/ai_toolset" }rmcp = { workspace = true }agent_trigger = { path = "../../crates/agent_trigger", features = ["outbound"] }ai_usage = { path = "../../crates/ai_usage" }+authentication_service_client = { path = "../../crates/authentication_service_client" }aws-sdk-sqs = { workspace = true }bot_id = { path = "../../crates/bot_id" }bots = { path = "../../crates/bots" }diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 81934de0d3..89b0f5dc31 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -52,6 +52,10 @@ macro_env_var::maybe_env_vars!(pub struct CodexOauthKmsKeyId;/// Rollout gate for sessions owned by a bot.pub struct EnableNonUserOwners;+ /// The authentication service's own internal key, which settlement+ /// requests for counted usage present. Required while+ /// `ENABLE_AI_USAGE_BILLING` is true; otherwise unused.+ pub struct AuthenticationServiceSecretKey;);/// The Pipedream project environment matching this deployment: production in@@ -70,6 +74,13 @@ 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,+ /// Default-off settlement of usage past allowances. When enabled, counted+ /// usage recorded here asks the authentication service to settle; that+ /// service's own policy decides whether it does.+ #[macro_config_default(ai_billing::AiUsageBilling::Disabled)]+ pub enable_ai_usage_billing: ai_billing::AiUsageBilling,+ /// Key settlement requests present to the authentication service.+ pub authentication_service_secret_key: AuthenticationServiceSecretKey,/// The free plan's hard monthly AI cap, in cents at provider cost./// Mandatory; set in Doppler.pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,@@ -268,13 +279,39 @@ impl Config {.context("ENABLE_NON_USER_OWNERS must be `true` or `false`")}+ /// Where this host's settlement requests go: the authentication service+ /// while `ENABLE_AI_USAGE_BILLING` is true, which then requires+ /// `AUTHENTICATION_SERVICE_SECRET_KEY`; nowhere otherwise.+ pub fn settlement_route(&self) -> anyhow::Result<ai_billing::composition::SettlementRoute> {+ let client = self+ .authentication_service_secret_key+ .value()+ .filter(|key| !key.trim().is_empty())+ .map(|key| {+ anyhow::Ok(std::sync::Arc::new(+ authentication_service_client::AuthServiceClient::new(+ key.to_owned(),+ macro_service_urls::AuthServiceUrl::new()?.to_string(),+ ),+ ))+ })+ .transpose()?;+ Ok(ai_billing::composition::SettlementRoute::from_policy(+ self.enable_ai_usage_billing,+ client,+ )?)+ }+/// Load the configuration from the environment.pub fn from_env() -> anyhow::Result<Self> {let enforcement = ai_usage::config::load_ai_usage_enforcement().map_err(|error| anyhow::anyhow!("{error}"))?;+ let billing = ai_billing::config::load_ai_usage_billing()+ .map_err(|error| anyhow::anyhow!("{error}"))?;let mut config = macro_config::ConfigLoader::load::<Config>().context("failed to load agent harness service config")?;config.enable_ai_usage_enforcement = enforcement;+ config.enable_ai_usage_billing = billing;Ok(config)}}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex db9b8e51f0..824d7d0327 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -309,8 +309,18 @@ async fn run() -> anyhow::Result<()> {config.enable_ai_usage_enforcement,config.ai_pricing(),);- let recorder =- ai_usage::pg_recorder_with_enforcement(pool.clone(), config.enable_ai_usage_enforcement);+ // One recorder for everything this process meters: in-memory agent+ // turns, session naming, trigger inference, and repository selection.+ // Counted usage asks the authentication service (which owns Stripe) to+ // settle the payer, the same way document cognition does, so credits are+ // consumed and a reload follows an agent turn rather than the next+ // Billing page view.+ let recorder = ai_billing::composition::pg_settling_recorder(+ pool.clone(),+ config.enable_ai_usage_enforcement,+ config.ai_pricing(),+ config.settlement_route()?,+ );let lifecycle_publisher = Arc::new(BrokerLifecyclePublisher::new(broker.clone()));let sessions = AgentSessionServiceImpl::new(session_repo.clone(),@@ -522,6 +532,7 @@ async fn run() -> anyhow::Result<()> {event_broker_tracker.clone(),config.enable_ai_usage_enforcement,config.ai_pricing(),+ recorder.clone(),).await.context("failed to build the in-memory agent tool context")?;diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rsindex 775ac79e18..29aa22d5e9 100644--- a/services/authentication_service/src/server.rs+++ b/services/authentication_service/src/server.rs@@ -539,6 +539,29 @@ pub async fn run() -> anyhow::Result<()> {.with_enforcement(config.enable_ai_usage_enforcement).with_billing(config.enable_ai_usage_billing),);+ // The floor under every settlement request: on a schedule, settle+ // everyone who recorded counted usage recently, whose period just closed,+ // or who holds a reload that was never collected. Settlement is+ // idempotent and serialized per payer in the database, so replicas may+ // sweep concurrently. Not started while billing is off: every settlement+ // would return before reading anything.+ let settlement_sweep = config.enable_ai_usage_billing.is_enabled().then(|| {+ tokio::spawn(ai_billing::inbound::run_settlement_sweep(+ ai_billing::domain::SettlementSweep::new(+ ai_billing_service.clone(),+ ai_billing::outbound::PgSettlementCandidates::new(db.clone()),+ ai_billing::outbound::RolesTeamsEntitlementSource::new(+ user_roles_and_permissions_service.clone(),+ teams_repo_impl.clone(),+ ),+ ),+ ai_billing::inbound::SETTLEMENT_SWEEP_INITIAL_DELAY,+ ai_billing::inbound::SETTLEMENT_SWEEP_INTERVAL,+ ))+ });+ if settlement_sweep.is_none() {+ tracing::info!("ai billing settlement sweep not started: ENABLE_AI_USAGE_BILLING is off");+ }let document_storage_service_client = Arc::new(document_storage_service_client);// The harness and scheduled-action services validate the fleet-wide// internal key, not this service's own inbound key.@@ -651,6 +674,12 @@ pub async fn run() -> anyhow::Result<()> {).await;+ // A sweep interrupted here leaves nothing half done: each settlement+ // step commits on its own and the next sweep, on any replica, resumes.+ if let Some(sweep) = settlement_sweep {+ sweep.abort();+ }+tracing::info!("waiting for event broker publishes to drain");event_broker_tracker.close();match tokio::time::timeout(EVENT_BROKER_DRAIN_TIMEOUT, event_broker_tracker.wait()).await {diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex cd6b677bb2..d760bcb97a 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -1305,11 +1305,15 @@ pub async fn run() -> anyhow::Result<()> {// Agent sessions belong to a different bot entirely// (`bot_id::MACRO_NEW_BOT_ID`, served by the harness), so the two paths// can never answer the same mention.+ // This host holds no authentication-service key, so its counted usage is+ // settled by that service's reconciliation sweep rather than requested+ // after each completion.let mut macro_agent_tool_context = ai_tools::build_tool_service_context_from_env(db.clone(),event_broker_tracker.clone(),config.enable_ai_usage_enforcement,config.ai_pricing(),+ ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement),).await.context("failed to build Macro agent tool context")?;diff --git a/services/mcp_service/Cargo.toml b/services/mcp_service/Cargo.tomlindex 784483616a..202631eeb4 100644--- a/services/mcp_service/Cargo.toml+++ b/services/mcp_service/Cargo.toml@@ -20,6 +20,7 @@ teams = { path = "../../crates/teams", default-features = false, features = ["ouai_tools = { path = "../../crates/ai_tools" }ai_toolset = { path = "../../crates/ai_toolset" }ai_usage = { path = "../../crates/ai_usage" }+authentication_service_client = { path = "../../crates/authentication_service_client" }anyhow = { workspace = true }async-trait = { workspace = true }attachment = { path = "../../crates/attachment" }diff --git a/services/mcp_service/src/config.rs b/services/mcp_service/src/config.rsindex 8abc6e2466..9789c6a959 100644--- a/services/mcp_service/src/config.rs+++ b/services/mcp_service/src/config.rs@@ -14,6 +14,10 @@ use macro_env_var::{env_vars, maybe_env_vars};maybe_env_vars! {/// Browser-reachable FusionAuth origin used for OAuth authorization redirects.pub struct FusionauthPublicUrl;+ /// The authentication service's own internal key, which settlement+ /// requests for counted usage present. Required while+ /// `ENABLE_AI_USAGE_BILLING` is true; otherwise unused.+ pub struct AuthenticationServiceSecretKey;/// Comma-separated hosts allowed as `https` OAuth redirect URI destinations/// for MCP clients. Falls back to [`DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`]/// when unset. Loopback `http` redirect URIs are always allowed and do not@@ -80,6 +84,13 @@ 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,+ /// Default-off settlement of usage past allowances. When enabled, counted+ /// usage recorded here asks the authentication service to settle; that+ /// service's own policy decides whether it does.+ #[macro_config_default(ai_billing::AiUsageBilling::Disabled)]+ pub enable_ai_usage_billing: ai_billing::AiUsageBilling,+ /// Key settlement requests present to the authentication service.+ pub authentication_service_secret_key: AuthenticationServiceSecretKey,/// The free plan's hard monthly AI cap, in cents at provider cost./// Mandatory; set in Doppler.pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,@@ -144,12 +155,38 @@ impl Config {)}+ /// Where this host's settlement requests go: the authentication service+ /// while `ENABLE_AI_USAGE_BILLING` is true, which then requires+ /// `AUTHENTICATION_SERVICE_SECRET_KEY`; nowhere otherwise.+ pub fn settlement_route(&self) -> anyhow::Result<ai_billing::composition::SettlementRoute> {+ let client = self+ .authentication_service_secret_key+ .value()+ .filter(|key| !key.trim().is_empty())+ .map(|key| {+ anyhow::Ok(std::sync::Arc::new(+ authentication_service_client::AuthServiceClient::new(+ key.to_owned(),+ macro_service_urls::AuthServiceUrl::new()?.to_string(),+ ),+ ))+ })+ .transpose()?;+ Ok(ai_billing::composition::SettlementRoute::from_policy(+ self.enable_ai_usage_billing,+ client,+ )?)+ }+pub fn from_env() -> anyhow::Result<Self> {let enforcement = ai_usage::config::load_ai_usage_enforcement().map_err(|error| anyhow::anyhow!("{error}"))?;+ let billing = ai_billing::config::load_ai_usage_billing()+ .map_err(|error| anyhow::anyhow!("{error}"))?;let mut config = macro_config::ConfigLoader::load::<Config>().context("failed to load mcp server config")?;config.enable_ai_usage_enforcement = enforcement;+ config.enable_ai_usage_billing = billing;Ok(config)}}diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 76ce494252..40b9ce2d06 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -448,8 +448,15 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To},);- let recorder =- ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement);+ // Counted usage from tools called over MCP asks the authentication+ // service (which owns Stripe) to settle the payer, the same way document+ // cognition does.+ let recorder = ai_billing::composition::pg_settling_recorder(+ db.clone(),+ config.enable_ai_usage_enforcement,+ config.ai_pricing(),+ config.settlement_route()?,+ );let tool_context = ToolServiceContext {connector_tool_context: ai_tools::build_connector_tool_context(db.clone(), None),diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.tomlindex b6d7d54d36..cbe2f1088e 100644--- a/services/scheduled_action/Cargo.toml+++ b/services/scheduled_action/Cargo.toml@@ -23,6 +23,7 @@ local_auth = ["macro_authorization/local_auth"][dependencies]ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }ai_usage = { path = "../../crates/ai_usage" }+authentication_service_client = { path = "../../crates/authentication_service_client" }bots = { path = "../../crates/bots", features = ["outbound"] }roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rsindex 9e6aad345c..4cd89d70a8 100644--- a/services/scheduled_action/src/bins/service.rs+++ b/services/scheduled_action/src/bins/service.rs@@ -161,11 +161,16 @@ async fn main() -> Result<()> {Arc::clone(&access),&config,)?),+ // Condition evaluation is the only model work this process meters+ // (agent targets are funded by the harness). Counted usage asks the+ // authentication service to settle the payer, as every other host does.Arc::new(JevClassifier::new(provider,- ai_usage::pg_recorder_with_enforcement(+ ai_billing::composition::pg_settling_recorder(db.clone(),config.enable_ai_usage_enforcement,+ config.ai_pricing(),+ config.settlement_route()?,),)),)),diff --git a/services/scheduled_action/src/config.rs b/services/scheduled_action/src/config.rsindex fb6f161376..8f2dfa3229 100644--- a/services/scheduled_action/src/config.rs+++ b/services/scheduled_action/src/config.rs@@ -9,7 +9,7 @@ use anyhow::Context;use database_env_vars::DatabaseUrl;use macro_auth::InternalApiKey;pub use macro_env::Environment;-use macro_env_var::env_vars;+use macro_env_var::{env_vars, maybe_env_vars};#[cfg(test)]mod test;@@ -19,6 +19,13 @@ env_vars! {pub struct KafkaBrokers;}+maybe_env_vars! {+ /// The authentication service's own internal key, which settlement+ /// requests for counted usage present. Required while+ /// `ENABLE_AI_USAGE_BILLING` is true; otherwise unused.+ pub struct AuthenticationServiceSecretKey;+}+/// The configuration parameters for the agent schedule service.#[derive(macro_config::MacroConfig)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]@@ -26,6 +33,13 @@ 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,+ /// Default-off settlement of usage past allowances. When enabled, counted+ /// usage recorded here asks the authentication service to settle; that+ /// service's own policy decides whether it does.+ #[macro_config_default(ai_billing::AiUsageBilling::Disabled)]+ pub enable_ai_usage_billing: ai_billing::AiUsageBilling,+ /// Key settlement requests present to the authentication service.+ pub authentication_service_secret_key: AuthenticationServiceSecretKey,/// The free plan's hard monthly AI cap, in cents at provider cost./// Mandatory; set in Doppler.pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,@@ -76,12 +90,38 @@ impl Config {)}+ /// Where this host's settlement requests go: the authentication service+ /// while `ENABLE_AI_USAGE_BILLING` is true, which then requires+ /// `AUTHENTICATION_SERVICE_SECRET_KEY`; nowhere otherwise.+ pub fn settlement_route(&self) -> anyhow::Result<ai_billing::composition::SettlementRoute> {+ let client = self+ .authentication_service_secret_key+ .value()+ .filter(|key| !key.trim().is_empty())+ .map(|key| {+ anyhow::Ok(std::sync::Arc::new(+ authentication_service_client::AuthServiceClient::new(+ key.to_owned(),+ macro_service_urls::AuthServiceUrl::new()?.to_string(),+ ),+ ))+ })+ .transpose()?;+ Ok(ai_billing::composition::SettlementRoute::from_policy(+ self.enable_ai_usage_billing,+ client,+ )?)+ }+pub fn from_env() -> anyhow::Result<Self> {let enforcement = ai_usage::config::load_ai_usage_enforcement().map_err(|error| anyhow::anyhow!("{error}"))?;+ let billing = ai_billing::config::load_ai_usage_billing()+ .map_err(|error| anyhow::anyhow!("{error}"))?;let mut config = macro_config::ConfigLoader::load::<Config>().context("failed to load agent schedule service config")?;config.enable_ai_usage_enforcement = enforcement;+ config.enable_ai_usage_billing = billing;Ok(config)}}diff --git a/services/scheduled_action/src/config/test.rs b/services/scheduled_action/src/config/test.rsindex f6d8bba1b5..49a7552dc2 100644--- a/services/scheduled_action/src/config/test.rs+++ b/services/scheduled_action/src/config/test.rs@@ -68,6 +68,51 @@ fn ai_usage_enforcement_defaults_off_and_requires_a_boolean() {}}+#[test]+fn settlement_requests_need_billing_on_and_the_authentication_key() {+ use ai_billing::composition::SettlementRoute;++ // Default: billing off, no key, nothing requested.+ let config: Config = serde_json::from_value(config_values()).unwrap();+ assert_eq!(+ config.enable_ai_usage_billing,+ ai_billing::AiUsageBilling::Disabled+ );+ assert!(matches!(+ config.settlement_route().unwrap(),+ SettlementRoute::Off+ ));++ // A key without billing is accepted and unused.+ let mut values = config_values();+ values["AUTHENTICATION_SERVICE_SECRET_KEY"] = json!("auth-key");+ let config: Config = serde_json::from_value(values).unwrap();+ assert!(matches!(+ config.settlement_route().unwrap(),+ SettlementRoute::Off+ ));++ // Billing is loaded like enforcement: a raw boolean, once, at startup.+ let mut values = config_values();+ values["ENABLE_AI_USAGE_BILLING"] = json!(true);+ let mut config: Config = serde_json::from_value(values).unwrap();+ assert_eq!(+ config.enable_ai_usage_billing,+ ai_billing::AiUsageBilling::Enabled+ );+ // Billing without the key is a startup error, not a silent downgrade.+ assert!(config.settlement_route().is_err());+ config.authentication_service_secret_key = serde_json::from_value(json!("auth-key")).unwrap();+ assert!(matches!(+ config.settlement_route().unwrap(),+ SettlementRoute::AuthService(_)+ ));++ let mut values = config_values();+ values["ENABLE_AI_USAGE_BILLING"] = json!("enabled");+ assert!(serde_json::from_value::<Config>(values).is_err());+}+#[test]fn event_routines_default_off_and_reuse_existing_brokers() {let config: Config = serde_json::from_value(config_values()).unwrap();