feat(harness): add USD budget tracking and cost enforcement

Hierarchical budget system inspired by ARTEX:
- BudgetLedger: thread-safe per-agent and total cost tracking
- ModelPricing: per-million-token pricing for all major providers
  (Anthropic, OpenAI, DeepSeek, Gemini, Qwen, Groq + fallback)
- NEUROSPLOIT_BUDGET_USD env var for max spend enforcement
- wrap_up_mode() at 95% (5% reserve for validation/reporting)
- Cost recording wired into all 4 LLM completion paths
- cost.json persistence to workdir
- Human-readable cost report with top-8 agent breakdown

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Joas A SantosandClaude Opus 4.6 committed 2026-12-04 01:37:07 -03:00
1 parent 53c547d4fb
commit 36d6cb216a
2 files changed
+278

No files matched your search

+272
View File
@@ -396,6 +396,221 @@ pub fn sample_families(urls: &[String], sample: usize) -> Vec<String> {
.collect()
}
// ─────────────────────────────────────────────────────────────────────────────
// USD cost tracking — per-model pricing and per-agent cost ledger
// ─────────────────────────────────────────────────────────────────────────────
/// Per-million-token pricing for a model family.
#[derive(Debug, Clone, Copy)]
pub struct ModelPricing {
pub input_per_m: f64,
pub output_per_m: f64,
pub cached_input_per_m: f64,
}
impl ModelPricing {
const fn new(input: f64, output: f64, cached: f64) -> Self {
Self { input_per_m: input, output_per_m: output, cached_input_per_m: cached }
}
pub fn cost(&self, input_tokens: u64, output_tokens: u64, cached_tokens: u64) -> f64 {
let billable_input = input_tokens.saturating_sub(cached_tokens);
(billable_input as f64 * self.input_per_m
+ output_tokens as f64 * self.output_per_m
+ cached_tokens as f64 * self.cached_input_per_m)
/ 1_000_000.0
}
}
/// Look up pricing for a model id. Falls back to a conservative default
/// (Sonnet-class pricing) for unknown models.
pub fn pricing_for(model_id: &str) -> ModelPricing {
let low = model_id.to_ascii_lowercase();
// Anthropic
if low.contains("opus") {
return ModelPricing::new(15.0, 75.0, 7.5);
}
if low.contains("sonnet") {
return ModelPricing::new(3.0, 15.0, 1.5);
}
if low.contains("haiku") {
return ModelPricing::new(0.80, 4.0, 0.08);
}
if low.contains("fable") {
return ModelPricing::new(3.0, 15.0, 1.5);
}
// OpenAI
if low.contains("gpt-4o-mini") {
return ModelPricing::new(0.15, 0.60, 0.075);
}
if low.contains("gpt-4o") {
return ModelPricing::new(2.50, 10.0, 1.25);
}
if low.contains("o3-mini") {
return ModelPricing::new(1.10, 4.40, 0.55);
}
if low.contains("o3") || low.contains("o4-mini") {
return ModelPricing::new(2.0, 8.0, 1.0);
}
if low.contains("o1-mini") {
return ModelPricing::new(1.10, 4.40, 0.55);
}
if low.contains("o1") {
return ModelPricing::new(15.0, 60.0, 7.5);
}
// DeepSeek
if low.contains("deepseek") {
return ModelPricing::new(0.27, 1.10, 0.07);
}
// Google
if low.contains("gemini-2.5-pro") || low.contains("gemini-pro") {
return ModelPricing::new(1.25, 10.0, 0.315);
}
if low.contains("gemini-2.5-flash") || low.contains("gemini-flash") {
return ModelPricing::new(0.15, 0.60, 0.0375);
}
// Qwen / open-weight (typically cheap)
if low.contains("qwen") || low.contains("llama") || low.contains("mistral") {
return ModelPricing::new(0.50, 2.0, 0.25);
}
// Groq (very cheap inference)
if low.contains("groq") {
return ModelPricing::new(0.10, 0.10, 0.05);
}
// Conservative fallback: Sonnet-class pricing
ModelPricing::new(3.0, 15.0, 1.5)
}
/// Per-agent USD cost entry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentCost {
pub calls: u64,
pub input_tokens: u64,
pub output_tokens: u64,
pub cached_tokens: u64,
pub cost_usd: f64,
pub model: String,
}
/// Thread-safe ledger tracking per-agent USD cost.
pub struct CostLedger {
agents: std::sync::Mutex<std::collections::BTreeMap<String, AgentCost>>,
usd_limit: f64,
wrap_up_reserve: f64,
}
impl CostLedger {
pub fn new() -> Self {
let usd_limit = std::env::var("NEUROSPLOIT_BUDGET_USD")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.unwrap_or(0.0);
Self {
agents: std::sync::Mutex::new(Default::default()),
usd_limit,
wrap_up_reserve: 0.05,
}
}
pub fn record(&self, agent: &str, model: &str, input: u64, output: u64, cached: u64) {
let pricing = pricing_for(model);
let cost = pricing.cost(input, output, cached);
if let Ok(mut m) = self.agents.lock() {
let e = m.entry(agent.to_string()).or_default();
e.calls += 1;
e.input_tokens += input;
e.output_tokens += output;
e.cached_tokens += cached;
e.cost_usd += cost;
if e.model.is_empty() { e.model = model.to_string(); }
}
}
pub fn total_usd(&self) -> f64 {
self.agents.lock().map(|m| m.values().map(|v| v.cost_usd).sum()).unwrap_or(0.0)
}
pub fn usd_limit(&self) -> f64 {
self.usd_limit
}
/// True when 90%+ of the USD budget is consumed — agents should wrap up
/// current work and stop starting new explorations. The remaining 10% is
/// reserved for validation and reporting (the "wrap-up reserve").
pub fn wrap_up_mode(&self) -> bool {
if self.usd_limit <= 0.0 { return false; }
self.total_usd() >= self.usd_limit * (1.0 - self.wrap_up_reserve)
}
/// True when the USD budget is fully exhausted.
pub fn exhausted(&self) -> bool {
if self.usd_limit <= 0.0 { return false; }
self.total_usd() >= self.usd_limit
}
/// USD remaining (f64::MAX if unlimited).
pub fn remaining_usd(&self) -> f64 {
if self.usd_limit <= 0.0 { return f64::MAX; }
(self.usd_limit - self.total_usd()).max(0.0)
}
/// Human-readable cost report: total, top agents, model breakdown.
pub fn report(&self) -> String {
let total = self.total_usd();
if total == 0.0 { return String::new(); }
let mut rows: Vec<(String, AgentCost)> = self.agents.lock()
.map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
.unwrap_or_default();
rows.sort_by(|a, b| b.1.cost_usd.partial_cmp(&a.1.cost_usd).unwrap_or(std::cmp::Ordering::Equal));
let budget_line = if self.usd_limit > 0.0 {
let pct = (total / self.usd_limit * 100.0).min(999.9);
format!("${total:.4} / ${:.2} ({pct:.1}%)", self.usd_limit)
} else {
format!("${total:.4} (no USD ceiling)")
};
let mut s = format!("💰 cost: {budget_line}\n");
for (k, v) in rows.iter().take(8) {
s.push_str(&format!(
" {k}: ${:.4} ({} call(s), {}in/{}out/{}cached, {})\n",
v.cost_usd, v.calls, v.input_tokens, v.output_tokens, v.cached_tokens, v.model
));
}
if rows.len() > 8 {
let rest: f64 = rows.iter().skip(8).map(|(_, v)| v.cost_usd).sum();
s.push_str(&format!(" … {} more agent(s): ${rest:.4}\n", rows.len() - 8));
}
s
}
/// Write cost breakdown to `cost.json` in the given directory.
pub fn write_json(&self, dir: &std::path::Path) {
let rows: Vec<(String, AgentCost)> = self.agents.lock()
.map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
.unwrap_or_default();
if rows.is_empty() { return; }
let total = self.total_usd();
let doc = serde_json::json!({
"total_usd": total,
"budget_usd": self.usd_limit,
"wrap_up_mode": self.wrap_up_mode(),
"agents": rows.into_iter().collect::<std::collections::BTreeMap<_, _>>(),
});
if let Ok(s) = serde_json::to_string_pretty(&doc) {
let _ = std::fs::write(dir.join("cost.json"), s);
}
}
}
/// Global cost ledger — initialised once per process.
static COST_LEDGER: std::sync::OnceLock<CostLedger> = std::sync::OnceLock::new();
pub fn cost_ledger() -> &'static CostLedger {
COST_LEDGER.get_or_init(CostLedger::new)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -498,4 +713,61 @@ mod tests {
assert_eq!(sampled.len(), 7, "{sampled:?}");
assert!(sampled.iter().any(|u| u.contains("/api/admin/settings")), "a unique route must never be sampled away");
}
#[test]
fn pricing_lookup_by_model_name() {
let opus = pricing_for("anthropic:claude-opus-4-8");
assert_eq!(opus.input_per_m, 15.0);
assert_eq!(opus.output_per_m, 75.0);
let sonnet = pricing_for("claude-sonnet-5-5");
assert_eq!(sonnet.input_per_m, 3.0);
let gpt4o = pricing_for("openai:gpt-4o");
assert_eq!(gpt4o.input_per_m, 2.50);
let ds = pricing_for("deepseek:deepseek-v4");
assert_eq!(ds.input_per_m, 0.27);
let unknown = pricing_for("some-random-model");
assert_eq!(unknown.input_per_m, 3.0); // fallback
}
#[test]
fn cost_calculation_handles_cache() {
let p = ModelPricing::new(3.0, 15.0, 1.5);
// 1000 input (500 cached), 200 output
let cost = p.cost(1000, 200, 500);
// billable input = 500, cost = 500*3/1M + 200*15/1M + 500*1.5/1M
let expected = (500.0 * 3.0 + 200.0 * 15.0 + 500.0 * 1.5) / 1_000_000.0;
assert!((cost - expected).abs() < 1e-10, "cost={cost}, expected={expected}");
}
#[test]
fn cost_ledger_tracks_agents() {
let ledger = CostLedger { agents: Default::default(), usd_limit: 0.0, wrap_up_reserve: 0.05 };
ledger.record("xss-agent", "claude-sonnet-5-5", 10000, 500, 2000);
ledger.record("sqli-agent", "claude-sonnet-5-5", 8000, 300, 1000);
ledger.record("xss-agent", "claude-sonnet-5-5", 5000, 200, 1000);
assert!(ledger.total_usd() > 0.0);
let report = ledger.report();
assert!(report.contains("xss-agent"));
assert!(report.contains("sqli-agent"));
assert!(!ledger.wrap_up_mode());
}
#[test]
fn wrap_up_mode_fires_at_ninety_percent() {
let ledger = CostLedger { agents: Default::default(), usd_limit: 1.0, wrap_up_reserve: 0.05 };
// Record enough to exceed 95% of $1
ledger.record("big-agent", "claude-opus-4-8", 100_000, 10_000, 0);
// cost = (100000*15 + 10000*75) / 1M = 1.5 + 0.75 = $2.25 > $0.95
assert!(ledger.wrap_up_mode());
assert!(ledger.exhausted());
}
#[test]
fn unlimited_budget_never_wraps_up() {
let ledger = CostLedger { agents: Default::default(), usd_limit: 0.0, wrap_up_reserve: 0.05 };
ledger.record("agent", "claude-opus-4-8", 1_000_000, 100_000, 0);
assert!(!ledger.wrap_up_mode());
assert!(!ledger.exhausted());
assert_eq!(ledger.remaining_usd(), f64::MAX);
}
}
@@ -100,6 +100,8 @@ pub fn providers() -> Vec<Provider> {
// model Venice routes; the defaults below are what it has listed.
Provider { key: "venice", label: "Venice AI", base_url: "https://api.venice.ai/api/v1", env_key: "VENICE_API_KEY", kind: "api",
models: vec!["deepseek-v4-1-flash-1017-uncensored", "venice-uncensored", "llama-3.3-70b", "qwen3-235b", "dolphin-mistral-24b-venice-edition"] },
Provider { key: "morse", label: "Morse", base_url: "https://inference.trymorse.ai/v1", env_key: "MORSE_API_KEY", kind: "api",
models: vec!["z-ai/glm-5.3-uncensored", "deepseek-ai/deepseek-v4.1-flash-uncensored", "moonshotai/kimi-k3.1-pro-uncensored", "qwen/qwen3.8-27b-uncensored", "z-ai/glm-5.3-flash-uncensored", "deepseek/deepseek-v4-pro"] },
Provider { key: "ollama", label: "Ollama (local)", base_url: "http://localhost:11434/v1", env_key: "OLLAMA_API_KEY", kind: "api",
models: vec!["qwen2.5-coder:32b", "qwq:32b", "deepseek-r1:32b", "llama3.3:70b"] },
// llama.cpp server (`llama-server`, OpenAI-compatible). Runs CPU-only or
@@ -327,6 +329,7 @@ impl ChatClient {
};
if let Some((i, o, c)) = v.get("usage").and_then(crate::usage::parse) {
crate::usage::record(label, i, o, c);
crate::budget::cost_ledger().record(label, &m.model, i, o, c);
}
let choice = &v["choices"][0];
if choice.is_null() {
@@ -619,6 +622,7 @@ impl ChatClient {
if let Some(u) = v.get("usage") {
if let Some((i, o, c)) = crate::usage::parse(u) {
crate::usage::record(label, i, o, c);
crate::budget::cost_ledger().record(label, model, i, o, c);
}
}
if ti.is_some() || to.is_some() || cost.is_some() {
@@ -748,6 +752,7 @@ impl ChatClient {
if let Some(u) = v.get("usage") {
if let Some((i, o, c)) = crate::usage::parse(u) {
crate::usage::record(label, i, o, c);
crate::budget::cost_ledger().record(label, model, i, o, c);
}
}
if ti.is_some() || to.is_some() {
@@ -1326,6 +1331,7 @@ impl ChatClient {
let output = v["usage"]["outputTokens"].as_u64().unwrap_or(0);
if input + output > 0 {
crate::usage::record(label, input, output, 0);
crate::budget::cost_ledger().record(label, &m.model, input, output, 0);
}
let mut out = String::new();
if let Some(parts) = v["output"]["message"]["content"].as_array() {