use crate::persona::Budget;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use troupekit_core::error::CoreError;
use troupekit_core::event::Usage;
use troupekit_core::tool::WEB_SEARCH;
use troupekit_providers::{CompletionRequest, Price, RESEND_NOTE_BYTES};
use troupekit_trace::{content, trace_span, Trace};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PeriodLimit {
pub key: String,
pub max_usd_micros: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Limits {
pub call: Option<u64>,
pub run: Option<u64>,
pub scope: Option<PeriodLimit>,
pub user: Option<PeriodLimit>,
}
impl Limits {
pub fn with_budget(mut self, budget: &Budget) -> Self {
let stricter = |a: Option<u64>, b: Option<u64>| match (a, b) {
(Some(x), Some(y)) => Some(x.min(y)),
(x, y) => x.or(y),
};
self.call = stricter(self.call, budget.call_usd_micros);
self.run = stricter(self.run, budget.run_usd_micros);
self
}
pub fn stricter(self, other: &Limits) -> Limits {
let lower = |a: Option<u64>, b: Option<u64>| match (a, b) {
(Some(x), Some(y)) => Some(x.min(y)),
(x, y) => x.or(y),
};
let period = |a: Option<PeriodLimit>, b: &Option<PeriodLimit>| match (a, b) {
(Some(x), Some(y)) if x.key == y.key => Some(PeriodLimit {
key: x.key,
max_usd_micros: x.max_usd_micros.min(y.max_usd_micros),
}),
(x, None) => x,
(_, Some(y)) => Some(y.clone()),
};
Limits {
call: lower(self.call, other.call),
run: lower(self.run, other.run),
scope: period(self.scope, &other.scope),
user: period(self.user, &other.user),
}
}
pub fn is_empty(&self) -> bool {
self.call.is_none() && self.run.is_none() && self.scope.is_none() && self.user.is_none()
}
}
pub use troupekit_core::store::UsageLedger;
#[derive(Debug, Default)]
pub struct InMemoryLedger(Mutex<HashMap<String, Usage>>);
impl InMemoryLedger {
pub fn usage(&self, key: &str) -> Usage {
self.0
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(key)
.copied()
.unwrap_or_default()
}
}
#[async_trait]
impl UsageLedger for InMemoryLedger {
async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
Ok(self.usage(key).cost_usd_micros)
}
async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
*self
.0
.lock()
.unwrap_or_else(|p| p.into_inner())
.entry(key.to_string())
.or_default() += usage;
Ok(())
}
}
pub fn estimate(req: &CompletionRequest, price: &Price) -> u64 {
let bytes = req.system.as_ref().map_or(0, String::len)
+ serde_json::to_string(&req.messages)
.expect("messages serialize")
.len()
+ serde_json::to_string(&req.tools)
.expect("tool specs serialize")
.len();
let input_tokens = u64::try_from(bytes.div_ceil(4)).expect("byte count fits in u64");
let searches: u64 = req
.tools
.iter()
.filter_map(|t| t.hosted)
.filter(|h| h.name() == WEB_SEARCH)
.map(|h| u64::from(h.max_uses()))
.sum();
price
.cost_usd_micros(&Usage {
input_tokens,
output_tokens: u64::from(req.max_tokens),
cost_usd_micros: 0,
})
.saturating_add(searches.saturating_mul(price.search_usd_micros))
}
pub fn estimate_calls(req: &CompletionRequest, price: &Price, extra: u32) -> u64 {
let first = estimate(req, price);
if extra == 0 {
return first;
}
let resent = price.cost_usd_micros(&Usage {
input_tokens: u64::from(req.max_tokens)
+ u64::try_from(RESEND_NOTE_BYTES.div_ceil(4)).expect("note bytes fit in u64"),
output_tokens: 0,
cost_usd_micros: 0,
});
let each = first.saturating_add(resent);
let total = first.saturating_add(each.saturating_mul(u64::from(extra)));
assert!(total >= first);
total
}
static TURNS: Mutex<BTreeMap<usize, Arc<tokio::sync::Mutex<()>>>> = Mutex::new(BTreeMap::new());
struct Turn {
id: usize,
lock: Arc<tokio::sync::Mutex<()>>,
guard: Option<tokio::sync::OwnedMutexGuard<()>>,
}
impl Turn {
async fn take(id: usize) -> Turn {
let lock = TURNS
.lock()
.unwrap_or_else(|p| p.into_inner())
.entry(id)
.or_default()
.clone();
let mut turn = Turn {
id,
lock,
guard: None,
};
turn.guard = Some(Arc::clone(&turn.lock).lock_owned().await);
turn
}
}
impl Drop for Turn {
fn drop(&mut self) {
drop(self.guard.take());
let mut turns = TURNS.lock().unwrap_or_else(|p| p.into_inner());
assert!(
Arc::strong_count(&self.lock) >= 2,
"the table and this turn hold the lock"
);
if Arc::strong_count(&self.lock) == 2 {
turns.remove(&self.id);
}
}
}
static RESERVED: Mutex<BTreeMap<(usize, String), u64>> = Mutex::new(BTreeMap::new());
#[must_use = "dropping the reservation releases it before the call is recorded"]
#[derive(Debug)]
pub(crate) struct Reservation {
slots: Vec<(usize, String)>,
amount: u64,
}
impl Drop for Reservation {
fn drop(&mut self) {
let mut table = RESERVED.lock().unwrap_or_else(|p| p.into_inner());
for slot in &self.slots {
let held = table.get_mut(slot).expect("a held slot is in the table");
assert!(
*held >= self.amount,
"a release never exceeds the reservations"
);
*held -= self.amount;
if *held == 0 {
table.remove(slot);
}
}
}
}
fn ledger_id(ledger: &dyn UsageLedger) -> usize {
std::ptr::from_ref(ledger).cast::<()>() as usize
}
fn reserved(id: usize, key: &str) -> u64 {
RESERVED
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(&(id, key.to_string()))
.copied()
.unwrap_or(0)
}
pub async fn check(
limits: &Limits,
price: &Price,
run_spent: u64,
estimate: u64,
ledger: &dyn UsageLedger,
) -> Result<Option<&'static str>, CoreError> {
Ok(admit(limits, price, run_spent, estimate, ledger)
.await?
.err())
}
pub(crate) async fn admit(
limits: &Limits,
price: &Price,
run_spent: u64,
estimate: u64,
ledger: &dyn UsageLedger,
) -> Result<Result<Reservation, &'static str>, CoreError> {
let mut span = trace_span!(
Trace::Budget,
"budget.check",
estimate = estimate,
run_spent = run_spent,
);
let periodic = limits.scope.is_some() || limits.user.is_some();
let id = ledger_id(ledger);
let _turn = if periodic {
Some(Turn::take(id).await)
} else {
None
};
let result = span
.instrument(crossed(limits, price, run_spent, estimate, ledger, id))
.await;
match &result {
Ok(layer) => span.record("crossed", layer.unwrap_or("none")),
Err(e) => {
span.fail("usage ledger failed");
span.record("error", content(e.to_string()));
}
}
Ok(match result? {
Some(layer) => Err(layer),
None => Ok(reserve(limits, id, estimate)),
})
}
fn reserve(limits: &Limits, id: usize, estimate: u64) -> Reservation {
if estimate == 0 {
return Reservation {
slots: Vec::new(),
amount: 0,
};
}
let mut slots: Vec<(usize, String)> = [&limits.scope, &limits.user]
.into_iter()
.flatten()
.map(|l| (id, l.key.clone()))
.collect();
slots.dedup();
let mut table = RESERVED.lock().unwrap_or_else(|p| p.into_inner());
for slot in &slots {
let held = table.entry(slot.clone()).or_insert(0);
*held = held.saturating_add(estimate);
}
Reservation {
slots,
amount: estimate,
}
}
async fn crossed(
limits: &Limits,
price: &Price,
run_spent: u64,
estimate: u64,
ledger: &dyn UsageLedger,
id: usize,
) -> Result<Option<&'static str>, CoreError> {
if limits.is_empty() {
return Ok(None);
}
if !price.verified {
return Ok(Some("unverified_price"));
}
if limits.call.is_some_and(|max| estimate > max) {
return Ok(Some("call"));
}
if limits
.run
.is_some_and(|max| run_spent.saturating_add(estimate) > max)
{
return Ok(Some("run"));
}
for (name, limit) in [("scope", &limits.scope), ("user", &limits.user)] {
if let Some(l) = limit {
let held = reserved(id, &l.key);
let Some(holding) = held.checked_add(estimate) else {
return Ok(Some(name));
};
let total = ledger.period_total(&l.key).await?.saturating_add(holding);
if total > l.max_usd_micros {
return Ok(Some(name));
}
}
}
Ok(None)
}
pub async fn record(
limits: &Limits,
ledger: &dyn UsageLedger,
usage: Usage,
) -> Result<(), CoreError> {
let mut keys: Vec<&str> = [&limits.scope, &limits.user]
.into_iter()
.flatten()
.map(|l| l.key.as_str())
.collect();
keys.dedup();
for key in keys {
ledger.record(key, usage).await?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct YieldingLedger {
inner: InMemoryLedger,
read: tokio::sync::Notify,
}
#[async_trait]
impl UsageLedger for YieldingLedger {
async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
let total = self.inner.period_total(key).await?;
self.read.notify_one();
tokio::task::yield_now().await;
Ok(total)
}
async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
self.inner.record(key, usage).await
}
}
fn capped(key: &str, max_usd_micros: u64) -> Limits {
Limits {
scope: Some(PeriodLimit {
key: key.into(),
max_usd_micros,
}),
..Limits::default()
}
}
#[tokio::test]
async fn a_release_during_a_pending_read_still_counts() {
let ledger = YieldingLedger::default();
let limits = capped("goal:race", 150);
let first = admit(&limits, &PRICE, 0, 100, &ledger)
.await
.unwrap()
.unwrap();
let settle = async {
ledger.read.notified().await;
record(
&limits,
&ledger,
Usage {
cost_usd_micros: 100,
..Usage::default()
},
)
.await
.unwrap();
drop(first);
};
let (second, ()) = tokio::join!(admit(&limits, &PRICE, 0, 100, &ledger), settle);
assert_eq!(
second.unwrap().err(),
Some("scope"),
"a call recorded and released during the read was counted zero times"
);
assert_eq!(ledger.inner.usage("goal:race").cost_usd_micros, 100);
}
#[tokio::test]
async fn a_busy_ledger_never_holds_up_another() {
let busy = InMemoryLedger::default();
let other = InMemoryLedger::default();
let held = Turn::take(ledger_id(&busy)).await;
let admitted = tokio::time::timeout(
std::time::Duration::from_secs(5),
admit(&capped("goal:other", 150), &PRICE, 0, 100, &other),
)
.await
.expect("an admission on another ledger waited for the busy one");
assert!(admitted.unwrap().is_ok());
let id = ledger_id(&busy);
drop(held);
assert!(
!TURNS.lock().unwrap().contains_key(&id),
"an unused lock stayed in the table"
);
}
#[tokio::test]
async fn reservations_near_u64_max_refuse_instead_of_overflowing() {
let ledger = InMemoryLedger::default();
let limits = capped("goal:max", u64::MAX);
let first = admit(&limits, &PRICE, 0, u64::MAX - 1, &ledger)
.await
.unwrap()
.unwrap();
assert_eq!(
check(&limits, &PRICE, 0, 2, &ledger).await.unwrap(),
Some("scope")
);
drop(first);
assert_eq!(reserved(ledger_id(&ledger), "goal:max"), 0);
}
#[tokio::test]
async fn admissions_on_a_yielding_ledger_take_turns() {
let ledger = YieldingLedger::default();
let limits = capped("goal:turns", 150);
let (a, b) = tokio::join!(
admit(&limits, &PRICE, 0, 100, &ledger),
admit(&limits, &PRICE, 0, 100, &ledger)
);
let (a, b) = (a.unwrap(), b.unwrap());
assert_eq!(
usize::from(a.is_ok()) + usize::from(b.is_ok()),
1,
"two admissions read the same total and both took the last room"
);
}
const PRICE: Price = Price {
input_usd_micros_per_mtok: 1_000_000,
output_usd_micros_per_mtok: 2_000_000,
verified: true,
long_context: None,
search_usd_micros: 0,
};
fn req() -> CompletionRequest {
CompletionRequest::user("x".repeat(400), 1000)
}
#[test]
fn estimate_calls_adds_each_resend() {
let r = req();
let one = estimate(&r, &PRICE);
assert_eq!(estimate_calls(&r, &PRICE, 0), one);
let resend = (1000 + RESEND_NOTE_BYTES.div_ceil(4)) as u64;
assert_eq!(estimate_calls(&r, &PRICE, 1), one + one + resend);
assert_eq!(estimate_calls(&r, &PRICE, 2), one + 2 * (one + resend));
assert_eq!(estimate_calls(&r, &Price::FREE, 3), 0);
}
#[test]
fn estimate_is_worst_case() {
let r = req();
let bytes = serde_json::to_string(&r.messages).unwrap().len() + 2;
let input = bytes.div_ceil(4) as u64;
assert_eq!(
estimate(&r, &PRICE),
PRICE.cost_usd_micros(&Usage {
input_tokens: input,
output_tokens: 1000,
cost_usd_micros: 0
})
);
assert!(estimate(&r, &PRICE) >= 2000 + 100);
assert_eq!(estimate(&r, &Price::FREE), 0);
}
#[test]
fn estimate_adds_every_allowed_search() {
use troupekit_core::tool::{HostedTool, ToolSpec};
let mut r = req();
let priced = Price {
search_usd_micros: 10_000,
..PRICE
};
let base = estimate(&r, &priced);
r.tools.push(ToolSpec {
name: "web_search".into(),
description: String::new(),
schema: serde_json::json!({}),
hosted: Some(HostedTool::WebSearch { max_uses: 3 }),
});
let tools = serde_json::to_string(&r.tools).unwrap().len() as u64;
assert!(estimate(&r, &priced) >= base + 30_000);
assert!(estimate(&r, &priced) <= base + 30_000 + tools.div_ceil(4) + 1);
}
#[tokio::test]
async fn each_layer_pauses_by_name() {
let ledger = InMemoryLedger::default();
ledger
.record(
"goal:1",
Usage {
cost_usd_micros: 900,
..Usage::default()
},
)
.await
.unwrap();
ledger
.record(
"user:1",
Usage {
cost_usd_micros: 5_000,
..Usage::default()
},
)
.await
.unwrap();
let scope = Some(PeriodLimit {
key: "goal:1".into(),
max_usd_micros: 1_000,
});
let user = Some(PeriodLimit {
key: "user:1".into(),
max_usd_micros: 5_050,
});
let cases = [
(
Limits {
call: Some(99),
..Limits::default()
},
0,
Some("call"),
),
(
Limits {
call: Some(100),
..Limits::default()
},
0,
None,
),
(
Limits {
run: Some(150),
..Limits::default()
},
60,
Some("run"),
),
(
Limits {
run: Some(150),
..Limits::default()
},
50,
None,
),
(
Limits {
scope: scope.clone(),
..Limits::default()
},
0,
None,
),
(
Limits {
scope: Some(PeriodLimit {
key: "goal:1".into(),
max_usd_micros: 999,
}),
..Limits::default()
},
0,
Some("scope"),
),
(
Limits {
scope,
user,
..Limits::default()
},
0,
Some("user"),
),
];
for (limits, spent, want) in cases {
assert_eq!(
check(&limits, &PRICE, spent, 100, &ledger).await.unwrap(),
want,
"{limits:?}"
);
}
}
#[tokio::test]
async fn concurrent_checks_never_share_the_last_room() {
let ledger = InMemoryLedger::default();
let limits = Limits {
scope: Some(PeriodLimit {
key: "goal:cap".into(),
max_usd_micros: 150,
}),
user: Some(PeriodLimit {
key: "goal:cap".into(),
max_usd_micros: 150,
}),
..Limits::default()
};
let (a, b) = tokio::join!(
admit(&limits, &PRICE, 0, 100, &ledger),
admit(&limits, &PRICE, 0, 100, &ledger)
);
let (a, b) = (a.unwrap(), b.unwrap());
assert_eq!(
usize::from(a.is_ok()) + usize::from(b.is_ok()),
1,
"both runs took the last room: {a:?} {b:?}"
);
let held = if a.is_ok() { a } else { b }.unwrap();
assert_eq!(
check(&limits, &PRICE, 0, 100, &ledger).await.unwrap(),
Some("scope"),
"a third check passed while the first call was in flight"
);
record(
&limits,
&ledger,
Usage {
cost_usd_micros: 40,
..Usage::default()
},
)
.await
.unwrap();
drop(held);
assert_eq!(reserved(ledger_id(&ledger), "goal:cap"), 0);
let next = admit(&limits, &PRICE, 0, 100, &ledger).await.unwrap();
assert!(next.is_ok(), "the recorded cost left room: {next:?}");
}
#[tokio::test]
async fn a_zero_estimate_releases_in_any_order() {
let ledger = InMemoryLedger::default();
let limits = Limits {
scope: Some(PeriodLimit {
key: "goal:free".into(),
max_usd_micros: 1_000,
}),
..Limits::default()
};
let id = ledger_id(&ledger);
let free = admit(&limits, &Price::FREE, 0, 0, &ledger)
.await
.unwrap()
.unwrap();
let paid = admit(&limits, &PRICE, 0, 100, &ledger)
.await
.unwrap()
.unwrap();
assert_eq!(reserved(id, "goal:free"), 100);
drop(paid);
drop(free);
assert_eq!(reserved(id, "goal:free"), 0);
for first_out in [true, false] {
let a = admit(&limits, &Price::FREE, 0, 0, &ledger)
.await
.unwrap()
.unwrap();
let b = admit(&limits, &Price::FREE, 0, 0, &ledger)
.await
.unwrap()
.unwrap();
if first_out {
drop(a);
drop(b);
} else {
drop(b);
drop(a);
}
assert_eq!(reserved(id, "goal:free"), 0);
}
}
#[tokio::test]
async fn one_key_for_both_caps_is_charged_once() {
let ledger = InMemoryLedger::default();
let cap = Some(PeriodLimit {
key: "goal:shared".into(),
max_usd_micros: 1_000,
});
let limits = Limits {
scope: cap.clone(),
user: cap,
..Limits::default()
};
record(
&limits,
&ledger,
Usage {
cost_usd_micros: 40,
..Usage::default()
},
)
.await
.unwrap();
assert_eq!(ledger.usage("goal:shared").cost_usd_micros, 40);
}
#[test]
fn persona_budget_only_tightens() {
let b = Budget {
call_usd_micros: Some(10),
run_usd_micros: None,
};
let host = Limits {
call: Some(20),
run: Some(30),
..Limits::default()
};
assert_eq!(
host.clone().with_budget(&b),
Limits {
call: Some(10),
run: Some(30),
..Limits::default()
}
);
let tight = Limits {
call: Some(5),
..Limits::default()
};
assert_eq!(tight.with_budget(&b).call, Some(5));
assert_eq!(Limits::default().with_budget(&b).call, Some(10));
}
#[tokio::test]
async fn unverified_price_pauses_only_with_limits() {
let ledger = InMemoryLedger::default();
let unverified = Price {
verified: false,
..Price::FREE
};
assert_eq!(
check(&Limits::default(), &unverified, 0, 0, &ledger)
.await
.unwrap(),
None
);
let limits = Limits {
run: Some(1),
..Limits::default()
};
assert_eq!(
check(&limits, &unverified, 0, 0, &ledger).await.unwrap(),
Some("unverified_price")
);
assert_eq!(
check(&limits, &Price::FREE, 0, 0, &ledger).await.unwrap(),
None
);
}
#[tokio::test]
async fn ledger_sums_per_key() {
let ledger = InMemoryLedger::default();
let limits = Limits {
scope: Some(PeriodLimit {
key: "goal:1".into(),
max_usd_micros: 10,
}),
user: Some(PeriodLimit {
key: "user:1".into(),
max_usd_micros: 10,
}),
..Limits::default()
};
let u = Usage {
input_tokens: 3,
output_tokens: 4,
cost_usd_micros: 7,
};
record(&limits, &ledger, u).await.unwrap();
record(&limits, &ledger, u).await.unwrap();
record(&Limits::default(), &ledger, u).await.unwrap();
assert_eq!(ledger.usage("goal:1"), u + u);
assert_eq!(ledger.period_total("user:1").await.unwrap(), 14);
assert_eq!(ledger.usage("other"), Usage::default());
}
}