The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(cost): remove the spend cap entirely
M3gA-Mind552377c27d04
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex 6b68b0becb..1a21b6b8b5 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -94,6 +94,13 @@ required-features = ["rss-bench"]# files. #5021 is still the right fix for symbols named in the middle of an# otherwise gate-free target — required-features is the blunt instrument, and# it costs the whole target when the gate is off.+[[test]]+# Reproduction of the removed spend cap: needs its own process because the+# global CostTracker is a `OnceCell`, so a shared `--lib` process makes the+# spend state order-dependent.+name = "cost_cap_removed"+path = "../../tests/cost_cap_removed.rs"+[[test]]name = "observability_smoke"path = "../../tests/observability_smoke.rs"diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rsindex 855c2a4a19..19fd30a8d4 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs@@ -55,13 +55,12 @@//! `check_budget` (which honours `cost.enabled`), and the scheduler-gate permit//! is held for exactly the lifetime of the crate permit.-use std::sync::atomic::{AtomicU8, Ordering};use std::sync::Arc;use async_trait::async_trait;use parking_lot::RwLock;-use tinyagents_harness::error::{Result, TinyAgentsError};+use tinyagents_harness::error::Result;use tinyagents_harness::host::budget_gate::{BudgetGate, CallEstimate, CompressionHint, ContextState, Permit,};@@ -71,20 +70,7 @@ use crate::config::{Config, DEFAULT_MODEL};use crate::cron::scheduler_gate;use crate::inference::provider::types::UsageInfo;use crate::inference::tokenjuice::AgentTokenjuiceCompression;-use crate::platform::cost::{self, BudgetCheck};--/// Cached budget pressure, encoded for [`AtomicU8`].-///-/// A plain enum behind a lock would make [`BudgetGate::compression_hint`] —-/// which the runtime calls between every iteration of a turn — take a lock on-/// the hot path. An atomic load is what the trait's "read a counter, compare-/// against a threshold" wording asks for.-const PRESSURE_NORMAL: u8 = 0;-/// The warn threshold (`cost.warn_at_percent`) has been crossed.-const PRESSURE_WARNING: u8 = 1;-/// A daily or monthly limit has been reached. Set only transiently: an-/// `Exceeded` check also refuses the call it was made for.-const PRESSURE_EXCEEDED: u8 = 2;+use crate::platform::cost;/// Context utilization at which an *already budget-driven* soft hint is/// escalated to hard.@@ -113,8 +99,6 @@ pub struct OpenHumanBudgetGate {/// session config and re-stamped by each [`acquire`](Self::acquire); see/// mismatch (1) in the module docs.last_model: RwLock<String>,- /// Cached budget pressure; one of the `PRESSURE_*` constants.- pressure: AtomicU8,/// Whether this session's model calls are **background** work that must/// queue behind [`scheduler_gate`].///@@ -149,7 +133,6 @@ impl OpenHumanBudgetGate {config,compression,last_model: RwLock::new(fallback),- pressure: AtomicU8::new(PRESSURE_NORMAL),background: false,}}@@ -172,40 +155,6 @@ impl OpenHumanBudgetGate {self.last_model.read().clone()}- /// Re-reads the budget and caches the resulting pressure.- ///- /// `pending_usd` is the cost of a call about to be made (`0.0` when- /// reconciling after one). Returns the raw [`BudgetCheck`] so- /// [`acquire`](Self::acquire) can refuse on `Exceeded`; returns `None` when- /// the tracker is uninitialised (before bootstrap, and in unit tests),- /// which OpenHuman treats everywhere as "no budget opinion", never as a- /// refusal.- fn refresh_pressure(&self, pending_usd: f64) -> Option<BudgetCheck> {- let tracker = cost::try_global()?;- match tracker.check_budget(pending_usd) {- Ok(check) => {- let pressure = match check {- BudgetCheck::Allowed => PRESSURE_NORMAL,- BudgetCheck::Warning { .. } => PRESSURE_WARNING,- BudgetCheck::Exceeded { .. } => PRESSURE_EXCEEDED,- };- self.pressure.store(pressure, Ordering::Relaxed);- Some(check)- }- Err(err) => {- // A failed budget read is not a refusal: `check_budget` errors- // on a malformed estimate or a storage problem, neither of- // which is evidence the user is over budget. Refusing here- // would turn a bad JSONL file into "no agent may run".- log::warn!(- "[tinyagents][budget] check_budget failed; proceeding without \- a budget opinion: {err}"- );- None- }- }- }-/// Lowers a hint to what the agent's TokenJuice profile tolerates.////// * `Off` — the agent has opted out of TokenJuice, so this gate asks for@@ -260,22 +209,6 @@ impl BudgetGate for OpenHumanBudgetGate {0,);- if let Some(BudgetCheck::Exceeded {- current_usd,- limit_usd,- period,- }) = self.refresh_pressure(estimated_usd)- {- log::warn!(- "[tinyagents][budget] refusing model call: {period:?} spend ${current_usd:.4} \- of ${limit_usd:.4} limit (model={} est=${estimated_usd:.4})",- est.model- );- return Err(TinyAgentsError::LimitExceeded(format!(- "cost budget exceeded: {period:?} spend ${current_usd:.4} of ${limit_usd:.4} limit"- )));- }-log::debug!("[tinyagents][budget] awaiting capacity model={} agent={:?} in={} out={} tools={} \est_usd={estimated_usd:.6}",@@ -290,7 +223,7 @@ impl BudgetGate for OpenHumanBudgetGate {// arm polls until background AI is re-enabled, so a signed-out user on a// local/BYOK model — or anyone who simply paused background AI — would// watch their chat hang until the turn timeout. The budget checks above- // still apply either way; only the concurrency queue is skipped.+ // only the concurrency queue is skipped.if !self.background {let grant_id = uuid::Uuid::new_v4().to_string();log::trace!(@@ -381,37 +314,19 @@ impl BudgetGate for OpenHumanBudgetGate {// Reconcile after the spend: this is the I/O-bearing refresh that// `compression_hint` then reads for free.- self.refresh_pressure(0.0);Ok(())}- /// Advises compression when OpenHuman is under *budget* pressure.- ///- /// A single relaxed atomic load plus, at most, one float compare — no lock,- /// no I/O, safe to call between every iteration of a turn.+ /// Always [`CompressionHint::None`]: this gate has no budget opinion.///- /// Context fullness never originates a hint here. That question is- /// `SummarizationPolicy`'s, and duplicating its threshold is how the two- /// come to disagree; utilization is used only to escalate a hint the budget- /// already justified. Consequently a healthy budget yields- /// [`CompressionHint::None`] — this gate declining to *ask*, with the- /// crate's own policy still free to compress.- fn compression_hint(&self, state: &ContextState) -> CompressionHint {- let hint = match self.pressure.load(Ordering::Relaxed) {- PRESSURE_WARNING => {- let crowded = state- .utilization()- .is_some_and(|used| used >= ESCALATE_AT_UTILIZATION);- if crowded {- CompressionHint::Hard- } else {- CompressionHint::Soft- }- }- PRESSURE_EXCEEDED => CompressionHint::Hard,- _ => CompressionHint::None,- };- self.cap_hint(hint)+ /// It used to escalate compression as OpenHuman approached its spend cap.+ /// With the cap removed there is no budget pressure to read, and context+ /// fullness was never this gate's question — that belongs to+ /// `SummarizationPolicy`, which still compresses on its own threshold.+ /// Duplicating that threshold here is how the two came to disagree, so+ /// this stays a declined request rather than a second opinion.+ fn compression_hint(&self, _state: &ContextState) -> CompressionHint {+ CompressionHint::None}}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.rsindex 0817b4ac31..1cb44a6f59 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@@ -137,107 +137,16 @@ async fn recording_usage_is_a_soft_no_op_without_a_tracker() {}#[test]-fn a_healthy_budget_declines_to_ask_for_compression() {- // Union semantics: `None` is "not asking", not "do not compress". A- // full context with no budget pressure must still yield `None` here so- // the crate's own SummarizationPolicy stays the authority on the- // window.+fn this_gate_never_asks_for_compression() {+ // Union semantics: `None` is "not asking", not "do not compress". This+ // gate has no budget opinion left to escalate from — the spend cap that+ // used to drive the hint is gone — and context fullness was never its+ // question, so even a full window yields `None` and the crate's own+ // SummarizationPolicy stays the authority.let gate = gate(AgentTokenjuiceCompression::Full);assert_eq!(gate.compression_hint(&crowded()), CompressionHint::None);}-#[test]-fn budget_warning_asks_softly_and_escalates_only_when_context_is_crowded() {- let gate = gate(AgentTokenjuiceCompression::Full);- gate.pressure.store(PRESSURE_WARNING, Ordering::Relaxed);-- let roomy = ContextState {- message_count: 4,- prompt_tokens: 1_000,- context_window_tokens: Some(100_000),- iterations: 1,- };- assert_eq!(gate.compression_hint(&roomy), CompressionHint::Soft);- assert_eq!(gate.compression_hint(&crowded()), CompressionHint::Hard);-- // An unknown window must not escalate — `utilization()` is `None`- // there, and "unknown" is not "full".- let unknown_window = ContextState {- message_count: 4,- prompt_tokens: 999_999,- context_window_tokens: None,- iterations: 1,- };- assert_eq!(- gate.compression_hint(&unknown_window),- CompressionHint::Soft- );-}--#[test]-fn an_exceeded_budget_asks_hard_regardless_of_context() {- let gate = gate(AgentTokenjuiceCompression::Full);- gate.pressure.store(PRESSURE_EXCEEDED, Ordering::Relaxed);- assert_eq!(- gate.compression_hint(&ContextState::default()),- CompressionHint::Hard- );-}--#[test]-fn the_tokenjuice_profile_caps_the_hint_but_never_raises_it() {- for (profile, warning, exceeded) in [- (- AgentTokenjuiceCompression::Auto,- CompressionHint::Soft,- CompressionHint::Hard,- ),- (- AgentTokenjuiceCompression::Full,- CompressionHint::Soft,- CompressionHint::Hard,- ),- // Light tolerates non-lossy reductions only.- (- AgentTokenjuiceCompression::Light,- CompressionHint::Soft,- CompressionHint::Soft,- ),- // Off opts the agent out of TokenJuice entirely.- (- AgentTokenjuiceCompression::Off,- CompressionHint::None,- CompressionHint::None,- ),- ] {- let gate = gate(profile);- gate.pressure.store(PRESSURE_WARNING, Ordering::Relaxed);- assert_eq!(- gate.compression_hint(&ContextState::default()),- warning,- "warning under {}",- profile.as_str()- );- gate.pressure.store(PRESSURE_EXCEEDED, Ordering::Relaxed);- assert_eq!(- gate.compression_hint(&ContextState::default()),- exceeded,- "exceeded under {}",- profile.as_str()- );- }-}--#[test]-fn refreshing_pressure_without_a_tracker_has_no_opinion() {- let gate = gate(AgentTokenjuiceCompression::Full);- gate.pressure.store(PRESSURE_WARNING, Ordering::Relaxed);- assert!(gate.refresh_pressure(1.0).is_none());- // The uninitialised tracker must not clear a previously-cached- // pressure — absence of a reading is not a reading of "fine".- assert_eq!(gate.pressure.load(Ordering::Relaxed), PRESSURE_WARNING);-}-#[tokio::test]async fn is_usable_as_a_trait_object() {// Pins object safety: the harness stores this as `Arc<dyn BudgetGate>`.diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rsindex f35cf7532a..8361fdb737 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rs@@ -1,4 +1,5 @@-//! [`CostBudgetMiddleware`]: enforce daily/monthly cost budgets before a model+//! [`CostBudgetMiddleware`]: token-accounting parity observer. It used to+//! enforce daily/monthly cost budgets before a model//! call spends, and shadow-compare token accounting against the crate//! `BudgetMiddleware`.@@ -7,12 +8,11 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::{AgentRun, BudgetTracker, Middleware};-use tinyinference_llm::model::ModelRequest;-/// `before_model`: enforce OpenHuman's daily/monthly cost budgets **before** a-/// model call spends (issue #4249, Phase 5). Reads the global-/// [`CostTracker`](crate::platform::cost) and, when cost budgets are configured-/// and already exceeded, fails the run before the provider call; a warning+/// Token-accounting parity observer. It once enforced OpenHuman's+/// daily/monthly cost budgets before a model call spent (issue #4249, Phase 5),+/// failing the run before the provider call when a budget was already+/// exceeded. That cap is gone and nothing here refuses any more; a warning/// threshold logs but proceeds. This enforcement path stays **authoritative**.////// Self-gating: a no-op unless a global tracker exists and `config.enabled` with@@ -68,69 +68,9 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Cos"cost_budget"}- async fn before_model(- &self,- _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- _state: &(),- request: &mut ModelRequest,- ) -> TaResult<()> {- use crate::platform::cost::types::BudgetCheck;- let Some(tracker) = crate::platform::cost::try_global() else {- return Ok(());- };-- // #5016: exempt the CURRENT request when it is BYOK, not just BYOK- // history. Excluding BYOK from the managed totals alone still refuses a- // mixed-route user's own-key calls once their managed spend has- // legitimately crossed the cap — managed exhaustion would disable the- // provider OpenHuman never bills for, which is the whole bug. Classify- // this call's route and skip the gate when OpenHuman is not the biller.- if let Some(model) = request.model.as_deref() {- let route = crate::platform::cost::route::route_for_model(model);- if !route.counts_toward_budget() {- tracing::debug!(- %model,- ?route,- "[tinyagents::mw] BYOK/local route — skipping the managed budget gate (#5016)"- );- return Ok(());- }- }-- // Pass 0.0 to test whether we are *already* over budget before spending- // more (rather than projecting this call's cost, which needs a token- // estimate).- match tracker.check_budget(0.0) {- Ok(BudgetCheck::Exceeded {- current_usd,- limit_usd,- period,- }) => {- tracing::warn!(- %current_usd, %limit_usd, ?period,- "[tinyagents::mw] cost budget exceeded — failing before model call"- );- Err(tinyagents_harness::TinyAgentsError::LimitExceeded(format!(- "cost budget exceeded: {period:?} spend ${current_usd:.4} \u{2265} limit ${limit_usd:.4}"- )))- }- Ok(BudgetCheck::Warning {- current_usd,- limit_usd,- period,- }) => {- tracing::warn!(- %current_usd, %limit_usd, ?period,- "[tinyagents::mw] cost budget warning threshold reached"- );- Ok(())- }- _ => Ok(()),- }- }-- /// Shadow parity check (W2-budget-dedupe). Enforcement already happened per- /// call in `before_model`; here we only observe. Compares the observe-only+ /// Shadow parity check (W2-budget-dedupe). This middleware no longer+ /// enforces anything — the spend cap is gone — so observing is all it+ /// does. Compares the observe-only/// crate `BudgetMiddleware`'s accumulated token spend against the runtime's/// authoritative `AgentRun::usage` and logs `[budget_shadow]` divergence./// Never fails the run.diff --git a/crates/openhuman-core/src/config/schema/identity_cost.rs b/crates/openhuman-core/src/config/schema/identity_cost.rsindex 988627d699..f75bb3569d 100644--- a/crates/openhuman-core/src/config/schema/identity_cost.rs+++ b/crates/openhuman-core/src/config/schema/identity_cost.rs@@ -12,9 +12,10 @@ use std::collections::HashMap;pub struct CostConfig {/// Enable budget enforcement (default: true).///- /// When `true`, [`crate::platform::cost::CostTracker::check_budget`]- /// honours `daily_limit_usd` / `monthly_limit_usd` and refuses- /// over-budget requests via `BudgetCheck::Exceeded`.+ /// Retained for **recording**, not enforcement: nothing refuses a request+ /// on cost any more. `CostTracker::record_usage` is a no-op when this is+ /// `false`; `record_usage_unconditional` (the dashboard/telemetry path)+ /// ignores it.////// **Important:** as of the cost-dashboard PR this flag controls/// **enforcement only**, not telemetry capture. The dashboard@@ -27,25 +28,27 @@ pub struct CostConfig {#[serde(default = "default_cost_enabled")]pub enabled: bool,- /// Daily spending limit in USD (default: 10.00).+ /// Monthly budget in USD, for the dashboard only (default: 100.00).///- /// Applies to **managed (OpenHuman-credit) inference only** — see+ /// **This is a display target, not a cap.** Nothing in the core refuses a+ /// request when it is exceeded — the enforcement path was removed with the+ /// spend cap. It is the denominator behind the dashboard's budget gauge+ /// and status (`CostTracker::get_dashboard`), which is why it survives and+ /// why the settings copy still points at `cost.monthly_limit_usd`.+ ///+ /// Counts **managed (OpenHuman-credit) spend only** — see/// [`crate::platform::cost::route`]. Bring-your-own-key and local/// inference is billed by the user's own provider, so it is recorded for- /// the dashboard but never counted against this limit and can never- /// refuse a request (#5016).- #[serde(default = "default_daily_limit")]- pub daily_limit_usd: f64,-- /// Monthly spending limit in USD (default: 100.00). Managed-route only,- /// on the same terms as [`Self::daily_limit_usd`].+ /// the dashboard but never counted here (#5016); driving the gauge off the+ /// all-route total filled a pure-BYOK user's bar against a limit that+ /// could never fire.+ ///+ /// A retired `daily_limit_usd` key may still be present in existing config+ /// files. It is accepted and ignored — this struct does not+ /// `deny_unknown_fields`, so upgrading never fails to parse.#[serde(default = "default_monthly_limit")]pub monthly_limit_usd: f64,- /// Warn when spending reaches this percentage of limit (default: 80)- #[serde(default = "default_warn_percent")]- pub warn_at_percent: u8,-/// Per-model pricing (USD per 1M tokens)#[serde(default)]pub prices: HashMap<String, ModelPricing>,@@ -113,18 +116,10 @@ fn default_cost_enabled() -> bool {true}-fn default_daily_limit() -> f64 {- 10.0-}-fn default_monthly_limit() -> f64 {100.0}-fn default_warn_percent() -> u8 {- 80-}-fn default_dashboard_enabled() -> bool {true}@@ -145,9 +140,7 @@ impl Default for CostConfig {fn default() -> Self {Self {enabled: default_cost_enabled(),- daily_limit_usd: default_daily_limit(),monthly_limit_usd: default_monthly_limit(),- warn_at_percent: default_warn_percent(),prices: get_default_pricing(),dashboard: CostDashboardConfig::default(),}diff --git a/crates/openhuman-core/src/config/schema/identity_cost_tests.rs b/crates/openhuman-core/src/config/schema/identity_cost_tests.rsindex 895c3e47ef..7d76c93e59 100644--- a/crates/openhuman-core/src/config/schema/identity_cost_tests.rs+++ b/crates/openhuman-core/src/config/schema/identity_cost_tests.rs@@ -4,9 +4,7 @@ use super::*;fn cost_config_defaults() {let c = CostConfig::default();assert!(c.enabled);- assert_eq!(c.daily_limit_usd, 10.0);assert_eq!(c.monthly_limit_usd, 100.0);- assert_eq!(c.warn_at_percent, 80);assert!(!c.prices.is_empty());assert!(c.dashboard.enabled);assert_eq!(c.dashboard.currency, "USD");@@ -31,10 +29,20 @@ fn cost_dashboard_config_serde_roundtrip() {assert!((c.dashboard.alert_threshold - 0.9).abs() < f64::EPSILON);}+/// Pre-existing failure, unrelated to the spend cap: dc5c014da consolidated+/// pricing onto a single managed default and left this asserting `>= 3`, which+/// `get_default_pricing` — one entry — can never satisfy. Pinning the entry+/// that must exist says what the default pricing is actually for; a count says+/// nothing and goes stale the next time the catalogue is consolidated.#[test]fn cost_config_default_pricing_has_known_models() {let c = CostConfig::default();- assert!(c.prices.len() >= 3);+ assert!(+ c.prices+ .contains_key(crate::config::schema::types::MODEL_MANAGED_DEFAULT),+ "default pricing must cover the managed default model; got {:?}",+ c.prices.keys().collect::<Vec<_>>()+ );}#[test]@@ -42,7 +50,6 @@ fn cost_config_serde_roundtrip() {let c = CostConfig::default();let json = serde_json::to_string(&c).unwrap();let back: CostConfig = serde_json::from_str(&json).unwrap();- assert_eq!(back.daily_limit_usd, 10.0);assert_eq!(back.monthly_limit_usd, 100.0);}@@ -50,15 +57,29 @@ fn cost_config_serde_roundtrip() {fn cost_config_toml_with_custom_values() {let toml = r#"enabled = true- daily_limit_usd = 50.0monthly_limit_usd = 500.0- warn_at_percent = 90"#;let c: CostConfig = toml::from_str(toml).unwrap();assert!(c.enabled);- assert_eq!(c.daily_limit_usd, 50.0);assert_eq!(c.monthly_limit_usd, 500.0);- assert_eq!(c.warn_at_percent, 90);+}++/// Every install that ran a build with the daily cap still has+/// `daily_limit_usd` in its `config.toml`. Retiring the field must not make+/// those files unparseable: `CostConfig` does not `deny_unknown_fields`, so the+/// key is accepted and ignored. If that ever changes, every such user fails to+/// load their config on upgrade — a far worse bug than the cap was.+#[test]+fn retired_daily_limit_key_is_accepted_and_ignored() {+ let toml = r#"+ enabled = true+ daily_limit_usd = 10.0+ monthly_limit_usd = 500.0+ "#;+ let c: CostConfig =+ toml::from_str(toml).expect("a config carrying the retired daily key must still parse");+ assert!(c.enabled);+ assert_eq!(c.monthly_limit_usd, 500.0);}#[test]diff --git a/crates/openhuman-core/src/platform/cost/mod.rs b/crates/openhuman-core/src/platform/cost/mod.rsindex 45a2838bbb..5dc4c6e838 100644--- a/crates/openhuman-core/src/platform/cost/mod.rs+++ b/crates/openhuman-core/src/platform/cost/mod.rs@@ -15,6 +15,6 @@ pub use schemas::{};pub use tracker::CostTracker;pub use types::{- BudgetCheck, BudgetStatus, CostDashboard, CostRecord, CostSource, CostSummary, DailyCostEntry,- ModelStats, TokenUsage, UsagePeriod,+ BudgetStatus, CostDashboard, CostRecord, CostSource, CostSummary, DailyCostEntry, ModelStats,+ TokenUsage, UsagePeriod,};diff --git a/crates/openhuman-core/src/platform/cost/tracker.rs b/crates/openhuman-core/src/platform/cost/tracker.rsindex 97019bacfd..e9c5c7ba91 100644--- a/crates/openhuman-core/src/platform/cost/tracker.rs+++ b/crates/openhuman-core/src/platform/cost/tracker.rs@@ -1,7 +1,6 @@use super::route::route_for_model;use super::types::{- BudgetCheck, BudgetStatus, CostDashboard, CostRecord, CostSummary, DailyCostEntry, ModelStats,- TokenUsage, UsagePeriod,+ BudgetStatus, CostDashboard, CostRecord, CostSummary, DailyCostEntry, ModelStats, TokenUsage,};use crate::config::CostConfig;use anyhow::{anyhow, Context, Result};@@ -51,91 +50,11 @@ impl CostTracker {self.session_costs.lock()}- /// Check if a request is within budget.- ///- /// Only **managed-route** spend is considered (#5016). The local `[cost]`- /// limits cap spend against OpenHuman credits; bring-your-own-key and- /// local inference is billed by the user's own provider, so counting it- /// here produced a phantom limit — a pure-BYOK user accrued locally- /// *estimated* spend they were never charged for and got "You're out of- /// credits" at the default $10/day. See [`super::route`].- ///- /// A pure-BYOK user therefore has zero managed spend and can never trip- /// this gate. Real managed-credit exhaustion is unaffected: it is enforced- /// server-side by the backend, which returns its own billing error.- pub fn check_budget(&self, estimated_cost_usd: f64) -> Result<BudgetCheck> {- if !self.config.enabled {- return Ok(BudgetCheck::Allowed);- }-- if !estimated_cost_usd.is_finite() || estimated_cost_usd < 0.0 {- return Err(anyhow!(- "Estimated cost must be a finite, non-negative value"- ));- }-- let mut storage = self.lock_storage();- let (daily_cost, monthly_cost) = storage.get_aggregated_managed_costs()?;- // The all-routes totals exist purely to make the managed-vs-BYOK split- // visible in a debug log. `tracing` evaluates field expressions eagerly,- // so compute them only when that level is actually enabled rather than- // on every budget check in production.- if tracing::enabled!(tracing::Level::DEBUG) {- let (daily_all, monthly_all) = storage.get_aggregated_costs()?;- tracing::debug!(- daily_managed_usd = daily_cost,- monthly_managed_usd = monthly_cost,- daily_all_routes_usd = daily_all,- monthly_all_routes_usd = monthly_all,- daily_limit_usd = self.config.daily_limit_usd,- monthly_limit_usd = self.config.monthly_limit_usd,- "[cost] budget check against managed-route spend only (BYOK excluded, #5016)"- );- }-- // Check daily limit- let projected_daily = daily_cost + estimated_cost_usd;- if projected_daily > self.config.daily_limit_usd {- return Ok(BudgetCheck::Exceeded {- current_usd: daily_cost,- limit_usd: self.config.daily_limit_usd,- period: UsagePeriod::Day,- });- }-- // Check monthly limit- let projected_monthly = monthly_cost + estimated_cost_usd;- if projected_monthly > self.config.monthly_limit_usd {- return Ok(BudgetCheck::Exceeded {- current_usd: monthly_cost,- limit_usd: self.config.monthly_limit_usd,- period: UsagePeriod::Month,- });- }-- // Check warning thresholds- let warn_threshold = f64::from(self.config.warn_at_percent.min(100)) / 100.0;- let daily_warn_threshold = self.config.daily_limit_usd * warn_threshold;- let monthly_warn_threshold = self.config.monthly_limit_usd * warn_threshold;-- if projected_daily >= daily_warn_threshold {- return Ok(BudgetCheck::Warning {- current_usd: daily_cost,- limit_usd: self.config.daily_limit_usd,- period: UsagePeriod::Day,- });- }-- if projected_monthly >= monthly_warn_threshold {- return Ok(BudgetCheck::Warning {- current_usd: monthly_cost,- limit_usd: self.config.monthly_limit_usd,- period: UsagePeriod::Month,- });- }-- Ok(BudgetCheck::Allowed)- }+ // `check_budget` and `BudgetCheck` were removed with the spend cap. Nothing+ // in the core refuses a request on cost any more: managed-credit+ // exhaustion is enforced server-side by the backend, which returns its own+ // billing error, and that is the only spend limit a user can now hit.+ // Recording below is untouched — the dashboard still sees every cost./// Record a usage event.///diff --git a/crates/openhuman-core/src/platform/cost/tracker_tests.rs b/crates/openhuman-core/src/platform/cost/tracker_tests.rsindex 704fe6c98c..2c98362f7c 100644--- a/crates/openhuman-core/src/platform/cost/tracker_tests.rs+++ b/crates/openhuman-core/src/platform/cost/tracker_tests.rs@@ -24,19 +24,6 @@ fn cost_tracker_initialization() {assert!(!tracker.session_id().is_empty());}-#[test]-fn budget_check_when_disabled() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: false,- ..Default::default()- };-- let tracker = CostTracker::new(config, tmp.path()).unwrap();- let check = tracker.check_budget(1000.0).unwrap();- assert!(matches!(check, BudgetCheck::Allowed));-}-#[test]fn record_usage_and_get_summary() {let tmp = TempDir::new().unwrap();@@ -51,26 +38,6 @@ fn record_usage_and_get_summary() {assert_eq!(summary.by_model.len(), 1);}-#[test]-fn budget_exceeded_daily_limit() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 0.01, // Very low limit- ..Default::default()- };-- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- // Record managed-route usage that exceeds the limit. Only managed spend- // gates a request (#5016), so the model id has to be a backend tier slug.- let usage = TokenUsage::new(MANAGED_MODEL, 10000, 5000, 1.0, 2.0); // ~0.02 USD- tracker.record_usage(usage).unwrap();-- let check = tracker.check_budget(0.01).unwrap();- assert!(matches!(check, BudgetCheck::Exceeded { .. }));-}-#[test]fn summary_by_model_is_session_scoped() {let tmp = TempDir::new().unwrap();@@ -128,31 +95,6 @@ fn malformed_lines_are_ignored_while_loading() {assert!((today_cost - valid_usage.cost_usd).abs() < f64::EPSILON);}-#[test]-fn invalid_budget_estimate_is_rejected() {- let tmp = TempDir::new().unwrap();- let tracker = CostTracker::new(enabled_config(), tmp.path()).unwrap();-- let err = tracker.check_budget(f64::NAN).unwrap_err();- assert!(err- .to_string()- .contains("Estimated cost must be a finite, non-negative value"));-}--#[test]-fn invalid_budget_negative_is_rejected() {- let tmp = TempDir::new().unwrap();- let tracker = CostTracker::new(enabled_config(), tmp.path()).unwrap();- assert!(tracker.check_budget(-1.0).is_err());-}--#[test]-fn invalid_budget_infinity_is_rejected() {- let tmp = TempDir::new().unwrap();- let tracker = CostTracker::new(enabled_config(), tmp.path()).unwrap();- assert!(tracker.check_budget(f64::INFINITY).is_err());-}-#[test]fn record_usage_when_disabled_is_noop() {let tmp = TempDir::new().unwrap();@@ -201,149 +143,6 @@ fn record_usage_rejects_nan_cost() {assert!(tracker.record_usage(usage).is_err());}-#[test]-fn budget_warning_threshold() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 10.0,- warn_at_percent: 80,- monthly_limit_usd: 1000.0,- ..Default::default()- };- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- // Record usage just under warning threshold (80% of 10 = 8.0)- let _usage = TokenUsage::new("test/model", 100000, 50000, 1.0, 2.0);- // This has a cost, so let's just check the budget with a projected amount- let check = tracker.check_budget(8.5).unwrap();- assert!(- matches!(check, BudgetCheck::Warning { .. }),- "expected warning, got {check:?}"- );-}--#[test]-fn budget_monthly_exceeded() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 1000.0,- monthly_limit_usd: 0.01,- ..Default::default()- };- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- let usage = TokenUsage::new(MANAGED_MODEL, 10000, 5000, 1.0, 2.0);- tracker.record_usage(usage).unwrap();-- let check = tracker.check_budget(0.01).unwrap();- assert!(matches!(- check,- BudgetCheck::Exceeded {- period: UsagePeriod::Month,- ..- }- ));-}--// ── BYOK budget exemption (#5016 / #5127) ──────────────────────────────-//-// The reported bug: a user with no OpenHuman credits configured, routing all-// inference through their own OpenRouter key, accumulated locally *estimated*-// spend until they tripped the default $10/day cap and were told "You're out-// of credits" — for inference OpenHuman never billed them for.--#[test]-fn byok_spend_never_exceeds_the_daily_limit() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 0.01,- ..Default::default()- };- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- // Far past the $0.01 daily cap — and irrelevant, because it is BYOK.- let usage = TokenUsage::new(BYOK_MODEL, 10_000_000, 5_000_000, 1.0, 2.0);- tracker.record_usage(usage).unwrap();-- // Estimate 0.0, matching what `CostBudgetMiddleware::before_model` actually- // passes. Charging the whole $0.01 limit to the *current* request would trip- // the 80% warning on that request's own projected cost, which says nothing- // about whether the recorded BYOK history leaked into the budget.- let check = tracker.check_budget(0.0).unwrap();- assert!(- matches!(check, BudgetCheck::Allowed),- "BYOK spend must never gate a request, got {check:?}"- );-- // `Exceeded` is the only variant that actually blocks a request, so pin it- // separately: even a request that would consume the entire remaining limit- // must not be blocked by BYOK history.- assert!(- !matches!(- tracker.check_budget(0.01).unwrap(),- BudgetCheck::Exceeded { .. }- ),- "BYOK history must never push a request over the managed cap"- );-}--#[test]-fn byok_spend_never_exceeds_the_monthly_limit() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 1000.0,- monthly_limit_usd: 0.01,- ..Default::default()- };- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- let usage = TokenUsage::new(BYOK_MODEL, 10_000_000, 5_000_000, 1.0, 2.0);- tracker.record_usage(usage).unwrap();-- // Estimate 0.0, as `CostBudgetMiddleware::before_model` passes: charging the- // whole $0.01 limit to the current request would trip the 80% warning on- // that request's own cost, which says nothing about the BYOK history.- let check = tracker.check_budget(0.0).unwrap();- assert!(- matches!(check, BudgetCheck::Allowed),- "BYOK spend must never gate a request, got {check:?}"- );- assert!(- !matches!(- tracker.check_budget(0.01).unwrap(),- BudgetCheck::Exceeded { .. }- ),- "BYOK history must never push a request over the managed monthly cap"- );-}--#[test]-fn byok_spend_does_not_trip_the_warning_threshold_either() {- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 10.0,- warn_at_percent: 80,- monthly_limit_usd: 1000.0,- ..Default::default()- };- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- let mut usage = TokenUsage::new(BYOK_MODEL, 1000, 500, 1.0, 1.0);- usage.cost_usd = 9.5; // 95% of the daily limit, if it counted- tracker.record_usage(usage).unwrap();-- let check = tracker.check_budget(0.0).unwrap();- assert!(- matches!(check, BudgetCheck::Allowed),- "BYOK spend must not raise a budget warning, got {check:?}"- );-}-#[test]fn byok_spend_is_still_recorded_for_the_dashboard() {// Exempting BYOK from the *budget* must not hide it from usage reporting:@@ -361,45 +160,6 @@ fn byok_spend_is_still_recorded_for_the_dashboard() {assert!((summary.session_cost_usd - 4.25).abs() < 0.0001);}-#[test]-fn managed_spend_still_gates_when_byok_spend_is_also_present() {- // A mixed user: BYOK for chat, managed for background workloads. Only the- // managed portion may push them over the limit.- let tmp = TempDir::new().unwrap();- let config = CostConfig {- enabled: true,- daily_limit_usd: 5.0,- monthly_limit_usd: 1000.0,- ..Default::default()- };- let tracker = CostTracker::new(config, tmp.path()).unwrap();-- let mut byok = TokenUsage::new(BYOK_MODEL, 1000, 500, 1.0, 1.0);- byok.cost_usd = 100.0; // dwarfs the limit, and must be ignored- tracker.record_usage(byok).unwrap();-- let mut managed = TokenUsage::new(MANAGED_MODEL, 1000, 500, 1.0, 1.0);- managed.cost_usd = 2.0; // under the $5 limit on its own- tracker.record_usage(managed).unwrap();-- assert!(- matches!(tracker.check_budget(0.0).unwrap(), BudgetCheck::Allowed),- "managed spend is under the limit; BYOK spend must not push it over"- );-- let mut more_managed = TokenUsage::new(MANAGED_MODEL, 1000, 500, 1.0, 1.0);- more_managed.cost_usd = 4.0; // 2.0 + 4.0 = 6.0 > 5.0- tracker.record_usage(more_managed).unwrap();-- assert!(- matches!(- tracker.check_budget(0.0).unwrap(),- BudgetCheck::Exceeded { .. }- ),- "managed spend over the limit must still gate"- );-}-#[test]fn legacy_byok_records_are_exempt_after_an_aggregate_rebuild() {// Records persisted by builds that predate #5016 carry no route field. The@@ -413,17 +173,15 @@ fn legacy_byok_records_are_exempt_after_an_aggregate_rebuild() {let config = CostConfig {enabled: true,- daily_limit_usd: 10.0,monthly_limit_usd: 10.0,..Default::default()};let tracker = CostTracker::new(config, tmp.path()).unwrap();- assert!(- matches!(tracker.check_budget(0.0).unwrap(), BudgetCheck::Allowed),- "pre-existing BYOK history must not keep an upgraded user blocked"- );- // …while still showing up in the usage figures.+ // Nothing refuses a request on cost any more, so what matters on upgrade is+ // that the legacy rows are classified correctly: they show up in the usage+ // figures without inflating the managed totals the dashboard is drawn+ // against.let now = Utc::now();let monthly = tracker.get_monthly_cost(now.year(), now.month()).unwrap();assert!((monthly - 50.0).abs() < 0.0001);diff --git a/crates/openhuman-core/src/platform/cost/types.rs b/crates/openhuman-core/src/platform/cost/types.rsindex 11f17dbd22..07e80cbae5 100644--- a/crates/openhuman-core/src/platform/cost/types.rs+++ b/crates/openhuman-core/src/platform/cost/types.rs@@ -132,25 +132,6 @@ impl CostRecord {}}-/// Budget enforcement result.-#[derive(Debug, Clone)]-pub enum BudgetCheck {- /// Within budget, request can proceed- Allowed,- /// Warning threshold exceeded but request can proceed- Warning {- current_usd: f64,- limit_usd: f64,- period: UsagePeriod,- },- /// Budget exceeded, request blocked- Exceeded {- current_usd: f64,- limit_usd: f64,- period: UsagePeriod,- },-}-/// Cost summary for reporting.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct CostSummary {diff --git a/tests/cost_cap_removed.rs b/tests/cost_cap_removed.rsnew file mode 100644index 0000000000..ee864f7c7f--- /dev/null+++ b/tests/cost_cap_removed.rs@@ -0,0 +1,87 @@+//! The spend cap is gone: a spend state that used to refuse must now grant.+//!+//! This is a reproduction of the reported symptom, not a test of the diff. The+//! user's installed app emitted, on every attempt:+//!+//! ```text+//! [tinyagents::mw] cost budget exceeded — failing before model call+//! current_usd=10.0341857 limit_usd=10 period=Day+//! ```+//!+//! and surfaced it as "Something went wrong. Please try again." — advice that+//! could not work, because the refusal happened *before* the model call, so+//! every retry hit the same wall.+//!+//! It lives in its own integration binary rather than beside the module for one+//! reason: `GLOBAL_TRACKER` is a process-wide `OnceCell`+//! (`platform/cost/global.rs`). A unit test that installs a global tracker wins+//! or loses depending on which test in the shared `--lib` process got there+//! first, so the reproduction would be order-dependent — and an order-dependent+//! reproduction that happens to find `None` proves nothing, because the gate+//! treats "no tracker" as "no budget opinion" and grants. One test per process+//! is what makes the spend state below actually reach the code under test.++use std::sync::Arc;++use openhuman_core::agent::tinyagents::host::OpenHumanBudgetGate;+use openhuman_core::config::{Config, DEFAULT_MODEL};+use openhuman_core::platform::cost::{self, TokenUsage};+use tinyagents_harness::host::budget_gate::{BudgetGate, CallEstimate};++/// Spend far past every limit the cap ever enforced: the retired daily default+/// was $10 and the monthly default is $100.+const RUNAWAY_SPEND_USD: f64 = 500.0;++#[tokio::test]+async fn a_spend_state_that_used_to_refuse_now_grants_and_is_still_recorded() {+ let tmp = tempfile::TempDir::new().expect("tempdir");++ // Enforcement-era config: `enabled = true` is what used to arm the cap.+ let mut config = Config::default();+ config.cost.enabled = true;+ cost::init_global(config.cost.clone(), tmp.path());+ let tracker = cost::try_global().expect(+ "this test owns its process, so nothing else can have claimed the \+ global tracker first; without it the gate has no budget opinion and \+ the reproduction below would be vacuous",+ );++ // Managed route — only managed spend was ever counted against the cap+ // (#5016), so a BYOK model here would have been ignored even before the+ // removal and would prove nothing.+ let mut usage = TokenUsage::new(DEFAULT_MODEL, 10_000, 5_000, 1.0, 2.0);+ usage.cost_usd = RUNAWAY_SPEND_USD;+ tracker.record_usage(usage).expect("recording the spend");++ // 1. THE SYMPTOM. `acquire()` is the surviving enforcement point+ // (`host/budget_gate.rs`), the one that produces the near-identical+ // "[tinyagents][budget] refusing model call" message. Before the+ // removal this returned `Err(LimitExceeded)` for exactly this state.+ let gate = OpenHumanBudgetGate::new(Arc::new(config));+ let estimate = CallEstimate::new(DEFAULT_MODEL, 1_000, 1_000).with_agent("lead");+ match gate.acquire(&estimate).await {+ Ok(permit) => drop(permit),+ Err(err) => panic!(+ "a runaway ${RUNAWAY_SPEND_USD} of managed spend must no longer refuse \+ a model call: the budget cap was removed, and this is the \+ enforcement point that used to refuse before the call was ever \+ made. Got: {err:?}"+ ),+ }++ // 2. WHAT MUST SURVIVE. Removing the cap must not blind the spend view.+ // The dashboard reads the same records the cap used to gate on, so+ // assert the spend is still there rather than assuming it, since+ // "I didn't touch it" is not evidence.+ let summary = tracker.get_summary().expect("summary");+ assert!(+ (summary.session_cost_usd - RUNAWAY_SPEND_USD).abs() < 0.0001,+ "the spend must still be recorded for the dashboard after the cap is \+ gone; got {} USD",+ summary.session_cost_usd+ );+ assert_eq!(+ summary.request_count, 1,+ "the recorded request must still be counted for the dashboard"+ );+}