Skip to content

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

test(cost): replace the tautological and assertion-free global cost tests

M3gA-Mind3c45e3b5e0ed
diff --git a/crates/openhuman-core/src/platform/cost/global_tests.rs b/crates/openhuman-core/src/platform/cost/global_tests.rs
index ae57eca9b4..591252865f 100644
--- a/crates/openhuman-core/src/platform/cost/global_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/global_tests.rs
@@ -1,4 +1,6 @@
use super::*;
+use crate::platform::cost::tracker_test_lock;
+use crate::platform::cost::types::CostRecord;
use tempfile::TempDir;
fn make_usage(input: u64, output: u64, charged: f64) -> UsageInfo {
@@ -46,28 +48,137 @@ fn build_token_usage_emits_when_tokens_present_even_with_zero_cost() {
assert!(build_token_usage("m", &usage).is_some());
}
+/// Install a global tracker if this process does not already have one, and
+/// return the live instance.
+///
+/// The tracker is a process-wide `OnceCell` shared by every test in this
+/// binary — including the runtime-bootstrap tests, which call
+/// `platform::cost::init_global` through `core/jsonrpc.rs`. A test therefore
+/// cannot assume it owns the global, and **cannot assume the global is
+/// absent**: that is precisely why the two tests below assert on records
+/// written through whichever tracker is installed, rather than on
+/// `try_global()` being `None`. An assertion predicated on emptiness would be
+/// order-dependent, and order-dependent is how a guard quietly becomes
+/// decorative.
+fn global_tracker() -> std::sync::Arc<crate::platform::cost::tracker::CostTracker> {
+ let tmp = TempDir::new().unwrap();
+ let mut cfg = CostConfig::default();
+ cfg.enabled = true;
+ init_global(cfg, tmp.path());
+ // Keep the directory alive for the call above; records are re-created on
+ // write (`CostStorage::add_record` re-makes the path), so a dropped temp
+ // dir cannot make the read-backs below flaky.
+ std::mem::forget(tmp);
+ try_global().expect("init_global must leave a tracker installed")
+}
+
+/// Records written by this test only. Every test in this file shares one
+/// tracker and one `costs.jsonl`, and libtest runs them in parallel, so each
+/// test filters by a model name no other test uses.
+fn records_for_model(
+ tracker: &crate::platform::cost::tracker::CostTracker,
+ model: &str,
+) -> Vec<CostRecord> {
+ tracker
+ .get_recent_records(2, 1000)
+ .expect("reading recent cost records must succeed")
+ .into_iter()
+ .filter(|record| record.usage.model == model)
+ .collect()
+}
+
#[test]
-fn record_provider_usage_without_global_is_noop() {
- // No GLOBAL_TRACKER initialised in this test process by default;
- // call must return Ok without panic.
- let usage = make_usage(10, 5, 0.5);
- record_provider_usage("m", &usage);
+fn record_provider_usage_persists_through_the_global_tracker() {
+ // Serialised against every other test that touches the process-global
+ // tracker; see `tracker_test_lock`.
+ let _lock = tracker_test_lock();
+ const MODEL: &str = "test-model/record-provider-usage-persists";
+ let tracker = global_tracker();
+
+ record_provider_usage(MODEL, &make_usage(10, 5, 0.5));
+
+ let records = records_for_model(&tracker, MODEL);
+ assert_eq!(
+ records.len(),
+ 1,
+ "record_provider_usage must persist exactly one record through the global tracker"
+ );
+ let usage = &records[0].usage;
+ assert_eq!(usage.input_tokens, 10);
+ assert_eq!(usage.output_tokens, 5);
+ assert_eq!(usage.total_tokens, 15);
+ assert!((usage.cost_usd - 0.5).abs() < f64::EPSILON);
+}
+
+#[test]
+fn record_provider_usage_skips_all_zero_payload() {
+ // Serialised against every other test that touches the process-global
+ // tracker; see `tracker_test_lock`.
+ let _lock = tracker_test_lock();
+ const MODEL: &str = "test-model/record-provider-usage-skips-zero";
+ let tracker = global_tracker();
+
+ // The all-zero skip lives in `record_provider_usage` itself (the
+ // `build_token_usage` `None` arm), so it holds whether or not a tracker is
+ // installed — which is what makes this the deterministic half of the old
+ // `..._without_global_is_noop` test. That test asserted nothing at all, and
+ // its premise ("no GLOBAL_TRACKER initialised in this test process") is not
+ // something a shared-process test binary can guarantee.
+ record_provider_usage(MODEL, &make_usage(0, 0, 0.0));
+
+ assert!(
+ records_for_model(&tracker, MODEL).is_empty(),
+ "an all-zero usage payload must not reach the tracker"
+ );
}
#[test]
fn init_global_is_idempotent() {
- // The OnceCell is process-wide. After at most one call across the
- // whole test run it will be `Some`, and any further `init_global`
- // call must be a no-op (and must not panic). We assert the
- // post-condition either way: try_global resolves to Some on the
- // happy path, or the construct-then-set race is logged silently.
- let tmp = TempDir::new().unwrap();
+ // Serialised against every other test that touches the process-global
+ // tracker; see `tracker_test_lock`.
+ let _lock = tracker_test_lock();
+ // A second `init_global` must be a no-op and must preserve the tracker the
+ // first caller installed (`global.rs` early-returns when the cell is set).
+ //
+ // Asserting that through `try_global()` alone would be vacuous: the cell is
+ // a `OnceCell`, so `set` refuses the replacement even with the early return
+ // deleted, and the *pointer* stays equal either way. The observable that
+ // actually distinguishes the two is one level down — `CostTracker::new`
+ // eagerly creates `<workspace>/state/` (`CostStorage::new` ->
+ // `fs::create_dir_all`). So if the guard is removed, the second call
+ // constructs a tracker for the second workspace and that directory appears
+ // on disk, even though the instance is then discarded.
+ //
+ // The test therefore asserts on the filesystem, which is where removing the
+ // guard is visible, and on pointer identity, which catches a different
+ // regression (swapping the `OnceCell` for storage that can be overwritten).
+ let first_dir = TempDir::new().unwrap();
+ let second_dir = TempDir::new().unwrap();
let mut cfg = CostConfig::default();
cfg.enabled = true;
- init_global(cfg.clone(), tmp.path());
- init_global(cfg, tmp.path()); // second call is a no-op
- // If this test ran first, global is now set. If another test set
- // a different workspace already, the original is retained — both
- // are valid behaviours per the contract.
- assert!(try_global().is_some() || try_global().is_none());
+
+ // After this the process has a tracker — ours, or one another test in this
+ // binary installed first. Either way the *second* call below must no-op, so
+ // this assertion holds regardless of test order.
+ init_global(cfg.clone(), first_dir.path());
+ let before = try_global().expect("init_global must leave a tracker installed");
+
+ let second_state_dir = second_dir.path().join("state");
+ assert!(
+ !second_state_dir.exists(),
+ "second workspace must start clean for this test to mean anything"
+ );
+
+ init_global(cfg, second_dir.path());
+
+ assert!(
+ !second_state_dir.exists(),
+ "second init_global constructed a CostTracker for the second workspace: the \
+ idempotence guard in init_global is gone"
+ );
+ let after = try_global().expect("the tracker must survive a second init_global");
+ assert!(
+ std::sync::Arc::ptr_eq(&before, &after),
+ "second init_global replaced the installed tracker instance"
+ );
}
diff --git a/crates/openhuman-core/src/platform/cost/mod.rs b/crates/openhuman-core/src/platform/cost/mod.rs
index 5dc4c6e838..e601fa3e87 100644
--- a/crates/openhuman-core/src/platform/cost/mod.rs
+++ b/crates/openhuman-core/src/platform/cost/mod.rs
@@ -18,3 +18,22 @@ pub use types::{
BudgetStatus, CostDashboard, CostRecord, CostSource, CostSummary, DailyCostEntry, ModelStats,
TokenUsage, UsagePeriod,
};
+
+/// Serialises tests that touch the process-global [`CostTracker`].
+///
+/// The tracker is a one-shot `OnceCell` shared by every test in this binary,
+/// so a test that reads it and a test that installs it must not interleave:
+/// `rpc_tests::dashboard_query_includes_persisted_record` guards itself with
+/// `try_global().is_some()`, and that check-then-use is only sound while no
+/// other test can call `init_global` between the two. Every test in this
+/// module that installs or reads the global holds this lock.
+///
+/// Poisoning is ignored on purpose — a panicking test must not cascade into
+/// unrelated failures in the tests that follow it.
+#[cfg(test)]
+pub(super) fn tracker_test_lock() -> std::sync::MutexGuard<'static, ()> {
+ static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
+ LOCK.get_or_init(|| std::sync::Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+}
diff --git a/crates/openhuman-core/src/platform/cost/rpc_tests.rs b/crates/openhuman-core/src/platform/cost/rpc_tests.rs
index e025f7ee42..df4f52ddac 100644
--- a/crates/openhuman-core/src/platform/cost/rpc_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/rpc_tests.rs
@@ -1,18 +1,15 @@
use super::*;
+// Shared with `global_tests.rs`: the lock now serialises every test that
+// touches the process-global tracker, not just the ones that mutate
+// `FALLBACK_TRACKER`. `dashboard_query_includes_persisted_record` guards on
+// `try_global().is_some()`, and that guard is only sound while no other test
+// can install the global between the check and the use.
+use crate::platform::cost::tracker_test_lock;
use crate::platform::cost::types::TokenUsage;
use chrono::Utc;
use std::collections::HashMap;
use tempfile::TempDir;
-/// Serialize all tests that mutate the process-global `FALLBACK_TRACKER`
-/// so they don't race each other within the same test binary.
-fn tracker_test_lock() -> std::sync::MutexGuard<'static, ()> {
- static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
- LOCK.get_or_init(|| std::sync::Mutex::new(()))
- .lock()
- .unwrap_or_else(|e| e.into_inner())
-}
-
fn tempdir_config() -> (TempDir, Config) {
let tmp = TempDir::new().unwrap();
let mut cfg = Config::default();