Skip to content

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

fix(agent-tracing): project the turn cost roll-up from the journal

Shanu70e388a5b22e
diff --git a/src/openhuman/agent/progress_tracing/journal_projection.rs b/src/openhuman/agent/progress_tracing/journal_projection.rs
index 6a1a3f37de..ea5984c825 100644
--- a/src/openhuman/agent/progress_tracing/journal_projection.rs
+++ b/src/openhuman/agent/progress_tracing/journal_projection.rs
@@ -15,12 +15,27 @@
//! (`duration_ms`/`output_bytes`/`error`) on `ToolCompleted` (tinyagents#18).
//!
//! Known parity gaps (see `docs/.../C4-journal-progress-parity-plan.md` §2a):
-//! - `ModelCallCompleted.cost_usd` and `cache_creation_tokens` are not on the
-//! crate event; filled as `0` here and to be sourced from the persisted
-//! per-run cost store at export time.
+//! - **Cost is an estimate, not the charge.** The provider's charged USD
+//! reaches the live path through the `usage_carry` side-channel, which is not
+//! an `AgentEvent` and is not journalled, so both the per-call
+//! `ModelCallCompleted.cost_usd` (`0` here — the generation span's cost is
+//! sourced from the persisted per-run cost store at export time) and the
+//! turn roll-up folded from `UsageRecorded` are journal-only figures. Token
+//! counts are exact; treat a projected `gen_ai.usage.cost_usd` as an
+//! estimate. `AgentEvent::CostRecorded` would close this if the crate ever
+//! emits it.
//! - Sub-agent prompt/output content is not on the crate lifecycle events, so
//! subagent spans carry lifecycle/timing and child tool/model structure but
//! empty delegated prompt/final output until a richer journal event exists.
+//! - `AgentProgress::SubagentAwaitingUser` has no journal source at all (the
+//! crate emits no matching lifecycle event), so a subagent span parked on a
+//! user prompt loses that attribute on replay.
+//!
+//! Everything else is projected. In particular the match in
+//! [`observation_to_progress`] is **exhaustive over `AgentEvent`** — a crate
+//! that adds a span-bearing event breaks the build here rather than silently
+//! diverging, which is exactly how the missing `UsageRecorded` roll-up went
+//! unnoticed (openhuman#6148).
use tinyagents_harness::events::AgentEvent;
use tinyagents_harness::observability::AgentObservation;
@@ -41,12 +56,29 @@ struct ReplayState {
/// `ModelCompleted` can name its generation span (the crate `ModelCompleted`
/// event carries no model name).
models: std::collections::HashMap<String, String>,
+ /// Model of the most recent top-level `ModelStarted`. `UsageRecorded`
+ /// carries no `call_id`, so this stands in for the live bridge's
+ /// per-run `self.model` when naming the turn's cost roll-up.
+ model: String,
/// Stack of currently-open sub-agent runs. The crate lifecycle event only
/// carries name/depth; ordered replay brackets child model/tool events.
subagents: Vec<ReplaySubagent>,
/// Monotonic suffix to make repeated invocations of the same child name
/// distinct in the span tree.
next_subagent_seq: u64,
+ /// Top-level iterations whose `UsageRecorded` has already been folded in.
+ /// Mirrors the live bridge's `recorded_iterations` dedupe guard — see the
+ /// `UsageRecorded` arm.
+ recorded_iterations: std::collections::HashSet<u32>,
+ /// Cumulative top-level usage, folded exactly as the live bridge folds it
+ /// so the roll-up carried by `TurnCostUpdated` is a running total.
+ input_tokens: u64,
+ output_tokens: u64,
+ cached_input_tokens: u64,
+ /// Cumulative estimated cost. The provider's *charged* amount rides the
+ /// un-journalled `usage_carry` side-channel, so this is an estimate — see
+ /// the module header.
+ cost_usd: f64,
}
#[derive(Clone)]
@@ -90,6 +122,12 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
}
None => {
state.iteration += 1;
+ // `UsageRecorded` carries no `call_id`; the live bridge names
+ // the roll-up with its per-run model, and the last top-level
+ // `ModelStarted` is the journal's equivalent. Only top-level
+ // calls are recorded — a child's model must not name the
+ // parent's turn.
+ state.model = model.clone();
state.iteration
}
};
@@ -183,6 +221,77 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
}
}
+ AgentEvent::UnknownToolCall {
+ call_id,
+ requested_name,
+ arguments,
+ recovery: _,
+ } => {
+ // #4118: the crate recovers an unavailable tool call without ever
+ // emitting `ToolStarted`/`ToolCompleted` for it, so the live bridge
+ // synthesises the pair itself. Without this arm the projection was
+ // short a whole tool span — a span *count* divergence, not just a
+ // missing attribute — on every turn the model named a tool it did
+ // not have. Mirrors `observability_part_02.rs`'s `UnknownToolCall`
+ // arm exactly, including the `Unknown` (recoverable) class.
+ let failure = Some(crate::openhuman::tools::status::describe(
+ crate::openhuman::tools::status::ToolFailureClass::Unknown,
+ ));
+ let label = format!(
+ "{} (unavailable)",
+ crate::openhuman::tools::traits::humanize_tool_name(requested_name)
+ );
+ let detail = Some("tool not available".to_string());
+ match state.active_subagent() {
+ Some(scope) => vec![
+ AgentProgress::SubagentToolCallStarted {
+ agent_id: scope.agent_id.clone(),
+ task_id: scope.task_id.clone(),
+ call_id: call_id.as_str().to_string(),
+ tool_name: requested_name.clone(),
+ arguments: arguments.clone(),
+ iteration: scope.iteration,
+ display_label: Some(label),
+ display_detail: detail,
+ },
+ AgentProgress::SubagentToolCallCompleted {
+ agent_id: scope.agent_id.clone(),
+ task_id: scope.task_id.clone(),
+ call_id: call_id.as_str().to_string(),
+ tool_name: requested_name.clone(),
+ success: false,
+ output_chars: 0,
+ output: String::new(),
+ arguments: Some(arguments.clone()),
+ elapsed_ms: 0,
+ iteration: scope.iteration,
+ failure,
+ },
+ ],
+ None => vec![
+ AgentProgress::ToolCallStarted {
+ call_id: call_id.as_str().to_string(),
+ tool_name: requested_name.clone(),
+ arguments: arguments.clone(),
+ iteration: state.iteration,
+ display_label: Some(label),
+ display_detail: detail,
+ },
+ AgentProgress::ToolCallCompleted {
+ call_id: call_id.as_str().to_string(),
+ tool_name: requested_name.clone(),
+ success: false,
+ output_chars: 0,
+ output: String::new(),
+ arguments: Some(arguments.clone()),
+ elapsed_ms: 0,
+ iteration: state.iteration,
+ failure,
+ },
+ ],
+ }
+ }
+
AgentEvent::ModelCompleted {
call_id,
usage,
@@ -213,7 +322,13 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
cached_input_tokens: usage.cache_read_tokens,
- cache_creation_tokens: 0,
+ // The crate `Usage` DOES carry cache-creation tokens; this used
+ // to be hardcoded `0`, which dropped the
+ // `gen_ai.usage.cache_creation_tokens` attribute from every
+ // projected generation span (`record_model_call` inserts it only
+ // when `> 0`) and so diverged from live whenever a provider
+ // reported a cache write.
+ cache_creation_tokens: usage.cache_creation_tokens,
reasoning_tokens: usage.reasoning_tokens,
cost_usd: 0.0,
}];
@@ -230,6 +345,58 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
progress
}
+ AgentEvent::UsageRecorded { usage } => {
+ // The cost footer is a top-level surface: the live bridge suppresses
+ // the per-child roll-up (`observability_part_01.rs`, `self.scope`
+ // guard), and a child run's usage is accounted separately. Skipping
+ // entirely — rather than accumulating silently — is what keeps the
+ // projected parent total equal to the live one, because live the
+ // parent and the child are *different* bridge instances with
+ // different accumulators, while the journal interleaves both runs
+ // into one observation stream.
+ if state.active_subagent().is_some() {
+ return Vec::new();
+ }
+ // Dedupe guard, mirroring the live bridge's (W2-budget-dedupe): the
+ // observe-only crate `BudgetMiddleware` makes each model call emit —
+ // and therefore journal — TWO `UsageRecorded` events with identical
+ // usage and *distinct* event ids, so an event-id key would not
+ // collapse them. Key on the run-scoped model-call identity instead:
+ // the iteration cursor, bumped once per `ModelStarted`. Without this
+ // every projected total would be double the live one.
+ if !state.recorded_iterations.insert(state.iteration) {
+ return Vec::new();
+ }
+ // The provider's *charged* amount reaches the live path through the
+ // `usage_carry` side-channel, which is not an `AgentEvent` and is not
+ // journalled (§2a of the C4 parity plan), so the projection prices
+ // the call with the same estimator the live path uses as its floor.
+ // The token counts are exact; `cost_usd` is an estimate.
+ state.cost_usd += crate::openhuman::agent::cost::estimate_call_cost_usd(
+ &state.model,
+ &crate::openhuman::inference::provider::UsageInfo {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ context_window: 0,
+ cached_input_tokens: usage.cache_read_tokens,
+ cache_creation_tokens: usage.cache_creation_tokens,
+ reasoning_tokens: usage.reasoning_tokens,
+ charged_amount_usd: 0.0,
+ },
+ );
+ state.input_tokens += usage.input_tokens;
+ state.output_tokens += usage.output_tokens;
+ state.cached_input_tokens += usage.cache_read_tokens;
+ vec![AgentProgress::TurnCostUpdated {
+ model: state.model.clone(),
+ iteration: state.iteration,
+ input_tokens: state.input_tokens,
+ output_tokens: state.output_tokens,
+ cached_input_tokens: state.cached_input_tokens,
+ total_usd: state.cost_usd,
+ }]
+ }
+
AgentEvent::SubAgentStarted { name, depth } => {
state.next_subagent_seq += 1;
let task_id = format!("{name}-d{depth}-{}", state.next_subagent_seq);
@@ -294,7 +461,62 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
}]
}
- _ => Vec::new(),
+ // Everything below carries no span data. This is written out rather than
+ // left as a `_ =>` catch-all on purpose: a wildcard is what let the
+ // missing `UsageRecorded` arm above sit here silently, diverging from
+ // live on every turn with nothing to catch it. With the match
+ // exhaustive, the next `AgentEvent` the crate adds is a compile error
+ // here — a decision to make, not a gap to discover in a log.
+ //
+ // Streaming/incremental progress. `SpanCollector` folds deltas into no
+ // span (`progress_tracing.rs`), so replaying them would change nothing.
+ AgentEvent::ModelDelta { .. }
+ | AgentEvent::ToolProgress { .. }
+ // Failure detail already carried by a span-bearing sibling: a tool's
+ // outcome rides `ToolCompleted.error`, a model's and a run's ride
+ // `RunFailed`, and `InvalidToolArgs` precedes the `ToolCompleted` that
+ // reports it.
+ | AgentEvent::ToolFailed { .. }
+ | AgentEvent::ModelFailed { .. }
+ | AgentEvent::SubAgentFailed { .. }
+ | AgentEvent::InvalidToolArgs { .. }
+ | AgentEvent::MiddlewareFailed { .. }
+ // Run-shaping diagnostics: they change what the model is asked, never
+ // what the trace records. The live bridge logs them and emits no
+ // `AgentProgress` for any of them either.
+ | AgentEvent::ToolsFiltered { .. }
+ | AgentEvent::WorkspacePrepared { .. }
+ | AgentEvent::WorkspaceViolation { .. }
+ | AgentEvent::WorkspaceCleanup { .. }
+ | AgentEvent::ControlApplied { .. }
+ | AgentEvent::StateUpdate
+ | AgentEvent::MiddlewareStarted { .. }
+ | AgentEvent::MiddlewareCompleted { .. }
+ | AgentEvent::CacheHit { .. }
+ | AgentEvent::CacheMiss { .. }
+ | AgentEvent::RetryScheduled { .. }
+ | AgentEvent::RateLimitWaited { .. }
+ | AgentEvent::FallbackSelected { .. }
+ | AgentEvent::ModelOverrideSkipped { .. }
+ | AgentEvent::FallbackSkipped { .. }
+ | AgentEvent::SubAgentReused { .. }
+ | AgentEvent::Steered { .. }
+ | AgentEvent::Compressed { .. }
+ | AgentEvent::RouteSelected { .. }
+ | AgentEvent::MemoryLoaded
+ | AgentEvent::MemorySaved
+ | AgentEvent::StreamClosed
+ // Budget accounting. The span roll-up is folded from `UsageRecorded`
+ // above; these report headroom, not usage. `CostRecorded` is declared
+ // upstream for future emit and is never emitted today — if the crate
+ // starts emitting it, it becomes the authoritative source for
+ // `TurnCostUpdated.total_usd` and should replace the estimate there.
+ | AgentEvent::CostRecorded { .. }
+ | AgentEvent::BudgetWarning { .. }
+ | AgentEvent::BudgetReserved { .. }
+ | AgentEvent::BudgetReconciled { .. }
+ | AgentEvent::BudgetExceeded { .. }
+ | AgentEvent::LimitReached { .. } => Vec::new(),
}
}
diff --git a/src/openhuman/agent/progress_tracing/journal_projection_tests.rs b/src/openhuman/agent/progress_tracing/journal_projection_tests.rs
index a6b5f3fdc6..606fb886c0 100644
--- a/src/openhuman/agent/progress_tracing/journal_projection_tests.rs
+++ b/src/openhuman/agent/progress_tracing/journal_projection_tests.rs
@@ -332,3 +332,424 @@ fn projects_turn_content_from_root_model_io() {
&serde_json::json!("short summary")
);
}
+
+/// A top-level model call that journals usage: `ModelStarted` → `UsageRecorded`
+/// → `ModelCompleted`, the order the agent loop emits them in
+/// (`run_loop.rs` emits `UsageRecorded` before `ModelCompleted`).
+fn turn_with_usage(usages: &[Usage]) -> Vec<AgentObservation> {
+ let mut events = vec![obs(
+ 0,
+ 1_000,
+ AgentEvent::RunStarted {
+ run_id: RunId::new("run-1"),
+ thread_id: None,
+ },
+ )];
+ let mut offset = 1;
+ for (index, usage) in usages.iter().enumerate() {
+ let call = format!("c{}", index + 1);
+ events.push(obs(
+ offset,
+ 1_010 + offset * 10,
+ AgentEvent::ModelStarted {
+ call_id: CallId::new(&call),
+ model: "gpt-4".to_string(),
+ },
+ ));
+ offset += 1;
+ events.push(obs(
+ offset,
+ 1_010 + offset * 10,
+ AgentEvent::UsageRecorded { usage: *usage },
+ ));
+ offset += 1;
+ events.push(obs(
+ offset,
+ 1_010 + offset * 10,
+ AgentEvent::ModelCompleted {
+ call_id: CallId::new(&call),
+ started_at_ms: Some(1_010),
+ usage: Some(*usage),
+ input: None,
+ output: None,
+ },
+ ));
+ offset += 1;
+ }
+ events.push(obs(
+ offset,
+ 1_010 + offset * 10,
+ AgentEvent::RunCompleted {
+ run_id: RunId::new("run-1"),
+ },
+ ));
+ events
+}
+
+fn turn_span(spans: &[super::TraceSpan]) -> &super::TraceSpan {
+ spans
+ .iter()
+ .find(|s| s.kind == SpanKind::Turn)
+ .expect("a root turn span")
+}
+
+/// #6148: the journal-shadow parity check compares attribute *keys*, and the
+/// root turn span's `gen_ai.*` group is written only by `TurnCostUpdated` —
+/// which the projection never emitted, so every turn diverged.
+#[test]
+fn usage_recorded_projects_the_turn_cost_rollup() {
+ let spans = spans_from_observations(ctx(), 10, &turn_with_usage(&[Usage::new(100, 20)]));
+ let turn = turn_span(&spans);
+
+ for key in [
+ "gen_ai.request.model",
+ "gen_ai.usage.input_tokens",
+ "gen_ai.usage.output_tokens",
+ "gen_ai.usage.cached_input_tokens",
+ "gen_ai.usage.cost_usd",
+ ] {
+ assert!(
+ turn.attributes.contains_key(key),
+ "projected turn span carries {key} (parity with the live span)"
+ );
+ }
+ assert_eq!(
+ turn.attributes["gen_ai.usage.input_tokens"],
+ serde_json::json!(100)
+ );
+ assert_eq!(
+ turn.attributes["gen_ai.usage.output_tokens"],
+ serde_json::json!(20)
+ );
+ // `gen_ai.request.model` is deliberately NOT value-asserted here: the roll-up
+ // writes the raw handle, and the `ModelCallCompleted` that follows overwrites
+ // the root with the provider-labeled `{provider_id}.{model}` form on both
+ // paths. The journal carries no `provider_id` (§2a), so this is `".gpt-4"`
+ // here against `"openai.gpt-4"` live — a *value* difference the key-only
+ // parity signature does not see, and the reason that key was never among the
+ // four the shadow check reported missing.
+}
+
+/// The roll-up is cumulative across a turn's model calls, matching the live
+/// bridge's running `BridgeState` totals rather than reporting the last call.
+#[test]
+fn turn_cost_rollup_accumulates_across_model_calls() {
+ let spans = spans_from_observations(
+ ctx(),
+ 10,
+ &turn_with_usage(&[Usage::new(100, 20), Usage::new(50, 5)]),
+ );
+ let turn = turn_span(&spans);
+ assert_eq!(
+ turn.attributes["gen_ai.usage.input_tokens"],
+ serde_json::json!(150)
+ );
+ assert_eq!(
+ turn.attributes["gen_ai.usage.output_tokens"],
+ serde_json::json!(25)
+ );
+}
+
+/// The observe-only crate `BudgetMiddleware` re-emits `UsageRecorded` for every
+/// model call, so the journal holds TWO identical events per call with distinct
+/// event ids. The live bridge dedupes on the iteration cursor; without the same
+/// guard here every projected total would be doubled.
+#[test]
+fn duplicate_usage_recorded_for_one_call_is_folded_once() {
+ let mut observations = turn_with_usage(&[Usage::new(100, 20)]);
+ // Re-emit the middleware's duplicate immediately after the loop's own event,
+ // with a distinct offset (and therefore a distinct event id).
+ observations.insert(
+ 3,
+ obs(
+ 99,
+ 1_035,
+ AgentEvent::UsageRecorded {
+ usage: Usage::new(100, 20),
+ },
+ ),
+ );
+
+ let spans = spans_from_observations(ctx(), 10, &observations);
+ let turn = turn_span(&spans);
+ assert_eq!(
+ turn.attributes["gen_ai.usage.input_tokens"],
+ serde_json::json!(100),
+ "the middleware's duplicate must not double the roll-up"
+ );
+ assert_eq!(
+ turn.attributes["gen_ai.usage.output_tokens"],
+ serde_json::json!(20)
+ );
+}
+
+/// Live, a child run has its own bridge instance and its own accumulator, and
+/// the per-child `TurnCostUpdated` is suppressed. The journal interleaves both
+/// runs into one stream, so the projection must skip child usage outright or the
+/// parent turn would over-report.
+#[test]
+fn subagent_usage_does_not_roll_into_the_parent_turn() {
+ let observations = vec![
+ obs(
+ 0,
+ 1_000,
+ AgentEvent::RunStarted {
+ run_id: RunId::new("run-1"),
+ thread_id: None,
+ },
+ ),
+ obs(
+ 1,
+ 1_010,
+ AgentEvent::ModelStarted {
+ call_id: CallId::new("c1"),
+ model: "gpt-4".to_string(),
+ },
+ ),
+ obs(
+ 2,
+ 1_020,
+ AgentEvent::UsageRecorded {
+ usage: Usage::new(100, 20),
+ },
+ ),
+ obs(
+ 3,
+ 1_030,
+ AgentEvent::SubAgentStarted {
+ name: "researcher".to_string(),
+ depth: 1,
+ },
+ ),
+ obs(
+ 4,
+ 1_040,
+ AgentEvent::ModelStarted {
+ call_id: CallId::new("c2"),
+ model: "gpt-4-mini".to_string(),
+ },
+ ),
+ obs(
+ 5,
+ 1_050,
+ AgentEvent::UsageRecorded {
+ usage: Usage::new(7_000, 900),
+ },
+ ),
+ obs(
+ 6,
+ 1_060,
+ AgentEvent::SubAgentCompleted {
+ name: "researcher".to_string(),
+ depth: 1,
+ },
+ ),
+ obs(
+ 7,
+ 1_070,
+ AgentEvent::RunCompleted {
+ run_id: RunId::new("run-1"),
+ },
+ ),
+ ];
+
+ let spans = spans_from_observations(ctx(), 10, &observations);
+ let turn = turn_span(&spans);
+ assert_eq!(
+ turn.attributes["gen_ai.usage.input_tokens"],
+ serde_json::json!(100),
+ "the child's 7000 input tokens stay out of the parent roll-up"
+ );
+ assert_eq!(
+ turn.attributes["gen_ai.request.model"],
+ serde_json::json!("gpt-4"),
+ "the child's model must not rename the parent turn"
+ );
+}
+
+/// `journal_projection` used to hardcode `cache_creation_tokens: 0` even though
+/// the crate `Usage` carries the real value. `record_model_call` inserts that
+/// attribute only when `> 0`, so the zero dropped the key from every projected
+/// generation span whenever a provider reported a cache write.
+#[test]
+fn cache_creation_tokens_reach_the_projected_generation_span() {
+ let usage = Usage {
+ cache_creation_tokens: 512,
+ ..Usage::new(100, 20)
+ };
+ let spans = spans_from_observations(ctx(), 10, &turn_with_usage(&[usage]));
+ let generation = spans
+ .iter()
+ .find(|s| s.kind == SpanKind::Generation)
+ .expect("a generation span");
+ assert_eq!(
+ generation.attributes["gen_ai.usage.cache_creation_tokens"],
+ serde_json::json!(512)
+ );
+}
+
+/// #4118: the crate recovers an unavailable tool call without emitting
+/// `ToolStarted`/`ToolCompleted`, and the live bridge synthesises the pair. The
+/// projection had no arm, so it was short a whole tool span — a span *count*
+/// divergence, not merely a missing attribute.
+#[test]
+fn unknown_tool_call_projects_a_failed_tool_span() {
+ let observations = vec![
+ obs(
+ 0,
+ 1_000,
+ AgentEvent::RunStarted {
+ run_id: RunId::new("run-1"),
+ thread_id: None,
+ },
+ ),
+ obs(
+ 1,
+ 1_010,
+ AgentEvent::ModelStarted {
+ call_id: CallId::new("c1"),
+ model: "gpt-4".to_string(),
+ },
+ ),
+ obs(
+ 2,
+ 1_020,
+ AgentEvent::UnknownToolCall {
+ call_id: CallId::new("t1"),
+ requested_name: "send_fax".to_string(),
+ arguments: serde_json::json!({ "to": "1234" }),
+ recovery: "rewrite:none".to_string(),
+ },
+ ),
+ obs(
+ 3,
+ 1_030,
+ AgentEvent::RunCompleted {
+ run_id: RunId::new("run-1"),
+ },
+ ),
+ ];
+
+ let spans = spans_from_observations(ctx(), 10, &observations);
+ let tool = spans
+ .iter()
+ .find(|s| s.kind == SpanKind::Tool)
+ .expect("the recovered call still produces a tool span");
+ assert_eq!(tool.name, "tool.send_fax");
+ assert_eq!(tool.attributes["tool.success"], serde_json::json!(false));
+ assert_eq!(tool.status, SpanStatus::Error);
+}
+
+/// The child-scope half of the `UnknownToolCall` projection: a sub-agent that
+/// names an unavailable tool gets the same synthesised failed-call pair, nested
+/// under its subagent span rather than the root turn.
+#[test]
+fn unknown_tool_call_inside_a_subagent_projects_a_child_tool_span() {
+ let observations = vec![
+ obs(
+ 0,
+ 1_000,
+ AgentEvent::RunStarted {
+ run_id: RunId::new("run-1"),
+ thread_id: None,
+ },
+ ),
+ obs(
+ 1,
+ 1_010,
+ AgentEvent::SubAgentStarted {
+ name: "researcher".to_string(),
+ depth: 1,
+ },
+ ),
+ obs(
+ 2,
+ 1_020,
+ AgentEvent::ModelStarted {
+ call_id: CallId::new("c1"),
+ model: "gpt-4-mini".to_string(),
+ },
+ ),
+ obs(
+ 3,
+ 1_030,
+ AgentEvent::UnknownToolCall {
+ call_id: CallId::new("t1"),
+ requested_name: "send_fax".to_string(),
+ arguments: serde_json::json!({ "to": "1234" }),
+ recovery: "rewrite:none".to_string(),
+ },
+ ),
+ obs(
+ 4,
+ 1_040,
+ AgentEvent::SubAgentCompleted {
+ name: "researcher".to_string(),
+ depth: 1,
+ },
+ ),
+ obs(
+ 5,
+ 1_050,
+ AgentEvent::RunCompleted {
+ run_id: RunId::new("run-1"),
+ },
+ ),
+ ];
+
+ let spans = spans_from_observations(ctx(), 10, &observations);
+ let subagent = spans
+ .iter()
+ .find(|s| s.kind == SpanKind::Subagent)
+ .expect("a subagent span");
+ let tool = spans
+ .iter()
+ .find(|s| s.kind == SpanKind::Tool)
+ .expect("the recovered child call still produces a tool span");
+ assert_eq!(tool.name, "tool.send_fax");
+ assert_eq!(tool.attributes["tool.success"], serde_json::json!(false));
+ assert_eq!(tool.status, SpanStatus::Error);
+ assert_ne!(
+ tool.parent_span_id.as_deref(),
+ None,
+ "the child tool span is parented inside the subagent scope"
+ );
+ assert!(
+ spans.iter().any(|s| s.kind == SpanKind::SubagentIteration),
+ "the child iteration span brackets it (subagent {})",
+ subagent.span_id
+ );
+}
+
+/// The exhaustive no-op arms: events that carry no span data must project to
+/// nothing, leaving the span tree byte-identical to the same journal without
+/// them. Guards against a future arm being moved out of the no-op group by
+/// accident.
+#[test]
+fn non_span_bearing_events_project_to_no_spans() {
+ let baseline = spans_from_observations(ctx(), 10, &turn_with_usage(&[Usage::new(100, 20)]));
+
+ let mut noisy = turn_with_usage(&[Usage::new(100, 20)]);
+ noisy.insert(
+ 2,
+ obs(
+ 90,
+ 1_015,
+ AgentEvent::CacheHit {
+ call_id: CallId::new("c1"),
+ key: "k".to_string(),
+ },
+ ),
+ );
+ noisy.insert(3, obs(91, 1_016, AgentEvent::MemoryLoaded));
+ noisy.insert(4, obs(92, 1_017, AgentEvent::StreamClosed));
+ let projected = spans_from_observations(ctx(), 10, &noisy);
+
+ assert_eq!(
+ projected.len(),
+ baseline.len(),
+ "diagnostic events add no spans"
+ );
+ let kinds = |spans: &[super::TraceSpan]| spans.iter().map(|s| s.kind).collect::<Vec<_>>();
+ assert_eq!(kinds(&projected), kinds(&baseline));
+}