Skip to content

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

fix(threads): count a thread's persisted token usage once, from the records

M3gA-Mindee0b4ca0128a
diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs
index 168e12e7e8..b762849a77 100644
--- a/crates/openhuman-core/src/agent/session_host/codec.rs
+++ b/crates/openhuman-core/src/agent/session_host/codec.rs
@@ -91,6 +91,24 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
Ok(rows)
}
+ /// The durable per-turn usage record: **this agent's own spend, excluding
+ /// its children.**
+ ///
+ /// Every transcript in `session_raw` now means the same thing — what the
+ /// agent that owns the file spent on its own provider calls. A sub-agent's
+ /// transcript has always been written that way (`SubagentUsage` is
+ /// "accumulated across every provider call this sub-agent made", and
+ /// `subagent_host::ops::graph::transcript` stores exactly that), so a reader
+ /// that walks a root plus its descendants counts every token once, at any
+ /// delegation depth. Folding children in here instead made the root record
+ /// overlap its own children's records, and `threads::ops::usage` added both
+ /// — a double count masked only by the dead `_meta` rollup (#6460).
+ ///
+ /// Exclusivity also makes the record independent of whether a child's usage
+ /// reached the parent's in-turn ledger at all. A detached delegation's does
+ /// not (#6459), so an inclusive record was silently inclusive for a blocking
+ /// spawn and exclusive for the default async one, with nothing in the file
+ /// saying which. The child's own transcript is written either way.
fn turn_usage(
&self,
options: &TranscriptTurnOptions<OpenHumanRunContext>,
@@ -106,27 +124,11 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
// completed. Snapshot their explicit ledger here, immediately before
// the runtime's atomic append, so durable billing cannot lag the UI.
sidecar.subagents = subagents;
- let child_input = sidecar
- .subagents
- .iter()
- .map(|entry| entry.usage.input_tokens)
- .sum::<u64>();
- let child_output = sidecar
- .subagents
- .iter()
- .map(|entry| entry.usage.output_tokens)
- .sum::<u64>();
- let child_cached_input = sidecar
- .subagents
- .iter()
- .map(|entry| entry.usage.cached_input_tokens)
- .sum::<u64>();
- let child_cost = sidecar
- .subagents
- .iter()
- .map(|entry| entry.usage.charged_amount_usd)
- .sum::<f64>();
- // Keep the sidecar authoritative for the post-commit UI too.
+ // Keep the sidecar authoritative for the post-commit UI too. The live
+ // `chat_done` projection (`holistic_last_turn_usage`) still folds these
+ // child entries in, because a turn's *spend* is parent + children; only
+ // the durable record below stays the parent's own, for the reason in
+ // this method's own doc comment.
*options
.context
.session_sidecar
@@ -136,13 +138,10 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
// Preserve the old contract of omitting a synthetic all-zero usage
// record, while ensuring every observed driver sidecar travels in the
// same atomic runtime append as its transcript rows.
- if sidecar.input_tokens.saturating_add(child_input) == 0
- && sidecar.output_tokens.saturating_add(child_output) == 0
- && sidecar
- .cached_input_tokens
- .saturating_add(child_cached_input)
- == 0
- && sidecar.cost_usd + child_cost == 0.0
+ if sidecar.input_tokens == 0
+ && sidecar.output_tokens == 0
+ && sidecar.cached_input_tokens == 0
+ && sidecar.cost_usd == 0.0
&& route.is_none()
{
return Ok(None);
@@ -157,13 +156,11 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
.map(|route| route.model.clone())
.unwrap_or_default(),
usage: MessageUsage {
- input: sidecar.input_tokens.saturating_add(child_input),
- output: sidecar.output_tokens.saturating_add(child_output),
- cached_input: sidecar
- .cached_input_tokens
- .saturating_add(child_cached_input),
+ input: sidecar.input_tokens,
+ output: sidecar.output_tokens,
+ cached_input: sidecar.cached_input_tokens,
context_window: sidecar.context_window,
- cost_usd: sidecar.cost_usd + child_cost,
+ cost_usd: sidecar.cost_usd,
},
ts: chrono::Utc::now().to_rfc3339(),
reasoning_content: None,
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
index 0b127693c9..d2003b7a65 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -93,8 +93,17 @@ fn codec_marks_failed_tool_rows_from_the_explicit_turn_sidecar() {
.is_some_and(|failure| failure.failed));
}
+/// The durable record is the parent's OWN spend.
+///
+/// This assertion used to read `18` — "direct + completed child input" — which
+/// made the root transcript's record overlap the child's own transcript, and
+/// `threads::ops::usage` added both (#6460). Inverted deliberately, not deleted:
+/// the sub-agent entry is still appended below, and the point is that it does
+/// **not** move these numbers. The live `chat_done` projection stays inclusive —
+/// see `last_turn_usage_reports_the_same_holistic_totals_as_transcript_billing`
+/// immediately below, which is the counterpart this split is meant to preserve.
#[test]
-fn codec_attaches_sidecar_usage_and_exact_tool_arguments_to_atomic_append() {
+fn codec_attaches_only_this_agents_own_sidecar_usage_to_atomic_append() {
let context = OpenHumanRunContext::new();
{
let mut sidecar = context.session_sidecar.lock().unwrap();
@@ -125,6 +134,9 @@ fn codec_attaches_sidecar_usage_and_exact_tool_arguments_to_atomic_append() {
charged_amount_usd: 0.001,
},
});
+ // `OpenHumanRunContext` is `Clone` and its child ledger is an `Arc`, so this
+ // probe observes the same ledger after `context` is moved into the options.
+ let probe = context.clone();
let usage = OpenHumanTranscriptCodec
.turn_usage(&TranscriptTurnOptions {
request_id: Some("request-usage".into()),
@@ -136,11 +148,32 @@ fn codec_attaches_sidecar_usage_and_exact_tool_arguments_to_atomic_append() {
.unwrap()
.expect("observed sidecar produces transcript usage");
- assert_eq!(usage.usage.input, 18, "direct + completed child input");
- assert_eq!(usage.usage.output, 10, "direct + completed child output");
- assert_eq!(usage.usage.cached_input, 4);
+ // The child contributed 5/2/1/$0.001 and is deliberately absent here: it is
+ // recorded in its own transcript, which the thread aggregate reads directly.
+ assert_eq!(
+ usage.usage.input, 13,
+ "the parent's own input, NOT 18 — the child's 5 belongs to the child's record"
+ );
+ assert_eq!(
+ usage.usage.output, 8,
+ "the parent's own output, NOT 10 — the child's 2 belongs to the child's record"
+ );
+ assert_eq!(
+ usage.usage.cached_input, 3,
+ "the parent's own cache reads, NOT 4"
+ );
assert_eq!(usage.usage.context_window, 128_000);
- assert!((usage.usage.cost_usd - 0.005).abs() < f64::EPSILON);
+ assert!(
+ (usage.usage.cost_usd - 0.004).abs() < f64::EPSILON,
+ "the parent's own cost, NOT 0.005"
+ );
+ // The entry is still on the sidecar — exclusivity is about what is written,
+ // not about discarding the ledger the live UI projection needs.
+ assert_eq!(
+ probe.subagent_usage_entries().len(),
+ 1,
+ "the child entry survives on the ledger for the live projection"
+ );
assert_eq!(usage.iteration, 2);
assert_eq!(usage.tool_calls.len(), 1);
assert_eq!(usage.tool_calls[0].id, "call-usage");
diff --git a/crates/openhuman-core/src/threads/ops/usage.rs b/crates/openhuman-core/src/threads/ops/usage.rs
index 6ed1106ae9..ca2554b418 100644
--- a/crates/openhuman-core/src/threads/ops/usage.rs
+++ b/crates/openhuman-core/src/threads/ops/usage.rs
@@ -3,6 +3,11 @@
use super::support::{counts, envelope, workspace_dir};
use crate::memory::ApiEnvelope;
use crate::rpc::RpcOutcome;
+use std::collections::BTreeMap;
+use std::path::Path;
+use tinyagents_session::transcript::{
+ find_root_transcripts_for_thread, read_transcript, SessionTranscript,
+};
/// Request for [`token_usage`]: the thread whose persisted usage to total.
#[derive(Debug, Clone, serde::Deserialize)]
@@ -22,13 +27,18 @@ pub struct ThreadTokenUsageResponse {
pub cost_usd: f64,
pub turn_count: usize,
/// Tokens of the most recent turn — numerator for the context-window gauge.
+ /// The orchestrator's own, excluding sub-agents: each child runs in its own
+ /// context window, so folding them in let the gauge exceed 100% (#4271).
pub last_turn_input_tokens: u64,
pub last_turn_output_tokens: u64,
/// Context window (tokens) inferred from the last model; `0` when unknown.
pub context_window: u64,
pub model: Option<String>,
pub updated: Option<String>,
- /// `false` when the thread has no persisted turns yet (all zeros).
+ /// `false` when the thread has no persisted spend yet (all zeros). The UI
+ /// uses this to decide whether to seed its live bucket at all, so a thread
+ /// whose transcripts exist but recorded nothing must report `false` — the
+ /// alternative overwrites a live in-progress bucket with zeros.
pub has_usage: bool,
/// Per-archetype sub-agent spend (re-audited at current pricing). The
/// top-level totals already include this; it's broken out for the UI's
@@ -46,13 +56,197 @@ pub struct SubagentUsageDto {
pub runs: usize,
}
+/// One transcript's own spend, summed from the per-turn `turn_usage` records
+/// the codec attaches to its assistant rows.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub(super) struct TranscriptSpend {
+ pub(super) input_tokens: u64,
+ pub(super) output_tokens: u64,
+ pub(super) cached_input_tokens: u64,
+ pub(super) cost_usd: f64,
+ /// Turns that recorded usage. The codec emits one record per durable
+ /// append, and omits an all-zero one, so this is "turns that spent".
+ pub(super) turns: usize,
+ /// The newest record's model and window, for the caller's last-turn view.
+ pub(super) last_input_tokens: u64,
+ pub(super) last_output_tokens: u64,
+ pub(super) model: Option<String>,
+ pub(super) context_window: u64,
+}
+
+/// Total one transcript file's own recorded spend.
+///
+/// The `_meta` header carries denormalised rollups for the same figures, but
+/// nothing has written them on the root path since the TinyAgents runtime
+/// cutover (`33566d382`) — every root transcript since reads `input_tokens: 0`
+/// while its per-turn records hold the real numbers (#6460). The per-turn
+/// records are the authoritative copy and the only one that is written on every
+/// path, so this reads those and ignores the header.
+///
+/// `read_transcript` is the reader that applies compaction records and drops
+/// interrupted partials, so a compacted or interrupted session is summed over
+/// its logical message set rather than its raw append log.
+pub(super) fn transcript_spend(transcript: &SessionTranscript) -> TranscriptSpend {
+ let mut spend = TranscriptSpend::default();
+ for message in &transcript.messages {
+ let Some(usage) = message.turn_usage.as_ref() else {
+ continue;
+ };
+ spend.input_tokens = spend.input_tokens.saturating_add(usage.usage.input);
+ spend.output_tokens = spend.output_tokens.saturating_add(usage.usage.output);
+ spend.cached_input_tokens = spend
+ .cached_input_tokens
+ .saturating_add(usage.usage.cached_input);
+ spend.cost_usd += usage.usage.cost_usd;
+ spend.turns += 1;
+ spend.last_input_tokens = usage.usage.input;
+ spend.last_output_tokens = usage.usage.output;
+ if usage.usage.context_window > 0 {
+ spend.context_window = usage.usage.context_window;
+ }
+ if !usage.model.is_empty() {
+ spend.model = Some(usage.model.clone());
+ }
+ }
+ // A transcript whose model never landed on a usage record still has one in
+ // its header; prefer the record, fall back to the header.
+ if spend.model.is_none() {
+ spend.model = transcript.meta.model.clone();
+ }
+ spend
+}
+
+/// Read one transcript, logging and skipping an unreadable file rather than
+/// failing the whole thread's aggregate for it.
+fn read(path: &Path) -> Option<SessionTranscript> {
+ match read_transcript(path) {
+ Ok(transcript) => Some(transcript),
+ Err(err) => {
+ log::warn!(
+ "[threads:usage] skipping unreadable transcript {}: {err}",
+ path.display()
+ );
+ None
+ }
+ }
+}
+
+/// Every descendant transcript of `root`, at any delegation depth.
+///
+/// Sub-agent transcripts are named `{root_stem}__{child}` (and a grandchild
+/// chains another `__`), which is the *only* durable record of the parent→child
+/// relation. Selecting them by `_meta.thread_id` instead — as the session
+/// crate's own summary helper does — drops the majority of them: a delegation
+/// gets its own worker thread, and `inherited_thread_id` lets that worker id win
+/// over the parent's, so the child's header names a thread the caller never
+/// asked about (#6460).
+fn descendant_transcripts(root: &Path) -> Vec<std::path::PathBuf> {
+ let Some(dir) = root.parent() else {
+ return Vec::new();
+ };
+ let Some(root_stem) = root.file_stem().and_then(|s| s.to_str()) else {
+ return Vec::new();
+ };
+ let prefix = format!("{root_stem}__");
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return Vec::new();
+ };
+ let mut matches: Vec<std::path::PathBuf> = entries
+ .flatten()
+ .map(|entry| entry.path())
+ .filter(|path| {
+ path.extension().and_then(|s| s.to_str()) == Some("jsonl")
+ && path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .is_some_and(|stem| stem.starts_with(&prefix))
+ })
+ .collect();
+ matches.sort();
+ matches
+}
+
+/// One thread's spend, split into the orchestrator's own and each sub-agent
+/// archetype's, each counted exactly once.
+#[derive(Debug, Clone, Default)]
+pub(super) struct ThreadSpend {
+ pub(super) root: TranscriptSpend,
+ /// Keyed by archetype (`_meta.agent`), with a run count.
+ pub(super) subagents: BTreeMap<String, (TranscriptSpend, usize)>,
+ pub(super) updated: Option<String>,
+ pub(super) found_transcript: bool,
+}
+
+/// Walk a thread's root transcripts and their descendants, totalling each file's
+/// own recorded spend.
+///
+/// Correct-by-construction because every transcript records only what the agent
+/// that owns it spent (see `session_host::codec::turn_usage`): the walk visits
+/// each file once, so no token is counted twice however deep the delegation went,
+/// and a child whose usage never reached its parent's in-turn ledger (#6459) is
+/// still counted from its own file.
+pub(super) fn thread_spend(workspace_dir: &Path, thread_id: &str) -> ThreadSpend {
+ let mut out = ThreadSpend::default();
+ let roots = find_root_transcripts_for_thread(workspace_dir, thread_id);
+ for root in &roots {
+ out.found_transcript = true;
+ if let Some(transcript) = read(root) {
+ let spend = transcript_spend(&transcript);
+ out.root.input_tokens = out.root.input_tokens.saturating_add(spend.input_tokens);
+ out.root.output_tokens = out.root.output_tokens.saturating_add(spend.output_tokens);
+ out.root.cached_input_tokens = out
+ .root
+ .cached_input_tokens
+ .saturating_add(spend.cached_input_tokens);
+ out.root.cost_usd += spend.cost_usd;
+ out.root.turns += spend.turns;
+ // `find_root_transcripts_for_thread` returns oldest first, so the
+ // last root to report a turn owns the last-turn view.
+ if spend.turns > 0 {
+ out.root.last_input_tokens = spend.last_input_tokens;
+ out.root.last_output_tokens = spend.last_output_tokens;
+ }
+ if spend.context_window > 0 {
+ out.root.context_window = spend.context_window;
+ }
+ if spend.model.is_some() {
+ out.root.model = spend.model;
+ }
+ out.updated = Some(transcript.meta.updated);
+ }
+ for child in descendant_transcripts(root) {
+ let Some(child_transcript) = read(&child) else {
+ continue;
+ };
+ let spend = transcript_spend(&child_transcript);
+ out.found_transcript = true;
+ let entry = out
+ .subagents
+ .entry(child_transcript.meta.agent_name.clone())
+ .or_default();
+ entry.0.input_tokens = entry.0.input_tokens.saturating_add(spend.input_tokens);
+ entry.0.output_tokens = entry.0.output_tokens.saturating_add(spend.output_tokens);
+ entry.0.cached_input_tokens = entry
+ .0
+ .cached_input_tokens
+ .saturating_add(spend.cached_input_tokens);
+ entry.0.cost_usd += spend.cost_usd;
+ entry.0.turns += spend.turns;
+ if entry.0.model.is_none() {
+ entry.0.model = spend.model;
+ }
+ entry.1 += 1;
+ }
+ }
+ out
+}
+
/// Total a thread's persisted token/cost usage across its root transcripts.
pub async fn token_usage(
request: ThreadTokenUsageRequest,
) -> Result<RpcOutcome<ApiEnvelope<ThreadTokenUsageResponse>>, String> {
let dir = workspace_dir().await?;
- let summary =
- tinyagents_session::transcript::read_thread_usage_summary(&dir, &request.thread_id);
+ let spend = thread_spend(&dir, &request.thread_id);
// Re-audit cost at CURRENT pricing rather than trusting the
// `charged_amount_usd` persisted in the transcript: those values were
@@ -73,89 +267,113 @@ pub async fn token_usage(
None => fallback,
};
- let response = match summary {
- Some(s) => {
- let context_window = s
- .model
- .as_deref()
- .and_then(crate::inference::model_context::context_window_for_model)
- .unwrap_or(0);
-
- // Orchestrator (root) spend, re-audited.
- let orchestrator_cost = audit_cost(
- s.model.as_deref(),
- s.input_tokens,
- s.output_tokens,
- s.cached_input_tokens,
- s.cost_usd,
- );
+ if !spend.found_transcript {
+ return Ok(envelope(
+ empty_response(&request.thread_id),
+ Some(counts([("has_usage", 0)])),
+ None,
+ ));
+ }
- // Sub-agent archetypes, each re-audited with its own model. Older
- // sub-agent transcripts didn't persist a model on their messages, so
- // fall back to the thread's (root) model rather than pricing them at
- // $0 — sub-agents usually run on the same managed tier as the parent.
- let mut subagents = Vec::with_capacity(s.subagents.len());
- let (mut sub_in, mut sub_out, mut sub_cached, mut sub_cost) = (0u64, 0u64, 0u64, 0.0);
- for g in &s.subagents {
- let sub_model = g.model.as_deref().or(s.model.as_deref());
- let cost = audit_cost(
- sub_model,
- g.input_tokens,
- g.output_tokens,
- g.cached_input_tokens,
- 0.0,
- );
- sub_in = sub_in.saturating_add(g.input_tokens);
- sub_out = sub_out.saturating_add(g.output_tokens);
- sub_cached = sub_cached.saturating_add(g.cached_input_tokens);
- sub_cost += cost;
- subagents.push(SubagentUsageDto {
- agent_id: g.agent_id.clone(),
- input_tokens: g.input_tokens,
- output_tokens: g.output_tokens,
- cost_usd: cost,
- runs: g.runs,
- });
- }
+ let root_model = spend.root.model.clone();
+ let context_window = if spend.root.context_window > 0 {
+ spend.root.context_window
+ } else {
+ root_model
+ .as_deref()
+ .and_then(crate::inference::model_context::context_window_for_model)
+ .unwrap_or(0)
+ };
- // Top-level totals = orchestrator + all sub-agents.
- ThreadTokenUsageResponse {
- thread_id: request.thread_id.clone(),
- input_tokens: s.input_tokens.saturating_add(sub_in),
- output_tokens: s.output_tokens.saturating_add(sub_out),
- cached_input_tokens: s.cached_input_tokens.saturating_add(sub_cached),
- cost_usd: orchestrator_cost + sub_cost,
- turn_count: s.turn_count,
- last_turn_input_tokens: s.last_turn_input_tokens,
- last_turn_output_tokens: s.last_turn_output_tokens,
- context_window,
- model: s.model,
- updated: Some(s.updated),
- has_usage: true,
- subagents,
- }
- }
- None => ThreadTokenUsageResponse {
- thread_id: request.thread_id.clone(),
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- cost_usd: 0.0,
- turn_count: 0,
- last_turn_input_tokens: 0,
- last_turn_output_tokens: 0,
- context_window: 0,
- model: None,
- updated: None,
- has_usage: false,
- subagents: Vec::new(),
- },
+ // Orchestrator (root) spend, re-audited.
+ let orchestrator_cost = audit_cost(
+ root_model.as_deref(),
+ spend.root.input_tokens,
+ spend.root.output_tokens,
+ spend.root.cached_input_tokens,
+ spend.root.cost_usd,
+ );
+
+ // Sub-agent archetypes, each re-audited with its own model. Older
+ // sub-agent transcripts didn't persist a model on their messages, so
+ // fall back to the thread's (root) model rather than pricing them at
+ // $0 — sub-agents usually run on the same managed tier as the parent.
+ let mut subagents = Vec::with_capacity(spend.subagents.len());
+ let (mut sub_in, mut sub_out, mut sub_cached, mut sub_cost) = (0u64, 0u64, 0u64, 0.0);
+ for (agent_id, (child, runs)) in &spend.subagents {
+ let sub_model = child.model.as_deref().or(root_model.as_deref());
+ let cost = audit_cost(
+ sub_model,
+ child.input_tokens,
+ child.output_tokens,
+ child.cached_input_tokens,
+ child.cost_usd,
+ );
+ sub_in = sub_in.saturating_add(child.input_tokens);
+ sub_out = sub_out.saturating_add(child.output_tokens);
+ sub_cached = sub_cached.saturating_add(child.cached_input_tokens);
+ sub_cost += cost;
+ subagents.push(SubagentUsageDto {
+ agent_id: agent_id.clone(),
+ input_tokens: child.input_tokens,
+ output_tokens: child.output_tokens,
+ cost_usd: cost,
+ runs: *runs,
+ });
+ }
+
+ // Top-level totals = orchestrator + all sub-agents, each counted once
+ // because each transcript recorded only its own spend.
+ let input_tokens = spend.root.input_tokens.saturating_add(sub_in);
+ let output_tokens = spend.root.output_tokens.saturating_add(sub_out);
+ let cached_input_tokens = spend.root.cached_input_tokens.saturating_add(sub_cached);
+ let cost_usd = orchestrator_cost + sub_cost;
+ // A thread whose transcripts exist but recorded no spend must not claim
+ // usage: the UI replaces its live bucket with this payload.
+ let has_usage =
+ input_tokens > 0 || output_tokens > 0 || cached_input_tokens > 0 || cost_usd > 0.0;
+
+ let response = ThreadTokenUsageResponse {
+ thread_id: request.thread_id.clone(),
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ cost_usd,
+ turn_count: spend.root.turns,
+ last_turn_input_tokens: spend.root.last_input_tokens,
+ last_turn_output_tokens: spend.root.last_output_tokens,
+ context_window,
+ model: root_model,
+ updated: spend.updated,
+ has_usage,
+ subagents,
};
- let has_usage = response.has_usage;
Ok(envelope(
response,
Some(counts([("has_usage", usize::from(has_usage))])),
None,
))
}
+
+fn empty_response(thread_id: &str) -> ThreadTokenUsageResponse {
+ ThreadTokenUsageResponse {
+ thread_id: thread_id.to_string(),
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ cost_usd: 0.0,
+ turn_count: 0,
+ last_turn_input_tokens: 0,
+ last_turn_output_tokens: 0,
+ context_window: 0,
+ model: None,
+ updated: None,
+ has_usage: false,
+ subagents: Vec::new(),
+ }
+}
+
+#[cfg(test)]
+#[path = "usage_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/threads/ops/usage_tests.rs b/crates/openhuman-core/src/threads/ops/usage_tests.rs
new file mode 100644
index 0000000000..5b9de670bd
--- /dev/null
+++ b/crates/openhuman-core/src/threads/ops/usage_tests.rs
@@ -0,0 +1,306 @@
+//! Aggregation tests for `threads::ops::usage`.
+//!
+//! Every fixture is written with the session crate's own writer
+//! (`append_transcript_turn`), never hand-rolled JSONL, so a wire-format change
+//! upstream surfaces here as a failure instead of silently diverging from what
+//! the core actually persists.
+
+use super::*;
+use tinyagents_session::transcript::{
+ append_transcript_turn, MessageUsage, TranscriptMessage, TranscriptMeta, TurnUsage,
+};
+
+const MODEL: &str = "openrouter/deepseek/deepseek-v4-flash";
+
+fn meta(agent: &str, agent_type: &str, thread_id: Option<&str>) -> TranscriptMeta {
+ TranscriptMeta {
+ agent_name: agent.to_string(),
+ agent_id: Some(agent.to_string()),
+ agent_type: Some(agent_type.to_string()),
+ dispatcher: "native".into(),
+ provider: Some("openhuman".into()),
+ model: Some(MODEL.into()),
+ created: "2026-09-22T00:00:00Z".into(),
+ updated: "2026-09-22T01:00:00Z".into(),
+ turn_count: 0,
+ // Every fixture leaves the denormalised `_meta` rollups at zero: that is
+ // exactly what is on disk for every root transcript written since
+ // `33566d382`, and the aggregate must not depend on them.
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ thread_id: thread_id.map(str::to_owned),
+ task_id: None,
+ }
+}
+
+fn turn_usage(input: u64, output: u64, cached: u64) -> TurnUsage {
+ TurnUsage {
+ provider: "openhuman".into(),
+ model: MODEL.into(),
+ usage: MessageUsage {
+ input,
+ output,
+ cached_input: cached,
+ context_window: 1_000_000,
+ cost_usd: 0.0,
+ },
+ ts: "2026-09-22T01:00:00Z".into(),
+ reasoning_content: None,
+ tool_calls: Vec::new(),
+ iteration: 1,
+ }
+}
+
+/// Append `turns` to `session_raw/{stem}.jsonl`, one durable turn per entry,
+/// growing the message set the way the runtime does.
+fn write_transcript_turns(
+ workspace: &Path,
+ stem: &str,
+ meta: &TranscriptMeta,
+ turns: &[(u64, u64, u64)],
+) {
+ let dir = workspace.join("session_raw");
+ std::fs::create_dir_all(&dir).expect("create session_raw");
+ let path = dir.join(format!("{stem}.jsonl"));
+ let mut persisted: Vec<TranscriptMessage> = Vec::new();
+ for (i, (input, output, cached)) in turns.iter().enumerate() {
+ let mut next = persisted.clone();
+ next.push(TranscriptMessage::new("user", format!("q{i}")));
+ next.push(TranscriptMessage::assistant(format!("a{i}")));
+ let mut turn_meta = meta.clone();
+ turn_meta.turn_count = i + 1;
+ append_transcript_turn(
+ &path,
+ &persisted,
+ &next,
+ &turn_meta,
+ Some(&turn_usage(*input, *output, *cached)),
+ Some(&format!("req-{i}")),
+ )
+ .expect("append turn");
+ persisted = next;
+ }
+}
+
+/// A thread with no sub-agents: the total is the orchestrator's own spend, and
+/// the zero `_meta` rollups are ignored.
+#[test]
+fn totals_a_thread_with_no_subagents_from_its_turn_records() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let thread = "thread-solo";
+ write_transcript_turns(
+ tmp.path(),
+ "1790000000_orchestrator_solo",
+ &meta("orchestrator", "root", Some(thread)),
+ &[(10_000, 100, 4_000), (20_000, 200, 8_000)],
+ );
+
+ let spend = thread_spend(tmp.path(), thread);
+
+ assert_eq!(spend.root.input_tokens, 30_000);
+ assert_eq!(spend.root.output_tokens, 300);
+ assert_eq!(spend.root.cached_input_tokens, 12_000);
+ assert_eq!(spend.root.turns, 2);
+ assert!(
+ spend.subagents.is_empty(),
+ "no sub-agent transcripts exist, so none may be attributed"
+ );
+ // The newest turn owns the last-turn view, not the sum of turns.
+ assert_eq!(spend.root.last_input_tokens, 20_000);
+ assert_eq!(spend.root.last_output_tokens, 200);
+}
+
+/// The `thread-37dcc15f` shape from the bug report: a root whose children burned
+/// far more than it did, and whose child transcripts carry a **worker** thread
+/// id rather than the parent's.
+///
+/// This is the regression. Selecting children by `_meta.thread_id` — what
+/// `read_thread_usage_summary` does — attributed 0 of the 397,423 child input
+/// tokens to the thread, so ~88% of its spend was invisible (#6460).
+#[test]
+fn counts_subagents_whose_transcripts_carry_a_worker_thread_id() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let thread = "thread-37dcc15f";
+ let root_stem = "1789765020_orchestrator_thread-37dcc";
+ write_transcript_turns(
+ tmp.path(),
+ root_stem,
+ &meta("orchestrator", "root", Some(thread)),
+ &[(16_884, 34, 0)],
+ );
+ // Both children name their own worker thread, never `thread`.
+ write_transcript_turns(
+ tmp.path(),
+ &format!("{root_stem}__1789766110_researcher_sub-a"),
+ &meta(
+ "researcher",
+ "subagent",
+ Some("worker-0aa53709-436d-4566-8798-3629beb11723"),
+ ),
+ &[(180_295, 8_000, 0)],
+ );
+ write_transcript_turns(
+ tmp.path(),
+ &format!("{root_stem}__1789766852_researcher_sub-b"),
+ &meta(
+ "researcher",
+ "subagent",
+ Some("worker-6b2d242f-c1b1-49ef-8b74-0a7ebeda4afc"),
+ ),
+ &[(217_128, 8_873, 0)],
+ );
+
+ let spend = thread_spend(tmp.path(), thread);
+
+ assert_eq!(spend.root.input_tokens, 16_884, "orchestrator's own spend");
+ let (researcher, runs) = spend
+ .subagents
+ .get("researcher")
+ .expect("both children group under their archetype despite the worker thread ids");
+ assert_eq!(*runs, 2, "two separate delegations, two runs");
+ assert_eq!(
+ researcher.input_tokens, 397_423,
+ "both children's input must be attributed to the parent thread"
+ );
+ assert_eq!(researcher.output_tokens, 16_873);
+
+ // The thread total counts every token exactly ONCE. The pre-fix arithmetic
+ // would reach 414,307 + 397,423 had the root record also carried its
+ // children, which is the double count this design removes.
+ let total = spend.root.input_tokens + researcher.input_tokens;
+ assert_eq!(total, 414_307);
+}
+
+/// A child's spend is counted from the child's own transcript, so a delegation
+/// whose usage never reached the parent's in-turn ledger (#6459, the default
+/// async path) is still counted — and counted once, not twice.
+#[test]
+fn counts_each_transcript_once_regardless_of_the_parent_ledger() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let thread = "thread-ledger";
+ let root_stem = "1790000001_orchestrator_ledger";
+ // The root records ONLY its own spend — the contract
+ // `session_host::codec::turn_usage` now guarantees.
+ write_transcript_turns(
+ tmp.path(),
+ root_stem,
+ &meta("orchestrator", "root", Some(thread)),
+ &[(1_000, 10, 0)],
+ );
+ write_transcript_turns(
+ tmp.path(),
+ &format!("{root_stem}__child_coder"),
+ &meta("coding_agent", "subagent", Some("worker-xyz")),
+ &[(5_000, 50, 0)],
+ );
+
+ let spend = thread_spend(tmp.path(), thread);
+ let (coder, runs) = spend.subagents.get("coding_agent").expect("child counted");
+
+ assert_eq!(spend.root.input_tokens, 1_000);
+ assert_eq!(coder.input_tokens, 5_000);
+ assert_eq!(*runs, 1);
+ assert_eq!(spend.root.input_tokens + coder.input_tokens, 6_000);
+}
+
+/// A grandchild chains another `__`, and must be counted once at its own depth
+/// rather than dropped or folded into its parent twice.
+#[test]
+fn counts_a_grandchild_delegation_once() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let thread = "thread-deep";
+ let root_stem = "1790000002_orchestrator_deep";
+ write_transcript_turns(
+ tmp.path(),
+ root_stem,
+ &meta("orchestrator", "root", Some(thread)),
+ &[(1_000, 10, 0)],
+ );
+ write_transcript_turns(
+ tmp.path(),
+ &format!("{root_stem}__child"),
+ &meta("researcher", "subagent", Some("worker-1")),
+ &[(2_000, 20, 0)],
+ );
+ write_transcript_turns(
+ tmp.path(),
+ &format!("{root_stem}__child__grandchild"),
+ &meta("coding_agent", "subagent", Some("worker-2")),
+ &[(4_000, 40, 0)],
+ );
+
+ let spend = thread_spend(tmp.path(), thread);
+ let total: u64 = spend.root.input_tokens
+ + spend
+ .subagents
+ .values()
+ .map(|(child, _)| child.input_tokens)
+ .sum::<u64>();
+ assert_eq!(
+ spend.subagents.len(),
+ 2,
+ "child and grandchild both counted"
+ );
+ assert_eq!(total, 7_000);
+}
+
+/// Legacy transcripts already on disk carry zero `_meta` rollups. They must keep
+/// working, which they do because the aggregate never reads the header.
+#[test]
+fn ignores_the_dead_meta_rollup_on_legacy_transcripts() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let thread = "thread-legacy";
+ let legacy = meta("orchestrator", "root", Some(thread));
+ assert_eq!(
+ legacy.input_tokens, 0,
+ "fixture must reproduce the on-disk state: a zero header"
+ );
+ write_transcript_turns(
+ tmp.path(),
+ "1789983533_orchestrator_legacy",
+ &legacy,
+ &[(12_495, 23, 12_288)],
+ );
+
+ let spend = thread_spend(tmp.path(), thread);
+ assert_eq!(
+ spend.root.input_tokens, 12_495,
+ "the per-turn record is authoritative, the zero header is not"
+ );
+ assert_eq!(spend.root.cached_input_tokens, 12_288);
+}
+
+/// A thread with no transcripts at all reports nothing, and a thread whose
+/// transcripts recorded no spend must not claim usage: the UI replaces its live
+/// bucket with this payload, so a false `has_usage` zeroes a turn in flight.
+#[test]
+fn reports_no_usage_for_an_unknown_or_spendless_thread() {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let absent = thread_spend(tmp.path(), "thread-nope");
+ assert!(!absent.found_transcript);
+ assert_eq!(absent.root.input_tokens, 0);
+
+ // A transcript that exists but recorded a single all-zero turn. The codec
+ // omits an all-zero usage record, so this is the shape on disk: rows, no
+ // usage.
+ let thread = "thread-empty";
+ let dir = tmp.path().join("session_raw");
+ std::fs::create_dir_all(&dir).expect("create session_raw");
+ let path = dir.join("1790000003_orchestrator_empty.jsonl");
+ append_transcript_turn(
+ &path,
+ &[],
+ &[TranscriptMessage::new("user", "hi")],
+ &meta("orchestrator", "root", Some(thread)),
+ None,
+ Some("req-0"),
+ )
+ .expect("append turn");
+
+ let spend = thread_spend(tmp.path(), thread);
+ assert!(spend.found_transcript, "the file is there");
+ assert_eq!(spend.root.turns, 0, "but it recorded no spend");
+ assert_eq!(spend.root.input_tokens, 0);
+}
diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rs
index 514bff0af0..4ce8c8d489 100644
--- a/tests/json_rpc_e2e.rs
+++ b/tests/json_rpc_e2e.rs
@@ -12926,20 +12926,49 @@ async fn json_rpc_threads_token_usage_reads_persisted_thread_totals() {
write_min_config(&openhuman_home, "http://127.0.0.1:9");
- // Plant a root session transcript for thread "thr-e2e": a `_meta` header with
- // the cumulative totals + an assistant message carrying last-turn usage/model.
+ // Plant a root session transcript for thread "thr-e2e": two turns, each
+ // carrying its own `usage` record, and a `_meta` header whose token rollups
+ // are ZERO.
+ //
+ // The zeros are the point. Every root transcript written since the TinyAgents
+ // runtime cutover (`33566d382`) has a zero `_meta` rollup while its per-turn
+ // records hold the real numbers (#6460). This fixture used to carry a
+ // non-zero `_meta` and no per-turn records on the sub-agent at all, so it
+ // asserted a contract the running system never produced — the RPC passed
+ // here while reading zeros in production. Totals below can now only come
+ // from the per-turn records, which is what the core actually writes.
+ //
+ // The two turns sum to the same 4200/900/600 the old header claimed, so every
+ // contract assertion further down (including the cost arithmetic) is
+ // unchanged; only the provenance of the numbers moved.
+ //
+ // `provider`, `model`, `usage` and `ts` are ALL load-bearing on an assistant
+ // row: `turn_usage_from_line` matches on all four being present and yields
+ // `None` if any is missing, so dropping one silently produces a row the
+ // model-context reader sees no usage on. The real writer always emits all
+ // four (verified against every usage-bearing row in a live transcript). The
+ // previous fixture omitted `provider` and still passed, because
+ // `read_last_assistant_usage` — the only reader it exercised — is more
+ // lenient than this one; that is the same "green over a shape production
+ // never writes" defect as the zero `_meta` above.
let raw = workspace.join("session_raw");
std::fs::create_dir_all(&raw).expect("mkdir session_raw");
let jsonl = format!(
- "{}\n{}\n{}\n",
+ "{}\n{}\n{}\n{}\n{}\n",
json!({"_meta": {
"agent": "main", "dispatcher": "native",
"created": "2026-04-11T14:30:00Z", "updated": "2026-04-11T14:35:22Z",
- "turn_count": 2, "input_tokens": 4200, "output_tokens": 900,
- "cached_input_tokens": 600, "charged_amount_usd": 0.0123, "thread_id": "thr-e2e"
+ "turn_count": 2, "input_tokens": 0, "output_tokens": 0,
+ "cached_input_tokens": 0, "charged_amount_usd": 0.0, "thread_id": "thr-e2e"
}}),
json!({"role": "user", "content": "hi"}),
- json!({"role": "assistant", "content": "hello", "model": "reasoning-v1",
+ json!({"role": "assistant", "content": "first",
+ "provider": "openhuman", "model": "reasoning-v1",
+ "usage": {"input": 3850, "output": 820, "cached_input": 560, "cost_usd": 0.0114},
+ "ts": "2026-04-11T14:32:00Z"}),
+ json!({"role": "user", "content": "again"}),
+ json!({"role": "assistant", "content": "hello",
+ "provider": "openhuman", "model": "reasoning-v1",
"usage": {"input": 350, "output": 80, "cached_input": 40, "cost_usd": 0.0009},
"ts": "2026-04-11T14:35:22Z"}),
);
@@ -12950,15 +12979,35 @@ async fn json_rpc_threads_token_usage_reads_persisted_thread_totals() {
// transcripts were historically written), so pricing must fall back to the
// thread's model rather than $0. Its spend is grouped under `coder` and
// folded into the thread totals — not collapsed into the orchestrator.
+ //
+ // Its `thread_id` is a WORKER thread, not "thr-e2e". That is what a real
+ // delegation writes — `inherited_thread_id` lets the worker id win over the
+ // parent's — and selecting children by thread id therefore dropped them
+ // entirely (#6460). They are found by the `{root_stem}__` filename relation
+ // instead, which is what this stem exercises. Its `_meta` rollups are zero
+ // like the root's, so the 1000/200 below can only come from its own turn
+ // record.
+ //
+ // Its `model` is deliberately the EMPTY STRING rather than absent. `model`
+ // has to be present for `turn_usage_from_line` to yield usage at all, and an
+ // empty one is exactly what the codec writes when no provider route resolved
+ // (`route.map(|r| r.model).unwrap_or_default()`), which is the real shape of
+ // a child that never recorded a model. The aggregate ignores an empty model,
+ // so pricing still falls back to the thread's model below rather than $0 —
+ // the behaviour this case has always been here to pin.
let sub_jsonl = format!(
"{}\n{}\n",
json!({"_meta": {
"agent": "coder", "dispatcher": "native",
"created": "2026-04-11T14:33:00Z", "updated": "2026-04-11T14:34:00Z",
- "turn_count": 1, "input_tokens": 1000, "output_tokens": 200,
- "cached_input_tokens": 0, "charged_amount_usd": 0.0, "thread_id": "thr-e2e"
+ "turn_count": 1, "input_tokens": 0, "output_tokens": 0,
+ "cached_input_tokens": 0, "charged_amount_usd": 0.0,
+ "thread_id": "worker-2f1c9a80-4d55-4a7e-9f11-0c6b5d3e8a42"
}}),
- json!({"role": "assistant", "content": "done"}),
+ json!({"role": "assistant", "content": "done",
+ "provider": "openhuman", "model": "",
+ "usage": {"input": 1000, "output": 200, "cached_input": 0, "cost_usd": 0.0},
+ "ts": "2026-04-11T14:34:00Z"}),
);
std::fs::write(
raw.join("1700000000_main__1700000050_coder.jsonl"),
@@ -12981,7 +13030,9 @@ async fn json_rpc_threads_token_usage_reads_persisted_thread_totals() {
let data = envelope
.get("data")
.unwrap_or_else(|| panic!("missing data envelope: {envelope}"));
- // Top-level totals include the sub-agent: 4200+1000 in, 900+200 out.
+ // Top-level totals include the sub-agent: 4200+1000 in, 900+200 out, each
+ // counted exactly once — the root's records are its OWN spend, the child's
+ // are the child's.
assert_eq!(data["input_tokens"], 5200);
assert_eq!(data["output_tokens"], 1100);
assert_eq!(data["cached_input_tokens"], 600);