Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(cost): count a call's own estimate and fail closed on invalid caps

Steven Enamakel98a28cc164eb
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
index 12c748d749..32fd135ea8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
@@ -101,6 +101,9 @@ pub struct OpenHumanBudgetGate {
/// other background wiring sites opt in with
/// [`Self::as_background_work`](Self::as_background_work).
background: bool,
+ /// The ledger budgets are checked against; `None` reads the process-wide
+ /// cost tracker. Set by tests.
+ tracker: Option<Arc<cost::CostTracker>>,
}
impl OpenHumanBudgetGate {
@@ -124,6 +127,7 @@ impl OpenHumanBudgetGate {
compression,
last_model: RwLock::new(fallback),
background: false,
+ tracker: None,
}
}
@@ -135,6 +139,13 @@ impl OpenHumanBudgetGate {
/// **not** opt in: the gate's `Paused` arm waits for background work to be
/// re-enabled, which for a user-initiated chat means waiting until the turn
/// times out.
+ /// Check budgets against `tracker` instead of the process-wide one.
+ #[cfg(test)]
+ pub(crate) fn with_tracker(mut self, tracker: Arc<cost::CostTracker>) -> Self {
+ self.tracker = Some(tracker);
+ self
+ }
+
pub fn as_background_work(mut self) -> Self {
self.background = true;
self
@@ -154,7 +165,7 @@ impl OpenHumanBudgetGate {
if policies.is_empty() {
return None;
}
- let Some(tracker) = cost::try_global() else {
+ let Some(tracker) = self.tracker.clone().or_else(cost::try_global) else {
log::debug!("[tinyagents][budget] budgets configured but no cost tracker; not checked");
return None;
};
@@ -167,6 +178,11 @@ impl OpenHumanBudgetGate {
/// with no file on disk, or one that does not parse, keeps the policies
/// the gate was built with.
fn live_budgets(&self) -> Vec<crate::config::BudgetPolicy> {
+ // An embedder's in-memory config is authoritative: a file on disk
+ // must not replace the budgets it supplied.
+ if crate::core::runtime::CoreContext::current_embedder_config().is_some() {
+ return self.config.cost.budgets.clone();
+ }
#[derive(serde::Deserialize, Default)]
struct File {
#[serde(default)]
@@ -181,8 +197,8 @@ impl OpenHumanBudgetGate {
Ok(raw) => match toml::from_str::<File>(&raw) {
Ok(file) => file.cost.budgets,
Err(error) => {
- log::debug!(
- "[tinyagents][budget] config budgets unreadable ({error}); using the session's"
+ log::warn!(
+ "[tinyagents][budget] config budgets unreadable ({error}); keeping the session's"
);
self.config.cost.budgets.clone()
}
@@ -217,6 +233,15 @@ impl OpenHumanBudgetGate {
let call = cost::budget::CallUnderCheck {
model: &model,
scope: &scope,
+ estimated_usd: cost::catalog::estimate_cost_usd(
+ &model,
+ est.estimated_input_tokens,
+ est.estimated_output_tokens,
+ 0,
+ ),
+ estimated_tokens: est
+ .estimated_input_tokens
+ .saturating_add(est.estimated_output_tokens),
};
let verdict = match cost::budget::check_call(policies, tracker, call, chrono::Utc::now()) {
Ok(verdict) => verdict,
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs
index 87db35410c..5ffa34e7ed 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate_tests.rs
@@ -316,3 +316,21 @@ fn a_call_is_checked_against_its_own_model() {
.check_budgets_against(&estimate_for("planner"), &policies, &tracker)
.is_some());
}
+
+#[tokio::test]
+async fn acquire_refuses_an_over_budget_call() {
+ let (_tmp, tracker) = ledger_with(2.0, "planner");
+ let gate = budgeted_gate(crate::config::BudgetAction::Refuse).with_tracker(Arc::new(tracker));
+ let err = match gate.acquire(&estimate_for("planner")).await {
+ Err(err) => err,
+ Ok(_) => panic!("an over-budget call must be refused"),
+ };
+ match err {
+ tinyagents_harness::error::TinyAgentsError::LimitExceeded(message) => {
+ assert!(message.starts_with("BUDGET_EXCEEDED:"), "{message}");
+ }
+ other => panic!("expected LimitExceeded, got {other:?}"),
+ }
+ // The same gate admits an agent the budget does not cover.
+ assert!(gate.acquire(&estimate_for("orchestrator")).await.is_ok());
+}
diff --git a/crates/openhuman-core/src/platform/cost/budget.rs b/crates/openhuman-core/src/platform/cost/budget.rs
index 83be26e0dd..c699731da0 100644
--- a/crates/openhuman-core/src/platform/cost/budget.rs
+++ b/crates/openhuman-core/src/platform/cost/budget.rs
@@ -21,13 +21,20 @@ use crate::config::{BudgetAction, BudgetPeriod, BudgetPolicy, BudgetScope};
use super::types::{CostRecord, UsageScope};
-/// The call being checked: its model and attribution.
+/// The call being checked: its model, attribution and estimated size. The
+/// estimate counts towards the limits, so a call that would itself cross one
+/// is refused rather than the call after it.
#[derive(Debug, Clone, Copy)]
pub struct CallUnderCheck<'a> {
pub model: &'a str,
pub scope: &'a UsageScope,
+ pub estimated_usd: f64,
+ pub estimated_tokens: u64,
}
+/// The warn fraction used when a policy's is not a number.
+pub const DEFAULT_WARN_FRACTION: f64 = 0.8;
+
/// One policy that is at or near its limit for this call.
#[derive(Debug, Clone, PartialEq)]
pub struct BudgetHit {
@@ -137,23 +144,49 @@ pub fn evaluate(
if bucket_of(policy.scope, &usage.model, &usage.scope) != Some(bucket) {
continue;
}
- spent_usd += usage.cost_usd;
+ // A record with a non-finite cost is corrupt; it counts as free
+ // rather than turning the whole total into NaN.
+ if usage.cost_usd.is_finite() {
+ spent_usd += usage.cost_usd.max(0.0);
+ }
// Saturating: a corrupt record must not wrap a total back under
// its limit.
tokens = tokens.saturating_add(usage.input_tokens.saturating_add(usage.output_tokens));
}
+ if call.estimated_usd.is_finite() {
+ spent_usd += call.estimated_usd.max(0.0);
+ }
+ tokens = tokens.saturating_add(call.estimated_tokens);
+ // An invalid USD cap (negative, NaN) fails closed: it refuses rather
+ // than silently disabling the budget.
+ let invalid_cap = policy
+ .max_usd
+ .is_some_and(|max| !max.is_finite() || max < 0.0);
+ if invalid_cap {
+ log::warn!(
+ "[cost][budget] budget `{}` has an invalid max_usd {:?}; treating it as reached",
+ policy.name.as_deref().unwrap_or("unnamed"),
+ policy.max_usd
+ );
+ }
let over = |spent: f64, max: Option<f64>, fraction: f64| {
- max.is_some_and(|max| max >= 0.0 && spent >= max * fraction)
+ max.is_some_and(|max| spent >= max * fraction)
+ };
+ let warn_fraction = if policy.warn_fraction.is_finite() {
+ policy.warn_fraction.clamp(0.0, 1.0)
+ } else {
+ DEFAULT_WARN_FRACTION
};
- let warn_fraction = policy.warn_fraction.clamp(0.0, 1.0);
- // Token limits compare as integers; only the warn threshold, a
- // fraction of the limit, is computed in floating point.
- let exceeded = over(spent_usd, policy.max_usd, 1.0)
+ // Token limits compare as integers, the warn threshold in per-mille.
+ let warn_per_mille = (warn_fraction * 1000.0).round() as u128;
+ let exceeded = invalid_cap
+ || over(spent_usd, policy.max_usd, 1.0)
|| policy.max_tokens.is_some_and(|max| tokens >= max);
- let warning = over(spent_usd, policy.max_usd, warn_fraction)
- || policy.max_tokens.is_some_and(|max| {
- tokens >= max || (tokens as f64) >= (max as f64) * warn_fraction
- });
+ let warning = exceeded
+ || over(spent_usd, policy.max_usd, warn_fraction)
+ || policy
+ .max_tokens
+ .is_some_and(|max| u128::from(tokens) * 1000 >= u128::from(max) * warn_per_mille);
if exceeded || warning {
verdict.hits.push(BudgetHit {
policy: policy
diff --git a/crates/openhuman-core/src/platform/cost/budget_tests.rs b/crates/openhuman-core/src/platform/cost/budget_tests.rs
index 9c2f29129f..08c9c95a22 100644
--- a/crates/openhuman-core/src/platform/cost/budget_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/budget_tests.rs
@@ -36,7 +36,12 @@ fn policy(
}
fn call<'a>(model: &'a str, scope: &'a UsageScope) -> CallUnderCheck<'a> {
- CallUnderCheck { model, scope }
+ CallUnderCheck {
+ model,
+ scope,
+ estimated_usd: 0.0,
+ estimated_tokens: 0,
+ }
}
#[test]
@@ -316,3 +321,74 @@ fn token_limits_compare_exactly_and_totals_saturate() {
let verdict = evaluate(&[limit], &[near], call("m", &scope), now());
assert!(verdict.refusal().is_none(), "{verdict:?}");
}
+
+#[test]
+fn an_invalid_usd_cap_fails_closed() {
+ let scope = UsageScope::default();
+ for bad in [-1.0, f64::NAN] {
+ let mut cap = policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 0.0,
+ BudgetAction::Refuse,
+ );
+ cap.max_usd = Some(bad);
+ let verdict = evaluate(&[cap], &[], call("m", &scope), now());
+ assert!(verdict.refusal().is_some(), "{bad}: {verdict:?}");
+ }
+}
+
+#[test]
+fn a_nan_cost_record_does_not_poison_the_total() {
+ let scope = UsageScope::default();
+ let mut corrupt = spend(10, "m", None, None, 0.0);
+ corrupt.usage.cost_usd = f64::NAN;
+ let real = spend(11, "m", None, None, 5.0);
+ let cap = policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 4.0,
+ BudgetAction::Refuse,
+ );
+ let verdict = evaluate(&[cap], &[corrupt, real], call("m", &scope), now());
+ assert!(verdict.refusal().is_some(), "{verdict:?}");
+}
+
+#[test]
+fn the_calls_own_estimate_counts() {
+ let scope = UsageScope::default();
+ let earlier = spend(10, "m", None, None, 0.9);
+ let cap = policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 1.0,
+ BudgetAction::Refuse,
+ );
+ let mut big = call("m", &scope);
+ big.estimated_usd = 0.2;
+ assert!(evaluate(&[cap.clone()], &[earlier.clone()], big, now())
+ .refusal()
+ .is_some());
+ assert!(evaluate(&[cap], &[earlier], call("m", &scope), now())
+ .refusal()
+ .is_none());
+}
+
+#[test]
+fn a_nan_warn_fraction_falls_back_to_the_default() {
+ let scope = UsageScope::default();
+ let mut cap = policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 1.0,
+ BudgetAction::Warn,
+ );
+ cap.warn_fraction = f64::NAN;
+ let verdict = evaluate(
+ &[cap],
+ &[spend(10, "m", None, None, 0.85)],
+ call("m", &scope),
+ now(),
+ );
+ assert_eq!(verdict.hits.len(), 1, "{verdict:?}");
+}