Skip to main content

adk_core/
spend.rs

1//! One spend ledger for model calls and payments.
2//!
3//! A [`SpendLedger`] holds budget for spend that is about to happen and records spend
4//! that did happen, so a model call and a checkout draw on the same limits:
5//!
6//! 1. [`reserve`](SpendLedger::reserve) holds an amount against every [`SpendLimits`]
7//!    entry that covers the key, or fails with [`SpendError::LimitExceeded`].
8//! 2. [`commit`](SpendLedger::commit) records the actual amount and drops the hold.
9//! 3. [`release`](SpendLedger::release) drops the hold without recording spend.
10//!
11//! A hold that is neither committed nor released stops counting once its time to live
12//! passes, so a process that dies mid-call does not lock budget forever.
13//!
14//! Amounts are integer micro-USD (`1_000_000` is one US dollar). Period windows start at
15//! UTC midnight ([`SpendPeriod::Day`]) and on the first of the month at UTC midnight
16//! ([`SpendPeriod::Month`]).
17
18use std::collections::HashMap;
19use std::fmt;
20use std::sync::Arc;
21use std::time::Duration;
22
23use async_trait::async_trait;
24use chrono::{DateTime, Datelike, NaiveDate, NaiveTime, Utc};
25use serde::{Deserialize, Serialize};
26use tokio::sync::Mutex;
27
28use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, ErrorDetails, Result, SystemClock};
29
30/// How long a reservation holds budget when it is neither committed nor released.
31pub const DEFAULT_RESERVATION_TTL: Duration = Duration::from_secs(15 * 60);
32
33/// Error code carried by the [`AdkError`] a ledger returns when a reservation would
34/// exceed a limit.
35pub const SPEND_LIMIT_EXCEEDED_CODE: &str = "spend.limit_exceeded";
36
37/// Calendar window over which spend is summed. Boundaries are UTC.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum SpendPeriod {
41    /// The UTC calendar day.
42    Day,
43    /// The UTC calendar month.
44    Month,
45    /// All recorded spend.
46    Lifetime,
47}
48
49impl SpendPeriod {
50    /// Returns the inclusive start of the window that contains `at`, or `None` for
51    /// [`SpendPeriod::Lifetime`].
52    ///
53    /// # Example
54    ///
55    /// ```rust
56    /// use adk_core::SpendPeriod;
57    /// use chrono::{TimeZone, Utc};
58    ///
59    /// let at = Utc.with_ymd_and_hms(2026, 10, 10, 17, 30, 0).unwrap();
60    /// assert_eq!(
61    ///     SpendPeriod::Month.window_start(at),
62    ///     Some(Utc.with_ymd_and_hms(2026, 10, 1, 0, 0, 0).unwrap())
63    /// );
64    /// assert_eq!(SpendPeriod::Lifetime.window_start(at), None);
65    /// ```
66    pub fn window_start(self, at: DateTime<Utc>) -> Option<DateTime<Utc>> {
67        let day = match self {
68            Self::Day => at.date_naive(),
69            Self::Month => NaiveDate::from_ymd_opt(at.year(), at.month(), 1)?,
70            Self::Lifetime => return None,
71        };
72        Some(day.and_time(NaiveTime::MIN).and_utc())
73    }
74}
75
76impl fmt::Display for SpendPeriod {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.write_str(match self {
79            Self::Day => "day",
80            Self::Month => "month",
81            Self::Lifetime => "lifetime",
82        })
83    }
84}
85
86/// Names a scope of spend and the window it is summed over.
87///
88/// `org` is required. `agent` and `vendor` narrow the scope; `None` means "any". Passed
89/// to [`SpendLedger::reserve`], the key attributes the spend, and its `None` fields
90/// record the spend as unattributed on that dimension. Used as a limit, the key bounds
91/// every entry it [`covers`](Self::covers) within its `period`.
92///
93/// # Example
94///
95/// ```rust
96/// use adk_core::{SpendKey, SpendPeriod};
97///
98/// let gemini_daily = SpendKey::org("acme").with_vendor("gemini").per(SpendPeriod::Day);
99/// let call = SpendKey::org("acme").with_agent("researcher").with_vendor("gemini");
100/// assert!(gemini_daily.covers(&call));
101/// assert!(!gemini_daily.covers(&SpendKey::org("acme").with_vendor("openai")));
102/// ```
103#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub struct SpendKey {
106    /// Organization, tenant, or application the spend belongs to.
107    pub org: String,
108    /// Agent that spent, or `None` for any agent.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub agent: Option<String>,
111    /// Vendor paid (model provider or merchant), or `None` for any vendor.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub vendor: Option<String>,
114    /// Window the key sums over when used as a limit.
115    pub period: SpendPeriod,
116}
117
118impl SpendKey {
119    /// Creates a key for all of `org`'s spend over [`SpendPeriod::Lifetime`].
120    pub fn org(org: impl Into<String>) -> Self {
121        Self { org: org.into(), agent: None, vendor: None, period: SpendPeriod::Lifetime }
122    }
123
124    /// Narrows the key to one agent.
125    pub fn with_agent(mut self, agent: impl Into<String>) -> Self {
126        self.agent = Some(agent.into());
127        self
128    }
129
130    /// Narrows the key to one vendor.
131    pub fn with_vendor(mut self, vendor: impl Into<String>) -> Self {
132        self.vendor = Some(vendor.into());
133        self
134    }
135
136    /// Sets the window the key sums over.
137    pub fn per(mut self, period: SpendPeriod) -> Self {
138        self.period = period;
139        self
140    }
141
142    /// Returns `true` when spend attributed to `entry` falls inside this key's scope.
143    ///
144    /// The organizations must be equal, and each dimension this key names must equal the
145    /// entry's. The periods are not compared.
146    pub fn covers(&self, entry: &SpendKey) -> bool {
147        self.org == entry.org
148            && self.agent.as_ref().is_none_or(|agent| entry.agent.as_ref() == Some(agent))
149            && self.vendor.as_ref().is_none_or(|vendor| entry.vendor.as_ref() == Some(vendor))
150    }
151}
152
153impl fmt::Display for SpendKey {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        write!(f, "org={}", self.org)?;
156        if let Some(agent) = &self.agent {
157            write!(f, " agent={agent}")?;
158        }
159        if let Some(vendor) = &self.vendor {
160            write!(f, " vendor={vendor}")?;
161        }
162        write!(f, " period={}", self.period)
163    }
164}
165
166/// One cap: spend covered by `key` within `key.period` must not exceed `max_micro_usd`.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169pub struct SpendLimit {
170    /// Scope and window of the cap.
171    pub key: SpendKey,
172    /// Largest amount, in micro-USD, the scope may consume in one window.
173    pub max_micro_usd: u64,
174}
175
176/// The caps a ledger enforces on every reservation.
177///
178/// Every limit whose key [covers](SpendKey::covers) a reservation's key is checked, so
179/// an organization cap, an agent cap, and a vendor cap apply together.
180///
181/// # Example
182///
183/// ```rust
184/// use adk_core::{SpendKey, SpendLimits, SpendPeriod};
185///
186/// let limits = SpendLimits::new()
187///     .limit(SpendKey::org("acme").per(SpendPeriod::Day), 50_000_000)
188///     .limit(SpendKey::org("acme").with_vendor("gemini").per(SpendPeriod::Month), 500_000_000);
189/// assert_eq!(limits.applicable(&SpendKey::org("acme").with_vendor("gemini")).count(), 2);
190/// ```
191#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
192pub struct SpendLimits {
193    limits: Vec<SpendLimit>,
194}
195
196impl SpendLimits {
197    /// Creates an empty set, which lets every reservation through.
198    pub fn new() -> Self {
199        Self::default()
200    }
201
202    /// Adds a cap of `max_micro_usd` on spend covered by `key` within `key.period`.
203    pub fn limit(mut self, key: SpendKey, max_micro_usd: u64) -> Self {
204        self.limits.push(SpendLimit { key, max_micro_usd });
205        self
206    }
207
208    /// Returns every configured cap.
209    pub fn iter(&self) -> impl Iterator<Item = &SpendLimit> {
210        self.limits.iter()
211    }
212
213    /// Returns the caps that apply to spend attributed to `entry`.
214    pub fn applicable<'a>(&'a self, entry: &'a SpendKey) -> impl Iterator<Item = &'a SpendLimit> {
215        self.limits.iter().filter(move |limit| limit.key.covers(entry))
216    }
217}
218
219/// Identifies one reservation in a ledger.
220#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
221#[serde(transparent)]
222pub struct ReservationId(String);
223
224impl ReservationId {
225    /// Creates a random identifier.
226    pub fn generate() -> Self {
227        Self(uuid::Uuid::new_v4().to_string())
228    }
229
230    /// Returns the identifier as a string.
231    pub fn as_str(&self) -> &str {
232        &self.0
233    }
234}
235
236impl From<String> for ReservationId {
237    fn from(value: String) -> Self {
238        Self(value)
239    }
240}
241
242impl fmt::Display for ReservationId {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.write_str(&self.0)
245    }
246}
247
248/// Failures specific to spend ledgers. Converts into [`AdkError`].
249#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
250pub enum SpendError {
251    /// The reservation would take a scope past its cap.
252    #[error(
253        "spend limit exceeded for {limit}: {consumed_micro_usd} micro-USD already consumed plus {requested_micro_usd} requested exceeds the cap of {max_micro_usd}. Raise the limit or wait for the window to reset"
254    )]
255    LimitExceeded {
256        /// The cap that refused the reservation.
257        limit: SpendKey,
258        /// The cap in micro-USD.
259        max_micro_usd: u64,
260        /// Committed spend plus live holds in the cap's current window.
261        consumed_micro_usd: u64,
262        /// The amount the caller asked to reserve.
263        requested_micro_usd: u64,
264    },
265    /// The reservation does not exist or was already committed or released.
266    #[error(
267        "reservation {0} is unknown or already settled. Commit or release each reservation exactly once"
268    )]
269    UnknownReservation(ReservationId),
270    /// The amount does not fit the ledger's storage.
271    #[error("amount of {0} micro-USD is larger than the ledger can store")]
272    AmountTooLarge(u64),
273    /// The ledger's backing store could not be reached or failed.
274    #[error("spend ledger unavailable: {0}. No budget is reserved while the ledger is unreachable")]
275    Unavailable(String),
276}
277
278impl From<SpendError> for AdkError {
279    fn from(error: SpendError) -> Self {
280        let message = error.to_string();
281        match error {
282            SpendError::LimitExceeded {
283                limit,
284                max_micro_usd,
285                consumed_micro_usd,
286                requested_micro_usd,
287            } => {
288                let mut details = ErrorDetails::default();
289                details.metadata.insert(
290                    "limit".to_string(),
291                    serde_json::to_value(&limit).unwrap_or(serde_json::Value::Null),
292                );
293                details.metadata.insert("max_micro_usd".to_string(), max_micro_usd.into());
294                details
295                    .metadata
296                    .insert("consumed_micro_usd".to_string(), consumed_micro_usd.into());
297                details
298                    .metadata
299                    .insert("requested_micro_usd".to_string(), requested_micro_usd.into());
300                AdkError::new(
301                    ErrorComponent::Guardrail,
302                    ErrorCategory::Forbidden,
303                    SPEND_LIMIT_EXCEEDED_CODE,
304                    message,
305                )
306                .with_details(details)
307            }
308            SpendError::UnknownReservation(_) => AdkError::new(
309                ErrorComponent::Guardrail,
310                ErrorCategory::NotFound,
311                "spend.unknown_reservation",
312                message,
313            ),
314            SpendError::AmountTooLarge(_) => AdkError::new(
315                ErrorComponent::Guardrail,
316                ErrorCategory::InvalidInput,
317                "spend.amount_too_large",
318                message,
319            ),
320            SpendError::Unavailable(_) => AdkError::new(
321                ErrorComponent::Guardrail,
322                ErrorCategory::Unavailable,
323                "spend.ledger_unavailable",
324                message,
325            ),
326        }
327    }
328}
329
330/// Converts a USD amount, such as [`UsageMetadata::cost`](crate::UsageMetadata::cost), to
331/// micro-USD, rounding up. Returns `None` for a negative, NaN, or infinite amount.
332///
333/// # Example
334///
335/// ```rust
336/// use adk_core::usd_to_micro_usd;
337///
338/// assert_eq!(usd_to_micro_usd(0.0125), Some(12_500));
339/// assert_eq!(usd_to_micro_usd(-1.0), None);
340/// ```
341pub fn usd_to_micro_usd(usd: f64) -> Option<u64> {
342    if !usd.is_finite() || usd < 0.0 {
343        return None;
344    }
345    // Rounded first so binary noise (0.0125 * 1e6 = 12500.000000000002) does not add a
346    // micro-USD, then up so a fractional micro-USD is never dropped.
347    let micro = (usd * 1_000_000.0 * 1_000.0).round() / 1_000.0;
348    Some(micro.ceil() as u64)
349}
350
351/// Durable record of reserved and committed spend, shared by model calls and payments.
352///
353/// Implementations must make [`reserve`](Self::reserve) atomic with respect to other
354/// reservations: two concurrent calls must never both succeed when together they exceed
355/// a cap. A reservation that is neither committed nor released stops counting after the
356/// ledger's time to live.
357///
358/// # Example
359///
360/// ```rust
361/// use adk_core::{InMemorySpendLedger, SpendKey, SpendLedger, SpendLimits, SpendPeriod};
362///
363/// # async fn demo() -> adk_core::Result<()> {
364/// let ledger = InMemorySpendLedger::new(
365///     SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), 50_000_000),
366/// );
367/// let key = SpendKey::org("acme").with_agent("researcher").with_vendor("gemini");
368///
369/// let hold = ledger.reserve(&key, 20_000).await?;
370/// ledger.commit(hold, 12_500).await?;
371/// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 12_500);
372/// # Ok(())
373/// # }
374/// ```
375#[async_trait]
376pub trait SpendLedger: fmt::Debug + Send + Sync {
377    /// Holds `amount_micro_usd` for spend attributed to `key`.
378    ///
379    /// `key.period` is not consulted; every configured limit that covers `key` is
380    /// checked against committed spend plus live holds in that limit's current window.
381    ///
382    /// # Errors
383    ///
384    /// Returns an [`AdkError`] with code [`SPEND_LIMIT_EXCEEDED_CODE`] when a limit would
385    /// be exceeded, or `spend.ledger_unavailable` when the backing store fails. Neither
386    /// leaves a hold behind.
387    async fn reserve(&self, key: &SpendKey, amount_micro_usd: u64) -> Result<ReservationId>;
388
389    /// Records `actual_micro_usd` as spent and drops the reservation's hold.
390    ///
391    /// The amount is recorded even when it exceeds the reservation, a limit, or the
392    /// reservation has expired: the spend already happened, and later reservations must
393    /// see it.
394    ///
395    /// # Errors
396    ///
397    /// Returns `spend.unknown_reservation` when `id` is unknown or already settled.
398    async fn commit(&self, id: ReservationId, actual_micro_usd: u64) -> Result<()>;
399
400    /// Drops the reservation's hold without recording spend.
401    ///
402    /// # Errors
403    ///
404    /// Returns `spend.unknown_reservation` when `id` is unknown or already settled.
405    async fn release(&self, id: ReservationId) -> Result<()>;
406
407    /// Returns committed spend covered by `key` within the current `period` window.
408    ///
409    /// `key.period` is not consulted. Live holds are not included.
410    ///
411    /// # Errors
412    ///
413    /// Returns `spend.ledger_unavailable` when the backing store fails.
414    async fn spent(&self, key: &SpendKey, period: SpendPeriod) -> Result<u64>;
415}
416
417/// A held reservation in [`InMemorySpendLedger`].
418#[derive(Debug, Clone)]
419struct Hold {
420    key: SpendKey,
421    amount: u64,
422    expires_at: DateTime<Utc>,
423}
424
425/// Attribution of committed spend, without the period.
426#[derive(Debug, Clone, PartialEq, Eq, Hash)]
427struct Attribution {
428    org: String,
429    agent: Option<String>,
430    vendor: Option<String>,
431}
432
433impl Attribution {
434    fn of(key: &SpendKey) -> Self {
435        Self { org: key.org.clone(), agent: key.agent.clone(), vendor: key.vendor.clone() }
436    }
437
438    fn as_key(&self) -> SpendKey {
439        SpendKey {
440            org: self.org.clone(),
441            agent: self.agent.clone(),
442            vendor: self.vendor.clone(),
443            period: SpendPeriod::Lifetime,
444        }
445    }
446}
447
448#[derive(Debug, Default)]
449struct LedgerState {
450    /// Committed spend per attribution and UTC day.
451    committed: HashMap<(Attribution, NaiveDate), u64>,
452    holds: HashMap<ReservationId, Hold>,
453}
454
455impl LedgerState {
456    fn committed(&self, scope: &SpendKey, period: SpendPeriod, now: DateTime<Utc>) -> u64 {
457        let since = period.window_start(now).map(|start| start.date_naive());
458        self.committed
459            .iter()
460            .filter(|((attribution, day), _)| {
461                since.is_none_or(|since| *day >= since) && scope.covers(&attribution.as_key())
462            })
463            .fold(0u64, |total, (_, amount)| total.saturating_add(*amount))
464    }
465
466    fn held(&self, scope: &SpendKey, now: DateTime<Utc>) -> u64 {
467        self.holds
468            .values()
469            .filter(|hold| hold.expires_at > now && scope.covers(&hold.key))
470            .fold(0u64, |total, hold| total.saturating_add(hold.amount))
471    }
472}
473
474/// Process-local [`SpendLedger`] for tests, development, and single-process deployments.
475///
476/// Committed spend is kept per attribution and UTC day, so memory grows with the number
477/// of distinct keys and days rather than with the number of calls. Nothing survives a
478/// restart; use a SQL ledger from `adk-session` for durable budgets.
479///
480/// # Example
481///
482/// ```rust
483/// use adk_core::{InMemorySpendLedger, SpendKey, SpendLimits, SpendPeriod};
484/// use std::time::Duration;
485///
486/// let ledger = InMemorySpendLedger::new(
487///     SpendLimits::new().limit(SpendKey::org("acme").per(SpendPeriod::Day), 50_000_000),
488/// )
489/// .with_reservation_ttl(Duration::from_secs(60));
490/// # let _ = ledger;
491/// ```
492#[derive(Debug)]
493pub struct InMemorySpendLedger {
494    limits: SpendLimits,
495    ttl: Duration,
496    clock: Arc<dyn Clock>,
497    state: Mutex<LedgerState>,
498}
499
500impl InMemorySpendLedger {
501    /// Creates a ledger enforcing `limits`, with [`DEFAULT_RESERVATION_TTL`].
502    pub fn new(limits: SpendLimits) -> Self {
503        Self {
504            limits,
505            ttl: DEFAULT_RESERVATION_TTL,
506            clock: Arc::new(SystemClock),
507            state: Mutex::new(LedgerState::default()),
508        }
509    }
510
511    /// Sets how long an unsettled reservation holds budget.
512    pub fn with_reservation_ttl(mut self, ttl: Duration) -> Self {
513        self.ttl = ttl;
514        self
515    }
516
517    /// Sets the clock that picks period windows and expires reservations.
518    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
519        self.clock = clock;
520        self
521    }
522
523    /// Returns the limits this ledger enforces.
524    pub fn limits(&self) -> &SpendLimits {
525        &self.limits
526    }
527}
528
529impl Default for InMemorySpendLedger {
530    fn default() -> Self {
531        Self::new(SpendLimits::new())
532    }
533}
534
535#[async_trait]
536impl SpendLedger for InMemorySpendLedger {
537    async fn reserve(&self, key: &SpendKey, amount_micro_usd: u64) -> Result<ReservationId> {
538        let mut state = self.state.lock().await;
539        let now = self.clock.now();
540        for limit in self.limits.applicable(key) {
541            let consumed = state
542                .committed(&limit.key, limit.key.period, now)
543                .saturating_add(state.held(&limit.key, now));
544            if consumed.saturating_add(amount_micro_usd) > limit.max_micro_usd {
545                return Err(SpendError::LimitExceeded {
546                    limit: limit.key.clone(),
547                    max_micro_usd: limit.max_micro_usd,
548                    consumed_micro_usd: consumed,
549                    requested_micro_usd: amount_micro_usd,
550                }
551                .into());
552            }
553        }
554        let ttl = chrono::Duration::from_std(self.ttl).unwrap_or(chrono::Duration::MAX);
555        let id = ReservationId::generate();
556        state.holds.insert(
557            id.clone(),
558            Hold {
559                key: key.clone(),
560                amount: amount_micro_usd,
561                expires_at: now.checked_add_signed(ttl).unwrap_or(DateTime::<Utc>::MAX_UTC),
562            },
563        );
564        Ok(id)
565    }
566
567    async fn commit(&self, id: ReservationId, actual_micro_usd: u64) -> Result<()> {
568        let mut state = self.state.lock().await;
569        let hold = state.holds.remove(&id).ok_or(SpendError::UnknownReservation(id))?;
570        let bucket = (Attribution::of(&hold.key), self.clock.now().date_naive());
571        let total = state.committed.entry(bucket).or_default();
572        *total = total.saturating_add(actual_micro_usd);
573        Ok(())
574    }
575
576    async fn release(&self, id: ReservationId) -> Result<()> {
577        let mut state = self.state.lock().await;
578        state.holds.remove(&id).map(|_| ()).ok_or_else(|| SpendError::UnknownReservation(id).into())
579    }
580
581    async fn spent(&self, key: &SpendKey, period: SpendPeriod) -> Result<u64> {
582        Ok(self.state.lock().await.committed(key, period, self.clock.now()))
583    }
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589    use chrono::TimeZone;
590    use std::sync::Arc;
591
592    fn daily_cap(org: &str, max: u64) -> SpendLimits {
593        SpendLimits::new().limit(SpendKey::org(org).per(SpendPeriod::Day), max)
594    }
595
596    #[test]
597    fn windows_start_at_utc_boundaries() {
598        let at = Utc.with_ymd_and_hms(2026, 2, 28, 23, 59, 59).unwrap();
599        assert_eq!(
600            SpendPeriod::Day.window_start(at),
601            Some(Utc.with_ymd_and_hms(2026, 2, 28, 0, 0, 0).unwrap())
602        );
603        assert_eq!(
604            SpendPeriod::Month.window_start(at),
605            Some(Utc.with_ymd_and_hms(2026, 2, 1, 0, 0, 0).unwrap())
606        );
607        assert_eq!(SpendPeriod::Lifetime.window_start(at), None);
608    }
609
610    #[test]
611    fn a_key_covers_only_entries_inside_its_scope() {
612        let entry = SpendKey::org("acme").with_agent("a").with_vendor("gemini");
613        assert!(SpendKey::org("acme").covers(&entry));
614        assert!(SpendKey::org("acme").with_agent("a").covers(&entry));
615        assert!(!SpendKey::org("acme").with_agent("b").covers(&entry));
616        assert!(!SpendKey::org("other").covers(&entry));
617        // An unattributed entry is not inside a vendor-scoped cap.
618        assert!(!SpendKey::org("acme").with_vendor("gemini").covers(&SpendKey::org("acme")));
619    }
620
621    #[test]
622    fn usd_rounds_up_to_whole_micro_usd() {
623        assert_eq!(usd_to_micro_usd(0.0), Some(0));
624        assert_eq!(usd_to_micro_usd(1.0), Some(1_000_000));
625        assert_eq!(usd_to_micro_usd(0.000_000_1), Some(1));
626        assert_eq!(usd_to_micro_usd(f64::NAN), None);
627        assert_eq!(usd_to_micro_usd(f64::INFINITY), None);
628    }
629
630    #[tokio::test]
631    async fn a_reservation_over_the_cap_is_refused_with_a_structured_error() {
632        let ledger = InMemorySpendLedger::new(daily_cap("acme", 100));
633        let key = SpendKey::org("acme").with_vendor("gemini");
634        let held = ledger.reserve(&key, 60).await.unwrap();
635
636        let error = ledger.reserve(&key, 41).await.unwrap_err();
637        assert_eq!(error.code, SPEND_LIMIT_EXCEEDED_CODE);
638        assert_eq!(error.category, ErrorCategory::Forbidden);
639        assert_eq!(error.details.metadata["consumed_micro_usd"], 60);
640        assert_eq!(error.details.metadata["requested_micro_usd"], 41);
641
642        ledger.release(held).await.unwrap();
643        ledger.reserve(&key, 100).await.expect("a released hold frees its budget");
644    }
645
646    #[tokio::test]
647    async fn commit_records_the_actual_amount_and_frees_the_hold() {
648        let ledger = InMemorySpendLedger::new(daily_cap("acme", 100));
649        let key = SpendKey::org("acme").with_agent("a").with_vendor("gemini");
650        let held = ledger.reserve(&key, 80).await.unwrap();
651        ledger.commit(held.clone(), 30).await.unwrap();
652
653        assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await.unwrap(), 30);
654        assert_eq!(
655            ledger
656                .spent(&SpendKey::org("acme").with_vendor("openai"), SpendPeriod::Day)
657                .await
658                .unwrap(),
659            0
660        );
661        ledger.reserve(&key, 70).await.expect("only the committed 30 counts");
662        assert_eq!(ledger.commit(held, 1).await.unwrap_err().code, "spend.unknown_reservation");
663    }
664
665    #[tokio::test]
666    async fn concurrent_reservations_never_exceed_a_daily_cap() {
667        let ledger = Arc::new(InMemorySpendLedger::new(daily_cap("acme", 1_000)));
668        let tasks: Vec<_> = (0..64)
669            .map(|i| {
670                let ledger = ledger.clone();
671                tokio::spawn(async move {
672                    let key = SpendKey::org("acme").with_agent(format!("agent-{}", i % 4));
673                    ledger.reserve(&key, 100).await
674                })
675            })
676            .collect();
677        let mut granted = 0;
678        for task in tasks {
679            if task.await.unwrap().is_ok() {
680                granted += 1;
681            }
682        }
683        assert_eq!(granted, 10);
684    }
685
686    #[tokio::test]
687    async fn an_expired_reservation_stops_holding_budget() {
688        let clock = crate::ManualClock::new(Utc.with_ymd_and_hms(2026, 10, 15, 12, 0, 0).unwrap());
689        let ledger = InMemorySpendLedger::new(daily_cap("acme", 100))
690            .with_reservation_ttl(Duration::from_secs(60))
691            .with_clock(Arc::new(clock.clone()));
692        let key = SpendKey::org("acme");
693        let abandoned = ledger.reserve(&key, 100).await.unwrap();
694        assert!(ledger.reserve(&key, 1).await.is_err());
695
696        clock.advance(Duration::from_secs(61));
697        let next = ledger.reserve(&key, 100).await.expect("the expired hold is released");
698        ledger.release(next).await.unwrap();
699
700        // A late commit still records the spend that happened.
701        ledger.commit(abandoned, 40).await.unwrap();
702        assert_eq!(ledger.spent(&key, SpendPeriod::Day).await.unwrap(), 40);
703    }
704}