use manifest_types::ThermodynamicCostRecord;
use std::collections::HashMap;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ThermodynamicsError {
#[error("Cost must be non-negative, got {0}")]
NegativeCost(f64),
#[error("Tenant '{tenant}' budget exceeded: ${current:.4} > ${limit:.2} limit")]
BudgetExceeded {
tenant: String,
current: f64,
limit: f64,
},
}
pub fn verify_cost_and_update(
budget_limit_usd: f64,
records: Vec<ThermodynamicCostRecord>,
new_record: ThermodynamicCostRecord,
) -> Result<Vec<ThermodynamicCostRecord>, ThermodynamicsError> {
if new_record.cost_usd < 0.0 {
return Err(ThermodynamicsError::NegativeCost(new_record.cost_usd));
}
let mut tenant_totals = HashMap::new();
for r in &records {
let entry = tenant_totals.entry(r.tenant_cid.clone()).or_insert(0.0);
*entry += r.cost_usd;
}
let current = tenant_totals
.get(&new_record.tenant_cid)
.cloned()
.unwrap_or(0.0);
if current + new_record.cost_usd > budget_limit_usd {
return Err(ThermodynamicsError::BudgetExceeded {
tenant: new_record.tenant_cid,
current: current + new_record.cost_usd,
limit: budget_limit_usd,
});
}
let mut updated_records = records;
updated_records.push(new_record);
Ok(updated_records)
}
#[cfg(test)]
mod tests {
use super::*;
use manifest_types::urn_models::ThermodynamicCostRecord;
#[test]
fn test_verify_cost_and_update() {
let budget = 100.0;
let records = vec![ThermodynamicCostRecord {
tenant_cid: "tenant_A".to_string(),
workflow_id: "wf_1".to_string(),
agent_cid: "agent_1".to_string(),
input_tokens: 100,
output_tokens: 50,
total_tokens: 150,
cost_usd: 40.0,
gpu_seconds: 5.0,
timestamp: 1600000000.0,
}];
let new_record = ThermodynamicCostRecord {
tenant_cid: "tenant_A".to_string(),
workflow_id: "wf_2".to_string(),
agent_cid: "agent_1".to_string(),
input_tokens: 50,
output_tokens: 20,
total_tokens: 70,
cost_usd: 50.0,
gpu_seconds: 2.0,
timestamp: 1600000100.0,
};
let res = verify_cost_and_update(budget, records.clone(), new_record.clone());
assert!(res.is_ok());
assert_eq!(res.unwrap().len(), 2);
let over_budget = ThermodynamicCostRecord {
cost_usd: 65.0,
..new_record
};
let res2 = verify_cost_and_update(budget, records, over_budget);
assert!(res2.is_err());
}
}