Skip to content

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

chore(progress_tracing): remove the progress tracing module

Steven Enamakela6a54ef23d62
diff --git a/crates/openhuman-core/src/agent/progress_tracing/README.md b/crates/openhuman-core/src/agent/progress_tracing/README.md
deleted file mode 100644
index 80257b7b3e..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/README.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# progress_tracing
-
-Turns the agent's real-time [`AgentProgress`](../progress.rs) event stream into
-OpenTelemetry/Langfuse-style trace spans (`agent.turn` -> `agent.iteration` ->
-`tool.*`/`subagent.*`), correlated by session id, for offline inspection and
-debugging long multi-agent runs (issue #3886). The module doc on
-[`core/observability/progress_tracing.rs`](../progress_tracing.rs) has the full span-tree shape and the
-content-capture privacy gate (`observability.agent_tracing.capture_content`,
-default on; enforced once, in `SpanCollector`, so no exporter can leak
-content).
-
-## Key files
-
-- `core/observability/progress_tracing.rs` (parent module file) declares the submodules
- below it. `collector/` holds `SpanCollector` (a pure state machine: feed it
- progress events plus a timestamp, it accumulates finished `TraceSpan`s).
- The data model (`TraceContext`, `RunType`, `SpanKind`/`SpanStatus`), content
- caps, `spans_to_ndjson`, the pure OTLP conversion and Langfuse batch
- chunking live upstream in
- `tinyagents_harness::observability::trace_export`. [`export.rs`](./export.rs) has the local file/log
- exporter `export_spans`, and the two run-completion entry points
- `export_run_trace` / `export_run_trace_from_journal`. Each entry point runs
- two independent, best-effort paths: a Langfuse push when
- `observability.share_usage_data` is on (the default), and local NDJSON
- export to `export_path` or the app log when
- `observability.agent_tracing.enabled` is on (opt-in).
-- [`otlp.rs`](./otlp.rs): the remote agent-turn exporter (the span-to-OTLP conversion is
- upstream; this file resolves the backend URL and credential and posts). It turns completed live spans
- into OTLP/HTTP JSON, preserves the root turn's input/output, maps
- TinyInference messages into role-labeled conversations, puts usage only on
- model generations, and summarizes repeated internal tool discovery.
- It POSTs through the authenticated backend's
- `/telemetry/langfuse/otel/v1/traces` proxy; the backend supplies project
- keys and authoritative user attribution. Export is on by default through
- `observability.share_usage_data`; local NDJSON export remains optional.
-- [`langfuse/environment.rs`](./langfuse/environment.rs) hold the proxy URL and environment
- resolution `otlp.rs` and the flow exporter share, plus the legacy batch
- projection kept for compatibility tests. No trace is sent on the legacy
- batch path; Langfuse v4 ingests traces only over OTLP.
-- [`journal_projection.rs`](./journal_projection.rs): `spans_from_observations` rebuilds spans from the
- durable `AgentObservation` journal instead of the live stream, by folding
- journalled events through the same `SpanCollector`, so a UI/supervisor can
- attach after a run. Its match is exhaustive over
- `tinyagents_harness::events::AgentEvent`; the module doc lists the known
- parity gaps (estimated vs. charged cost, no subagent prompt/output content).
-
-Tests live in this directory as `*_tests.rs` files, e.g.
-[`progress_tracing_tests.rs`](./progress_tracing_tests.rs), [`progress_tracing_span_tree_tests.rs`](./progress_tracing_span_tree_tests.rs),
-[`progress_tracing_attribution_tests.rs`](./progress_tracing_attribution_tests.rs), [`progress_tracing_content_gate_tests.rs`](./progress_tracing_content_gate_tests.rs),
-[`langfuse_tests.rs`](./langfuse_tests.rs), [`langfuse_batch_tests.rs`](./langfuse_batch_tests.rs), [`langfuse_trace_fields_tests.rs`](./langfuse_trace_fields_tests.rs),
-[`journal_projection_tests.rs`](./journal_projection_tests.rs), [`journal_projection_cost_rollup_tests.rs`](./journal_projection_cost_rollup_tests.rs).
-
-## Called by
-
-- [`web_chat/progress_bridge.rs`](../../web_chat/progress_bridge.rs): the only caller. Builds a `SpanCollector`
- per run, feeds it `AgentProgress`, shadow-compares the live spans against
- `spans_from_observations` over the run journal, then calls
- `export_run_trace_from_journal` (journal available) or `export_run_trace`.
-
-[`flows/tinyflows/langfuse_export.rs`](../../flows/tinyflows/langfuse_export.rs) is the separate flow-run exporter. It
-builds the graph trace with `tinyagents_graph::GraphLangfuseExporter` and sends
-it to the same OTLP proxy route as Langfuse v4 spans
-(`build_otlp_requests`), so no trace goes to the legacy batch path.
-
-## Related docs
-
-- [docs/gitbooks/en/developing/agent-observability.md](../../../../../docs/gitbooks/en/developing/agent-observability.md)
-- [Parent module README](../README.md)
-- [Agent harness architecture](../../../../../docs/gitbooks/en/developing/architecture/agent-harness.md)
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs
deleted file mode 100644
index 2b7b303bc8..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs
+++ /dev/null
@@ -1,577 +0,0 @@
-//! Folding the live [`AgentProgress`] event stream into the span tree, and
-//! sealing whatever is left open once the stream closes.
-
-use std::collections::BTreeMap;
-
-use crate::progress::AgentProgress;
-use tinyagents_harness::observability::trace_export::serialize::{
- json_f64, json_str, json_u32, json_u64, json_usize, status_of, truncate_chars,
- MAX_ERROR_MESSAGE_CHARS, MAX_MODEL_CONTENT_CHARS,
-};
-use tinyagents_harness::observability::trace_export::SpanKind;
-
-use super::state::{SpanCollector, SubagentState};
-use tinyagents_harness::observability::trace_export::SpanStatus;
-
-impl SpanCollector {
- /// Fold a single progress event into the span tree, stamped at
- /// `now_unix_ms` (the consumer's wall clock when it observed the event).
- pub fn record(&mut self, event: &AgentProgress, now_unix_ms: u64) {
- self.last_activity_unix_ms = self.last_activity_unix_ms.max(now_unix_ms);
- match event {
- AgentProgress::TurnStarted => {
- self.ensure_turn_span(now_unix_ms);
- }
-
- AgentProgress::IterationStarted {
- iteration,
- max_iterations,
- } => {
- self.close_current_iteration(now_unix_ms);
- self.first_deltas = Default::default();
- self.call_clock = Default::default();
- let parent = self.ensure_turn_span(now_unix_ms);
- let mut attrs = BTreeMap::new();
- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));
- attrs.insert(
- "agent.max_iterations".to_string(),
- json_u32(*max_iterations),
- );
- let (id, index) = self.open_span(
- SpanKind::Iteration,
- format!("agent.iteration#{iteration}"),
- Some(parent),
- now_unix_ms,
- attrs,
- );
- self.current_iteration_span_id = Some(id);
- self.current_iteration_index = Some(index);
- }
-
- AgentProgress::ToolCallStarted {
- call_id,
- tool_name,
- arguments,
- iteration,
- ..
- } => {
- let parent = self.active_parent_id(now_unix_ms);
- let mut attrs = BTreeMap::new();
- attrs.insert("tool.name".to_string(), json_str(tool_name));
- attrs.insert("tool.call_id".to_string(), json_str(call_id));
- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));
- if let Some(model) = &self.last_model {
- attrs.insert("tool.model".to_string(), json_str(model));
- }
- let (_, index) = self.open_span(
- SpanKind::Tool,
- format!("tool.{tool_name}"),
- Some(parent),
- now_unix_ms,
- attrs,
- );
- self.capture_tool_arguments(index, arguments);
- self.open_tools.insert(call_id.clone(), index);
- }
-
- AgentProgress::ToolCallCompleted {
- call_id,
- success,
- output_chars,
- output,
- arguments,
- elapsed_ms,
- failure,
- ..
- } => {
- if let Some(index) = self.open_tools.remove(call_id) {
- // The tinyagents path emits `Null` arguments on the started
- // event and the real captured arguments on completion —
- // backfill the span input when it's still empty.
- if self.spans[index].input.is_none() {
- if let Some(arguments) = arguments {
- self.capture_tool_arguments(index, arguments);
- }
- }
- self.capture_tool_output(index, output);
- let start = self.spans[index].start_unix_ms;
- let mut extra = BTreeMap::new();
- extra.insert(
- "tool.success".to_string(),
- serde_json::Value::Bool(*success),
- );
- extra.insert("tool.output_chars".to_string(), json_usize(*output_chars));
- extra.insert("tool.elapsed_ms".to_string(), json_u64(*elapsed_ms));
- self.insert_failure_attrs(failure.as_ref(), &mut extra);
- self.close_span(index, start + elapsed_ms, status_of(*success), extra);
- }
- }
-
- AgentProgress::ModelCallCompleted {
- model,
- provider_id,
- subagent_task_id,
- input,
- output,
- iteration,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cache_creation_tokens,
- reasoning_tokens,
- cost_usd,
- } => {
- self.record_model_call(
- model,
- provider_id,
- subagent_task_id.as_deref(),
- input.as_ref(),
- output.as_ref(),
- *iteration,
- *input_tokens,
- *output_tokens,
- *cached_input_tokens,
- *cache_creation_tokens,
- *reasoning_tokens,
- *cost_usd,
- now_unix_ms,
- );
- }
-
- AgentProgress::SubagentSpawned {
- agent_id,
- task_id,
- mode,
- dedicated_thread,
- prompt_chars,
- prompt,
- display_name,
- ..
- } => {
- let parent = self.active_parent_id(now_unix_ms);
- let label = display_name.clone().unwrap_or_else(|| agent_id.clone());
- let mut attrs = BTreeMap::new();
- attrs.insert("subagent.agent_id".to_string(), json_str(agent_id));
- attrs.insert("subagent.task_id".to_string(), json_str(task_id));
- attrs.insert("subagent.mode".to_string(), json_str(mode));
- attrs.insert(
- "subagent.dedicated_thread".to_string(),
- serde_json::Value::Bool(*dedicated_thread),
- );
- attrs.insert(
- "subagent.prompt_chars".to_string(),
- json_usize(*prompt_chars),
- );
- if let Some(name) = display_name {
- attrs.insert("subagent.display_name".to_string(), json_str(name));
- }
- let (_, index) = self.open_span(
- SpanKind::Subagent,
- format!("subagent.{label}"),
- Some(parent),
- now_unix_ms,
- attrs,
- );
- // The delegated prompt is the subagent span's input (gated +
- // truncated like model content — scout prompts run 10k+ chars).
- if self.ctx.capture_content && !prompt.is_empty() {
- if let Some(span) = self.spans.get_mut(index) {
- span.input = Some(serde_json::Value::String(truncate_chars(
- prompt,
- MAX_MODEL_CONTENT_CHARS,
- )));
- }
- }
- self.finished_subagents.remove(task_id);
- self.subagents
- .insert(task_id.clone(), SubagentState::new(index));
- }
-
- AgentProgress::SubagentIterationStarted {
- task_id,
- iteration,
- max_iterations,
- extended_policy,
- ..
- } => {
- // Resolve parent + prior child iteration up front so we don't
- // hold a borrow across the mutating open_span call.
- let (parent_id, prior_iteration_id) = match self.subagent_state(task_id) {
- Some(state) => (
- self.spans[state.span_index].span_id.clone(),
- state.current_iteration_span_id.clone(),
- ),
- None => return,
- };
- if let Some(prior) = prior_iteration_id {
- if let Some(idx) = self.span_index_by_id(&prior) {
- self.close_span(idx, now_unix_ms, SpanStatus::Ok, BTreeMap::new());
- }
- }
- let mut attrs = BTreeMap::new();
- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));
- attrs.insert(
- "agent.max_iterations".to_string(),
- json_u32(*max_iterations),
- );
- attrs.insert(
- "agent.extended_policy".to_string(),
- serde_json::Value::Bool(*extended_policy),
- );
- let (id, _) = self.open_span(
- SpanKind::SubagentIteration,
- format!("subagent.iteration#{iteration}"),
- Some(parent_id),
- now_unix_ms,
- attrs,
- );
- if let Some(state) = self.subagent_state_mut(task_id) {
- state.current_iteration_span_id = Some(id.clone());
- state.last_iteration_span_id = Some(id);
- state.first_deltas = Default::default();
- state.call_clock = Default::default();
- }
- }
-
- AgentProgress::SubagentToolCallStarted {
- task_id,
- call_id,
- tool_name,
- arguments,
- iteration,
- ..
- } => {
- let (parent_id, model) = match self.subagent_state(task_id) {
- Some(state) => (
- match state
- .current_iteration_span_id
- .as_ref()
- .or(state.last_iteration_span_id.as_ref())
- {
- Some(id) => id.clone(),
- None => self.spans[state.span_index].span_id.clone(),
- },
- state.last_model.clone(),
- ),
- None => {
- log::debug!(
- "[agent-tracing] tool start for unknown subagent task_id={task_id} \
- call_id={call_id}; dropped"
- );
- return;
- }
- };
- let mut attrs = BTreeMap::new();
- attrs.insert("tool.name".to_string(), json_str(tool_name));
- attrs.insert("tool.call_id".to_string(), json_str(call_id));
- attrs.insert("agent.iteration".to_string(), json_u32(*iteration));
- if let Some(model) = model {
- attrs.insert("tool.model".to_string(), json_str(&model));
- }
- let (_, index) = self.open_span(
- SpanKind::Tool,
- format!("tool.{tool_name}"),
- Some(parent_id),
- now_unix_ms,
- attrs,
- );
- self.capture_tool_arguments(index, arguments);
- if let Some(state) = self.subagent_state_mut(task_id) {
- state.open_tools.insert(call_id.clone(), index);
- }
- }
-
- AgentProgress::SubagentToolCallCompleted {
- task_id,
- call_id,
- success,
- output_chars,
- output,
- arguments,
- elapsed_ms,
- failure,
- ..
- } => {
- // Finished subagents are searched too: under channel backpressure
- // a child's completion events can reach the collector after the
- // orchestrator's `SubagentCompleted`, and dropping them left the
- // tool span open until the turn ended.
- let Some(index) = self
- .subagent_state_mut(task_id)
- .and_then(|state| state.open_tools.remove(call_id))
- else {
- log::debug!(
- "[agent-tracing] tool completion without an open span \
- task_id={task_id} call_id={call_id}; dropped"
- );
- return;
- };
- if self.spans[index].input.is_none() {
- if let Some(arguments) = arguments {
- self.capture_tool_arguments(index, arguments);
- }
- }
- self.capture_tool_output(index, output);
- let start = self.spans[index].start_unix_ms;
- let mut extra = BTreeMap::new();
- extra.insert(
- "tool.success".to_string(),
- serde_json::Value::Bool(*success),
- );
- extra.insert("tool.output_chars".to_string(), json_usize(*output_chars));
- extra.insert("tool.elapsed_ms".to_string(), json_u64(*elapsed_ms));
- self.insert_failure_attrs(failure.as_ref(), &mut extra);
- self.close_span(index, start + elapsed_ms, status_of(*success), extra);
- }
-
- AgentProgress::SubagentCompleted {
- task_id,
- elapsed_ms,
- iterations,
- output_chars,
- output,
- stop,
- ..
- } => {
- let Some(span_index) = self.retire_subagent(task_id, now_unix_ms, SpanStatus::Ok)
- else {
- return;
- };
- let state = SubagentSpanRef { span_index };
- // The subagent's final assistant text is the span's output
- // (same gate + cap as its prompt input).
- if self.ctx.capture_content && !output.is_empty() {
- if let Some(span) = self.spans.get_mut(state.span_index) {
- span.output = Some(serde_json::Value::String(truncate_chars(
- output,
- MAX_MODEL_CONTENT_CHARS,
- )));
- }
- }
- let start = self.spans[state.span_index].start_unix_ms;
- let mut extra = BTreeMap::new();
- extra.insert("subagent.iterations".to_string(), json_u32(*iterations));
- extra.insert(
- "subagent.output_chars".to_string(),
- json_usize(*output_chars),
- );
- extra.insert("subagent.elapsed_ms".to_string(), json_u64(*elapsed_ms));
- // A child the harness stopped early (breaker / iteration cap)
- // is handed back incomplete: WARNING, not a clean Ok.
- let status = match stop {
- Some(stop) => {
- Self::insert_stop_attrs(stop, &mut extra);
- log::debug!(
- "[agent-tracing] subagent stopped early task_id={task_id} {}",
- stop.status_message()
- );
- SpanStatus::Unset
- }
- None => SpanStatus::Ok,
- };
- self.close_span(state.span_index, start + elapsed_ms, status, extra);
- }
-
- AgentProgress::SubagentFailed { task_id, error, .. } => {
- let Some(span_index) =
- self.retire_subagent(task_id, now_unix_ms, SpanStatus::Error)
- else {
- return;
- };
- let state = SubagentSpanRef { span_index };
- let mut extra = BTreeMap::new();
- // Always record that an error occurred and its length. The raw
- // error text (may embed paths / payloads) is recorded — truncated
- // — only when content capture is on, and surfaces in Langfuse as
- // the observation statusMessage.
- extra.insert("error".to_string(), serde_json::Value::Bool(true));
- extra.insert("error.length".to_string(), json_usize(error.len()));
- if self.ctx.capture_content {
- extra.insert(
- "error.message".to_string(),
- serde_json::Value::String(truncate_chars(error, MAX_ERROR_MESSAGE_CHARS)),
- );
- }
- self.close_span(state.span_index, now_unix_ms, SpanStatus::Error, extra);
- }
-
- AgentProgress::TurnCostUpdated {
- model,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- total_usd,
- ..
- } => {
- // Cumulative cost/usage rides on the root turn span so a trace
- // viewer shows the whole-run total at the top.
- let index = match self.turn_span_index {
- Some(idx) => idx,
- None => {
- self.ensure_turn_span(now_unix_ms);
- self.turn_span_index.expect("turn span just created")
- }
- };
- if let Some(span) = self.spans.get_mut(index) {
- span.attributes
- .insert("gen_ai.request.model".to_string(), json_str(model));
- span.attributes.insert(
- "gen_ai.usage.input_tokens".to_string(),
- json_u64(*input_tokens),
- );
- span.attributes.insert(
- "gen_ai.usage.output_tokens".to_string(),
- json_u64(*output_tokens),
- );
- span.attributes.insert(
- "gen_ai.usage.cached_input_tokens".to_string(),
- json_u64(*cached_input_tokens),
- );
- span.attributes
- .insert("gen_ai.usage.cost_usd".to_string(), json_f64(*total_usd));
- }
- }
-
- AgentProgress::TurnContent { input, output } => {
- // Storage-level privacy gate (#4454): prompt/reply text is
- // attached to the span ONLY when content capture is opted in.
- // With the gate off (default), the content is dropped here so no
- // exporter — NDJSON file, app log, or Langfuse push — can ever
- // serialize it. This is the single choke point; the exporters
- // deliberately do not re-check the flag.
- if !self.ctx.capture_content {
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] TurnContent dropped at storage (capture_content=false)"
- );
- return;
- }
- let index = match self.turn_span_index {
- Some(idx) => idx,
- None => {
- self.ensure_turn_span(now_unix_ms);
- self.turn_span_index.expect("turn span just created")
- }
- };
- // The first input is the originating user message (the web
- // channel records it before the run starts); a later one — the
- // commit path's last user-role message, which can be tool
- // results or a harness nudge — must not replace it.
- let record_input = !self.turn_input_recorded
- && input.as_deref().is_some_and(|text| !text.trim().is_empty());
- if record_input {
- self.turn_input_recorded = true;
- }
- if let Some(span) = self.spans.get_mut(index) {
- if let (true, Some(text)) = (record_input, input) {
- span.input = Some(serde_json::Value::String(truncate_chars(
- text,
- MAX_MODEL_CONTENT_CHARS,
- )));
- }
- if let Some(text) = output {
- span.output = Some(serde_json::Value::String(truncate_chars(
- text,
- MAX_MODEL_CONTENT_CHARS,
- )));
- }
- log::debug!(
- target: "agent-tracing",
- "[agent-tracing] TurnContent attached to turn span (capture_content=true)"
- );
- }
- }
-
- AgentProgress::TurnCompleted { iterations, stop } => {
- self.close_current_iteration(now_unix_ms);
- if let Some(index) = self.turn_span_index {
- self.spans[index]
- .attributes
- .insert("agent.iterations".to_string(), json_u32(*iterations));
- // A turn the harness stopped early still arrives here; it
- // closes at WARNING instead of as a clean completion.
- let outcome = match stop {
- Some(stop) => super::state::TurnOutcome::Stopped { stop: stop.clone() },
- None => super::state::TurnOutcome::Completed,
- };
- self.apply_turn_outcome(outcome, now_unix_ms);
- }
- }
-
- // Content-bearing / streaming events carry prompt text, tool
- // arguments, or model output — never exported (privacy rule).
- // Only *when* the first one arrived is kept, for time to first
- // token on the generation span.
- AgentProgress::TextDelta { .. } => self.first_deltas.observe(now_unix_ms, true),
- AgentProgress::ThinkingDelta { .. } | AgentProgress::ToolCallArgsDelta { .. } => {
- self.first_deltas.observe(now_unix_ms, false)
- }
- AgentProgress::SubagentTextDelta { task_id, .. } => {
- if let Some(state) = self.subagent_state_mut(task_id) {
- state.first_deltas.observe(now_unix_ms, true);
- }
- }
- AgentProgress::SubagentThinkingDelta { task_id, .. } => {
- if let Some(state) = self.subagent_state_mut(task_id) {
- state.first_deltas.observe(now_unix_ms, false);
- }
- }
- AgentProgress::SubagentAwaitingUser { .. } => {}
- // A running tool's status line can quote its output (a shell
- // call's last line), so it is content and never exported.
- AgentProgress::ToolCallProgress { .. } => {}
- }
- }
-}
-
-/// Span index of a subagent that just completed or failed (its full state has
-/// moved to `finished_subagents`).
-struct SubagentSpanRef {
- span_index: usize,
-}
-
-impl SpanCollector {
- /// Failure attributes for a closing tool span (parent or child).
- ///
- /// * `tool.failure_class` — the classified class (`CommandFailed`,
- /// `InvalidArguments`, `NotFound`, …). Content-free, so not gated: it is
- /// what separates a program that exited non-zero from a harness failure
- /// on an error-level observation.
- /// * `observation.level = WARNING` — for `CommandFailed` only.
- /// * `error.message` — the classified plain-language cause, truncated,
- /// which Langfuse renders as the statusMessage. Gated on content capture
- /// (it can quote user data / paths).
- fn insert_failure_attrs(
- &self,
- failure: Option<&tinytools::status::ClassifiedFailure>,
- extra: &mut BTreeMap<String, serde_json::Value>,
- ) {
- let Some(failure) = failure else {
- return;
- };
- if let Ok(serde_json::Value::String(class)) = serde_json::to_value(failure.class) {
- extra.insert(
- "tool.failure_class".to_string(),
- serde_json::Value::String(class),
- );
- }
- // A program that ran and exited non-zero is an expected outcome, not a
- // harness failure: export it at WARNING so error rates count only the
- // latter.
- if failure.class == tinytools::status::ToolFailureClass::CommandFailed {
- extra.insert(
- super::finish::LEVEL_ATTR.to_string(),
- serde_json::Value::String("WARNING".to_string()),
- );
- }
- if self.ctx.capture_content {
- extra.insert(
- "error.message".to_string(),
- serde_json::Value::String(truncate_chars(
- &failure.cause_plain,
- MAX_ERROR_MESSAGE_CHARS,
- )),
- );
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/finish.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/finish.rs
deleted file mode 100644
index fc0f3bd5a4..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/finish.rs
+++ /dev/null
@@ -1,221 +0,0 @@
-//! Sealing the span tree: retiring a finished subagent, recording a turn's
-//! outcome on the root span, and force-closing whatever is still open when
-//! the progress stream ends.
-
-use std::collections::BTreeMap;
-
-use tinyagents_harness::observability::trace_export::serialize::{
- json_str, truncate_chars, MAX_ERROR_MESSAGE_CHARS,
-};
-use tinyagents_harness::observability::trace_export::{SpanKind, SpanStatus};
-
-use super::state::{SpanCollector, TurnOutcome};
-
-/// Metadata key marking a span this collector closed without its completion
-/// event. Its latency is a bound, not a measurement.
-pub(crate) const FORCE_CLOSED_ATTR: &str = "force_closed";
-/// Span attribute carrying a Langfuse level override: `WARNING` for spans that
-/// need attention without being harness failures (a force-closed tool, a
-/// cancelled turn, a command that exited non-zero). The OTLP converter exports
-/// it as the observation level.
-pub(crate) const LEVEL_ATTR: &str =
- tinyagents_harness::observability::trace_export::otlp::OBSERVATION_LEVEL_ATTR;
-
-impl SpanCollector {
- /// Seal every span still open after the stream closes. Idempotent.
- ///
- /// A turn span still open here never saw `TurnCompleted`, so it is sealed
- /// as [`TurnOutcome::Incomplete`]. Callers that know how the turn ended
- /// use [`Self::finish_with_outcome`].
- pub fn finish(&mut self, now_unix_ms: u64) {
- self.finish_with_outcome(now_unix_ms, None);
- }
-
- /// [`Self::finish`], recording `outcome` on the root turn span when it is
- /// still open (a `TurnCompleted` already sealed it otherwise).
- ///
- /// Spans other than the turn that are still open lost their completion
- /// event. They are force-closed at the last moment they could have been
- /// running (their parent's end, else the last event seen) and marked
- /// `force_closed` with a `WARNING` level, so their duration is not read as
- /// a real latency.
- pub fn finish_with_outcome(&mut self, now_unix_ms: u64, outcome: Option<TurnOutcome>) {
- let end = self.last_activity_unix_ms.max(now_unix_ms);
- if let Some(index) = self.turn_span_index {
- if self.spans[index].end_unix_ms.is_none() {
- // Close the open iteration first so a tool under it can be
- // bounded by the iteration's end.
- self.close_current_iteration(self.last_activity_unix_ms.min(end));
- self.apply_turn_outcome(outcome.unwrap_or(TurnOutcome::Incomplete), end);
- }
- }
- // A span still open is bounded by its parent's end when the parent
- // already closed (a tool under a finished iteration ran no later than
- // the next model call), else by the last event seen.
- let open: Vec<usize> = (0..self.spans.len())
- .filter(|&idx| self.spans[idx].end_unix_ms.is_none())
- .collect();
- let fallback_end = self.last_activity_unix_ms.min(end);
- for idx in open {
- self.force_close(idx, fallback_end);
- }
- self.current_iteration_span_id = None;
- self.current_iteration_index = None;
- self.open_tools.clear();
- self.subagents.clear();
- self.finished_subagents.clear();
- }
-
- /// Record how the turn ended on the root span and seal it at
- /// `now_unix_ms`. A no-op without a turn span.
- ///
- /// * completed → `Ok`;
- /// * failed / timed out / incomplete → `Error` with an `error.message`
- /// (Langfuse statusMessage). The raw failure text can quote user data,
- /// so it is attached only with content capture on; otherwise a fixed,
- /// content-free message is used;
- /// * cancelled → status left unset, `observation.level = WARNING`;
- /// * stopped (breaker / wind-down / iteration cap) → status left unset,
- /// `observation.level = WARNING` plus the content-free stop attributes
- /// ([`Self::insert_stop_attrs`]).
- pub(crate) fn apply_turn_outcome(&mut self, outcome: TurnOutcome, now_unix_ms: u64) {
- let Some(index) = self.turn_span_index else {
- return;
- };
- let capture = self.ctx.capture_content;
- let gated = |text: &str, generic: &str| -> serde_json::Value {
- if capture && !text.trim().is_empty() {
- serde_json::Value::String(truncate_chars(text, MAX_ERROR_MESSAGE_CHARS))
- } else {
- json_str(generic)
- }
- };
- let mut extra = BTreeMap::new();
- let (status, label) = match &outcome {
- TurnOutcome::Completed => (SpanStatus::Ok, "completed"),
- TurnOutcome::Failed { message } => {
- extra.insert("error.message".to_string(), gated(message, "Turn failed"));
- (SpanStatus::Error, "failed")
- }
- TurnOutcome::TimedOut { message } => {
- extra.insert(
- "error.message".to_string(),
- gated(message, "Turn timed out"),
- );
- (SpanStatus::Error, "timed_out")
- }
- TurnOutcome::Incomplete => {
- extra.insert(
- "error.message".to_string(),
- json_str("Turn ended without completing"),
- );
- (SpanStatus::Error, "incomplete")
- }
- TurnOutcome::Cancelled { reason } => {
- extra.insert(LEVEL_ATTR.to_string(), json_str("WARNING"));
- extra.insert(
- "observation.status_message".to_string(),
- gated(reason.as_deref().unwrap_or(""), "Turn cancelled"),
- );
- (SpanStatus::Unset, "cancelled")
- }
- TurnOutcome::Stopped { stop } => {
- Self::insert_stop_attrs(stop, &mut extra);
- log::debug!(
- "[agent-tracing] turn stopped early trace_id={} {}",
- self.ctx.session_id,
- stop.status_message()
- );
- (SpanStatus::Unset, "stopped")
- }
- };
- if status == SpanStatus::Error {
- extra.insert("error".to_string(), serde_json::Value::Bool(true));
- }
- extra.insert("turn.outcome".to_string(), json_str(label));
- log::debug!(
- "[agent-tracing] turn outcome trace_id={} outcome={label}",
- self.ctx.session_id
- );
- self.close_span(index, now_unix_ms, status, extra);
- }
-
- /// Mark a span (turn or subagent) as stopped early: `WARNING` level, the
- /// content-free `stopped: …` summary as its status message, and the
- /// `turn.stop_*` attributes. The summary is also written as
- /// `error.message`, which is what the OTLP converter exports as the
- /// Langfuse statusMessage; it is safe ungated because it holds only the
- /// stop kind, a failure class and a tool name.
- pub(super) fn insert_stop_attrs(
- stop: &tinyagents_harness::turn_stop::TurnStop,
- extra: &mut BTreeMap<String, serde_json::Value>,
- ) {
- let message = stop.status_message();
- extra.insert(LEVEL_ATTR.to_string(), json_str("WARNING"));
- extra.insert("observation.status_message".to_string(), json_str(&message));
- extra.insert("error.message".to_string(), json_str(&message));
- extra.insert("turn.outcome".to_string(), json_str("stopped"));
- extra.insert("turn.stop_kind".to_string(), json_str(stop.kind.as_str()));
- if let Some(class) = &stop.failure_class {
- extra.insert("turn.stop_class".to_string(), json_str(class));
- }
- if let Some(operation) = &stop.operation {
- extra.insert("turn.stop_operation".to_string(), json_str(operation));
- }
- }
-
- /// Move a completed/failed subagent to `finished_subagents`, closing its
- /// open iteration with `status`. Its still-open tool spans stay open so a
- /// late completion can close them precisely. Returns the subagent span's
- /// index, or `None` for an unknown (or already finished) task.
- pub(super) fn retire_subagent(
- &mut self,
- task_id: &str,
- now_unix_ms: u64,
- status: SpanStatus,
- ) -> Option<usize> {
- let mut state = self.subagents.remove(task_id)?;
- if let Some(id) = state.current_iteration_span_id.take() {
- if let Some(idx) = self.span_index_by_id(&id) {
- self.close_span(idx, now_unix_ms, status, BTreeMap::new());
- }
- }
- if !state.open_tools.is_empty() {
- log::debug!(
- "[agent-tracing] subagent task_id={task_id} finished with {} tool span(s) still \
- open; awaiting late completions",
- state.open_tools.len()
- );
- }
- let span_index = state.span_index;
- self.finished_subagents.insert(task_id.to_string(), state);
- Some(span_index)
- }
-
- /// Close one span that never got its completion event.
- fn force_close(&mut self, idx: usize, fallback_end: u64) {
- let (kind, start, parent_end) = {
- let span = &self.spans[idx];
- let parent_end = span
- .parent_span_id
- .as_deref()
- .and_then(|id| self.span_index_by_id(id))
- .and_then(|parent| self.spans[parent].end_unix_ms);
- (span.kind, span.start_unix_ms, parent_end)
- };
- let end = parent_end
- .filter(|end| *end >= start)
- .unwrap_or(fallback_end);
- let mut extra = BTreeMap::new();
- if matches!(kind, SpanKind::Tool | SpanKind::Subagent) {
- extra.insert(FORCE_CLOSED_ATTR.to_string(), serde_json::Value::Bool(true));
- extra.insert(LEVEL_ATTR.to_string(), json_str("WARNING"));
- log::debug!(
- "[agent-tracing] force-closed span name={} start={start} end={end} \
- (completion event never arrived)",
- self.spans[idx].name
- );
- }
- self.close_span(idx, end, SpanStatus::Unset, extra);
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/generation.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/generation.rs
deleted file mode 100644
index 964d15d3fd..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/generation.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-//! Pure helpers that shape a generation span's attributes: the model label,
-//! usage normalization across provider routes, cost provenance, and the
-//! unstreamed-call guard for time to first token.
-
-/// A call whose first delta landed this close to its completion was not
-/// streamed: non-streaming providers (the OpenAI Responses path used by the
-/// ChatGPT/Codex sign-in) emit the whole reply as one synthetic delta right
-/// before completing, so its "first token" is just the completion instant.
-pub(super) const UNSTREAMED_DELTA_WINDOW_MS: u64 = 100;
-
-/// Model name to report for a call: the event's own, else the scope's last
-/// known model, else `"unknown"`. A child bridge or a journal completion whose
-/// `ModelStarted` was lost reports an empty name, which surfaced in Langfuse
-/// as `llm.` / model `.`.
-pub(super) fn resolve_model(model: &str, fallback: Option<&str>) -> String {
- let model = model.trim();
- if !model.is_empty() {
- return model.to_string();
- }
- fallback
- .map(str::trim)
- .filter(|m| !m.is_empty())
- .unwrap_or("unknown")
- .to_string()
-}
-
-/// Langfuse-facing model label: `{provider}.{model}`, or the bare model when
-/// the provider is unknown (the journal projection has none), instead of a
-/// dangling `.{model}`.
-pub(super) fn model_label(provider_id: &str, model: &str) -> String {
- let provider = provider_id.trim();
- if provider.is_empty() {
- model.to_string()
- } else {
- format!("{provider}.{model}")
- }
-}
-
-/// One call's token usage in a single convention, whatever the route reported.
-///
-/// Routes disagree on what `input_tokens` means: most (OpenAI-compatible,
-/// OpenRouter, the Anthropic API adapter) report the whole prompt, cache
-/// reads and writes included; the Claude Code route forwards Anthropic's raw
-/// `input_tokens`, which counts only the uncached remainder. Exported as-is,
-/// the second made Langfuse's `total` smaller than the cache read alone. A
-/// prompt-inclusive count can never be below `cache_read + cache_creation`,
-/// so a count that is must be the uncached remainder and is widened here.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) struct NormalizedUsage {
- /// Whole prompt: uncached + cache read + cache creation.
- pub(super) input_total: u64,
- /// Prompt tokens neither read from nor written to a cache.
- pub(super) input_uncached: u64,
- pub(super) cache_read: u64,
- pub(super) cache_creation: u64,
- pub(super) output: u64,
- /// `input_total + output`.
- pub(super) total: u64,
- /// Whether the route reported the uncached remainder and it was widened.
- pub(super) widened: bool,
-}
-
-pub(super) fn normalize_usage(
- input_tokens: u64,
- output_tokens: u64,
- cache_read: u64,
- cache_creation: u64,
-) -> NormalizedUsage {
- let cached = cache_read.saturating_add(cache_creation);
- let widened = input_tokens < cached;
- let input_total = if widened {
- input_tokens.saturating_add(cached)
- } else {
- input_tokens
- };
- NormalizedUsage {
- input_total,
- input_uncached: input_total.saturating_sub(cached),
- cache_read,
- cache_creation,
- output: output_tokens,
- total: input_total.saturating_add(output_tokens),
- widened,
- }
-}
-
-/// Where a generation's cost figure came from.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) enum CostSource {
- /// A provider charge or an estimate from a known price.
- Priced,
- /// The call has neither a reported charge nor a known estimate.
- Unpriced,
-}
-
-impl CostSource {
- pub(super) fn as_str(self) -> &'static str {
- match self {
- Self::Priced => "priced",
- Self::Unpriced => "unpriced",
- }
- }
-}
-
-/// Preserve the optional cost supplied by the call's accounting layer.
-/// Unknown costs stay absent; a reported zero remains a known price.
-pub(super) fn effective_cost(reported_usd: Option<f64>) -> (Option<f64>, CostSource) {
- let source = if reported_usd.is_some() {
- CostSource::Priced
- } else {
- CostSource::Unpriced
- };
- (reported_usd, source)
-}
-
-/// Whether a call with these delta stamps was really streamed. A call is
-/// treated as unstreamed when its first delta arrived within
-/// [`UNSTREAMED_DELTA_WINDOW_MS`] of completion but well after it started:
-/// that delta carries the completion instant, not a first token.
-pub(super) fn is_unstreamed(first_delta_ms: u64, start_ms: u64, end_ms: u64) -> bool {
- end_ms.saturating_sub(first_delta_ms) <= UNSTREAMED_DELTA_WINDOW_MS
- && first_delta_ms.saturating_sub(start_ms) > UNSTREAMED_DELTA_WINDOW_MS
-}
-
-#[cfg(test)]
-#[path = "generation_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/generation_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/generation_tests.rs
deleted file mode 100644
index e789578730..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/generation_tests.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use super::*;
-
-#[test]
-fn model_label_skips_an_empty_provider() {
- assert_eq!(model_label("managed", "chat-v1"), "managed.chat-v1");
- assert_eq!(
- model_label("", "openrouter/deepseek/deepseek-v4-flash"),
- "openrouter/deepseek/deepseek-v4-flash"
- );
- assert_eq!(model_label(" ", "m"), "m");
-}
-
-#[test]
-fn resolve_model_falls_back_for_an_empty_name() {
- assert_eq!(resolve_model("gpt-4o", Some("other")), "gpt-4o");
- assert_eq!(resolve_model("", Some("deepseek")), "deepseek");
- assert_eq!(resolve_model(" ", None), "unknown");
-}
-
-#[test]
-fn prompt_inclusive_usage_is_kept() {
- // deepseek/OpenRouter route: input already counts the cache read.
- let usage = normalize_usage(66_732, 484, 64_768, 0);
- assert!(!usage.widened);
- assert_eq!(usage.input_total, 66_732);
- assert_eq!(usage.input_uncached, 1_964);
- assert_eq!(usage.total, 67_216);
-}
-
-#[test]
-fn uncached_only_input_is_widened() {
- // Claude Code route: Anthropic's raw `input_tokens` is the uncached
- // remainder, so the reported total used to be smaller than the cache read.
- let usage = normalize_usage(12, 300, 40_000, 2_000);
- assert!(usage.widened);
- assert_eq!(usage.input_total, 42_012);
- assert_eq!(usage.input_uncached, 12);
- assert_eq!(usage.cache_read, 40_000);
- assert_eq!(usage.cache_creation, 2_000);
- assert_eq!(usage.total, 42_312);
- assert_eq!(
- usage.total,
- usage.input_uncached + usage.cache_read + usage.cache_creation + usage.output
- );
-}
-
-#[test]
-fn unknown_cost_is_absent_and_reported_zero_is_preserved() {
- assert_eq!(effective_cost(None), (None, CostSource::Unpriced));
- assert_eq!(effective_cost(Some(0.5)), (Some(0.5), CostSource::Priced));
- assert_eq!(effective_cost(Some(0.0)), (Some(0.0), CostSource::Priced));
-}
-
-#[test]
-fn single_delta_at_completion_is_unstreamed() {
- assert!(is_unstreamed(4_990, 1_000, 5_000));
- assert!(!is_unstreamed(1_300, 1_000, 5_000));
- // A fast call is not second-guessed.
- assert!(!is_unstreamed(1_050, 1_000, 1_060));
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/mod.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/mod.rs
deleted file mode 100644
index e18a78d859..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/mod.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-//! The [`SpanCollector`] state machine: data shape and construction
-//! ([`state`]), turn/parent bootstrap and content capture ([`span_lifecycle`]),
-//! generation-span folding ([`model_call`], attribute shaping in
-//! [`generation`]), the public event fold ([`events`]), and sealing the tree
-//! with the turn's outcome ([`finish`]).
-
-mod events;
-mod finish;
-mod generation;
-mod model_call;
-mod span_lifecycle;
-mod state;
-
-pub use state::{SpanCollector, TurnOutcome};
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/model_call.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/model_call.rs
deleted file mode 100644
index 803cc4cc05..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/model_call.rs
+++ /dev/null
@@ -1,371 +0,0 @@
-//! Folding a per-call `ModelCallCompleted` event into a generation span plus
-//! its rollups onto the enclosing subagent/turn span.
-
-use std::collections::BTreeMap;
-
-use tinyagents_harness::observability::trace_export::serialize::{
- capture_model_content, json_f64, json_str, json_u32, json_u64,
-};
-use tinyagents_harness::observability::trace_export::{SpanKind, SpanStatus};
-
-use super::generation;
-use super::state::SpanCollector;
-
-impl SpanCollector {
- /// Fold a per-call `ModelCallCompleted` into the tree:
- ///
- /// 1. emit a closed [`SpanKind::Generation`] span (name `llm.<model>`)
- /// parented under the current iteration — or, for a child call
- /// (`subagent_task_id` set), under the owning subagent's current
- /// iteration — carrying exact per-call model/usage/cost plus provenance
- /// (`gen_ai.provider`) and the pricing basis the local estimator uses;
- /// 2. record the captured request messages (incl. the system prompt) and
- /// completion as the generation's input/output, gated on
- /// `capture_content` and truncated to [`tinyagents_harness::observability::trace_export::serialize::MAX_MODEL_CONTENT_CHARS`];
- /// 3. accumulate reasoning / cache-creation tokens onto the root turn
- /// span, which `TurnCostUpdated` (cumulative rollup) does not carry —
- /// and, for child calls, roll model + usage onto the subagent span so
- /// a delegation (e.g. the Context Scout) surfaces its model natively.
- ///
- /// The Langfuse-facing model label is `{provider_id}.{model}` (e.g.
- /// `managed.hint:chat`, `openai.gpt-4o`), or the bare model when the
- /// provider is unknown; an empty model falls back to the scope's last
- /// known model (see [`generation::resolve_model`]).
- ///
- /// Start is the call's own request start when known
- /// ([`SpanCollector::set_next_call_start`]), else the later of the
- /// enclosing iteration's start and the previous call's end in that
- /// iteration ([`super::state::CallClock`]); end is the observation time of
- /// the usage record. Usage is normalized across routes
- /// ([`generation::normalize_usage`]) and an unpriced model's placeholder
- /// cost is dropped ([`generation::effective_cost`]).
- #[allow(clippy::too_many_arguments)]
- pub(in crate::core::observability::progress_tracing) fn record_model_call(
- &mut self,
- model: &str,
- provider_id: &str,
- subagent_task_id: Option<&str>,
- input: Option<&serde_json::Value>,
- output: Option<&serde_json::Value>,
- iteration: u32,
- input_tokens: u64,
- output_tokens: u64,
- cached_input_tokens: u64,
- cache_creation_tokens: u64,
- reasoning_tokens: u64,
- cost_usd: Option<f64>,
- now_unix_ms: u64,
- ) {
- // Resolve the parent + start basis: a child call nests under its
- // subagent's current iteration (else its last one, for a call reported
- // after the subagent finished; else the subagent span itself); a parent
- // call nests under the turn's current iteration (else root).
- let subagent_state = subagent_task_id.and_then(|id| self.subagent_state(id));
- let (parent, start_basis_index, clock, fallback_model) = match subagent_state {
- Some(state) => {
- let iteration_id = state
- .current_iteration_span_id
- .clone()
- .or_else(|| state.last_iteration_span_id.clone());
- let clock = state.call_clock;
- let fallback = state.last_raw_model.clone();
- match iteration_id {
- Some(id) => {
- let idx = self.span_index_by_id(&id);
- (id, idx, clock, fallback)
- }
- None => (
- self.spans[state.span_index].span_id.clone(),
- Some(state.span_index),
- clock,
- fallback,
- ),
- }
- }
- None => {
- if let Some(id) = subagent_task_id {
- log::debug!(
- "[agent-tracing] model call for unknown subagent task_id={id}; \
- nesting under the parent turn"
- );
- }
- let parent = self.active_parent_id(now_unix_ms);
- (
- parent,
- self.current_iteration_index,
- self.call_clock,
- self.last_raw_model.clone(),
- )
- }
- };
- let basis_start = start_basis_index
- .and_then(|idx| self.spans.get(idx))
- .map(|span| span.start_unix_ms)
- .unwrap_or(now_unix_ms);
- let start_unix_ms = clock
- .explicit_start_unix_ms
- .unwrap_or_else(|| basis_start.max(clock.last_call_end_unix_ms.unwrap_or(0)))
- .min(now_unix_ms);
- let model = generation::resolve_model(model, fallback_model.as_deref());
- // Consume this call's first-delta stamps + start bookkeeping so the
- // next call on the same iteration (a retry, a repair) starts clean and
- // after this one.
- let next_clock = super::state::CallClock {
- last_call_end_unix_ms: Some(now_unix_ms),
- explicit_start_unix_ms: None,
- };
- let first_deltas = match subagent_task_id {
- Some(id) => match self.subagent_state_mut(id) {
- Some(state) => {
- state.call_clock = next_clock;
- state.last_raw_model = Some(model.clone());
- std::mem::take(&mut state.first_deltas)
- }
- None => Default::default(),
- },
- None => {
- self.call_clock = next_clock;
- self.last_raw_model = Some(model.clone());
- std::mem::take(&mut self.first_deltas)
- }
- };
-
- let labeled_model = generation::model_label(provider_id, &model);
- // Remember which model this scope is on so the tool spans it requests
- // name it (correlating tool errors to models without a join). The
- // label already drops an empty provider (the journal replay has none).
- match subagent_task_id {
- Some(id) => {
- if let Some(state) = self.subagent_state_mut(id) {
- state.last_model = Some(labeled_model.clone());
- }
- }
- None => self.last_model = Some(labeled_model.clone()),
- }
- let pricing = crate::agent::cost::lookup_pricing(&model);
- let usage = generation::normalize_usage(
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cache_creation_tokens,
- );
- let (cost_usd, cost_source) = generation::effective_cost(cost_usd);
- if usage.widened {
- log::debug!(
- "[agent-tracing] widened uncached input to prompt-inclusive model={labeled_model} \
- reported_in={input_tokens} cache_read={cached_input_tokens} \
- cache_write={cache_creation_tokens} input_total={}",
- usage.input_total
- );
- }
-
- let mut attrs = BTreeMap::new();
- attrs.insert("gen_ai.request.model".to_string(), json_str(&labeled_model));
- attrs.insert("gen_ai.provider".to_string(), json_str(provider_id));
- attrs.insert("agent.iteration".to_string(), json_u32(iteration));
- // Prompt-inclusive input (uncached + cache read + cache write), so the
- // exporter's `input - cache_read` and `input + output` hold on every
- // route.
- attrs.insert(
- "gen_ai.usage.input_tokens".to_string(),
- json_u64(usage.input_total),
- );
- attrs.insert(
- "gen_ai.usage.output_tokens".to_string(),
- json_u64(output_tokens),
- );
- // Every usage dimension always flows (even 0) so usageDetails stay
- // complete and comparable across routes.
- attrs.insert(
- "gen_ai.usage.cached_input_tokens".to_string(),
- json_u64(usage.cache_read),
- );
- attrs.insert(
- "gen_ai.usage.cache_creation_tokens".to_string(),
- json_u64(usage.cache_creation),
- );
- attrs.insert(
- "gen_ai.usage.uncached_input_tokens".to_string(),
- json_u64(usage.input_uncached),
- );
- attrs.insert(
- "gen_ai.usage.total_tokens".to_string(),
- json_u64(usage.total),
- );
- if reasoning_tokens > 0 {
- attrs.insert(
- "gen_ai.usage.reasoning_tokens".to_string(),
- json_u64(reasoning_tokens),
- );
- }
- // An unpriced call carries no cost attribute rather than a $0 one.
- if let Some(cost_usd) = cost_usd {
- attrs.insert("gen_ai.usage.cost_usd".to_string(), json_f64(cost_usd));
- }
- attrs.insert(
- "gen_ai.cost.source".to_string(),
- json_str(cost_source.as_str()),
- );
- // Time to first token. Deltas only arrive on streamed calls, so a
- // unary call carries neither attribute; nor does a non-streaming call
- // whose single synthetic delta lands at completion (its "first token"
- // would be the whole latency).
- let unstreamed = first_deltas
- .any_unix_ms
- .is_some_and(|first| generation::is_unstreamed(first, start_unix_ms, now_unix_ms));
- if unstreamed {
- attrs.insert(
- "gen_ai.response.streamed".to_string(),
- serde_json::Value::Bool(false),
- );
- } else {
- if let Some(first) = first_deltas.any_unix_ms {
- let first = first.max(start_unix_ms);
- attrs.insert(
- "gen_ai.response.first_token_unix_ms".to_string(),
- json_u64(first),
- );
- attrs.insert(
- "gen_ai.response.time_to_first_token_ms".to_string(),
- json_u64(first - start_unix_ms),
- );
- }
- if let Some(first_text) = first_deltas.text_unix_ms {
- attrs.insert(
- "gen_ai.response.time_to_first_text_ms".to_string(),
- json_u64(first_text.max(start_unix_ms) - start_unix_ms),
- );
- }
- }
- // Pricing basis so Langfuse cost figures are auditable against the
- // client-side estimator (USD per million tokens). Absent for an
- // unpriced model rather than showing the placeholder rate.
- if let Some(pricing) = pricing {
- attrs.insert(
- "gen_ai.pricing.input_per_mtok_usd".to_string(),
- json_f64(pricing.input_per_token.unwrap_or(0.0) * 1_000_000.0),
- );
- attrs.insert(
- "gen_ai.pricing.cached_input_per_mtok_usd".to_string(),
- json_f64(pricing.cache_read_input_per_token.unwrap_or(0.0) * 1_000_000.0),
- );
- attrs.insert(
- "gen_ai.pricing.output_per_mtok_usd".to_string(),
- json_f64(pricing.output_per_token.unwrap_or(0.0) * 1_000_000.0),
- );
- }
-
- log::debug!(
- "[agent-tracing] generation span model={labeled_model} \
- iteration={iteration} child={} in={input_tokens} out={output_tokens} \
- cached={cached_input_tokens} ttft_ms={:?} ttft_text_ms={:?} \
- cost_usd={cost_usd:?} cost_source={} unstreamed={unstreamed} \
- input_captured={} output_captured={}",
- subagent_task_id.is_some(),
- first_deltas
- .any_unix_ms
- .map(|first| first.saturating_sub(start_unix_ms)),
- first_deltas
- .text_unix_ms
- .map(|first| first.saturating_sub(start_unix_ms)),
- cost_source.as_str(),
- input.is_some(),
- output.is_some(),
- );
- let (_, index) = self.open_span(
- SpanKind::Generation,
- format!("llm.{model}"),
- Some(parent),
- start_unix_ms,
- attrs,
- );
- // Captured request messages (incl. system prompt) + completion become
- // the generation's input/output — only while content capture is on,
- // truncated so one huge context window can't bloat the trace batch.
- if self.ctx.capture_content {
- if let Some(span) = self.spans.get_mut(index) {
- if let Some(value) = input {
- span.input = Some(capture_model_content(value));
- }
- if let Some(value) = output {
- span.output = Some(capture_model_content(value));
- }
- }
- }
- self.close_span(index, now_unix_ms, SpanStatus::Ok, BTreeMap::new());
-
- // Child call: roll model + usage + cost onto the owning subagent span
- // so the delegation row (e.g. `subagent.Context Scout`) natively shows
- // which model served it and what it cost.
- if let Some(state_index) = subagent_task_id
- .and_then(|id| self.subagent_state(id))
- .map(|state| state.span_index)
- {
- if let Some(span) = self.spans.get_mut(state_index) {
- span.attributes
- .insert("gen_ai.request.model".to_string(), json_str(&labeled_model));
- span.attributes
- .insert("gen_ai.provider".to_string(), json_str(provider_id));
- for (key, add) in [
- ("gen_ai.usage.input_tokens", usage.input_total),
- ("gen_ai.usage.output_tokens", output_tokens),
- ("gen_ai.usage.cached_input_tokens", usage.cache_read),
- ("gen_ai.usage.cache_creation_tokens", usage.cache_creation),
- ] {
- let prior = span
- .attributes
- .get(key)
- .and_then(serde_json::Value::as_u64)
- .unwrap_or(0);
- span.attributes
- .insert(key.to_string(), json_u64(prior.saturating_add(add)));
- }
- if let Some(cost_usd) = cost_usd {
- let prior_cost = span
- .attributes
- .get("gen_ai.usage.cost_usd")
- .and_then(serde_json::Value::as_f64)
- .unwrap_or(0.0);
- span.attributes.insert(
- "gen_ai.usage.cost_usd".to_string(),
- json_f64(prior_cost + cost_usd),
- );
- }
- }
- return;
- }
-
- // Root rollup for the usage dimensions the cumulative TurnCostUpdated
- // event does not carry (reasoning / cache-creation), plus provenance
- // and the provider-labeled model (TurnCostUpdated only knows the raw
- // model handle and can fire before the first per-call event).
- let root = match self.turn_span_index {
- Some(idx) => idx,
- None => {
- self.ensure_turn_span(now_unix_ms);
- self.turn_span_index.expect("turn span just created")
- }
- };
- if let Some(span) = self.spans.get_mut(root) {
- span.attributes
- .insert("gen_ai.provider".to_string(), json_str(provider_id));
- span.attributes
- .insert("gen_ai.request.model".to_string(), json_str(&labeled_model));
- for (key, add) in [
- ("gen_ai.usage.reasoning_tokens", reasoning_tokens),
- ("gen_ai.usage.cache_creation_tokens", cache_creation_tokens),
- ] {
- if add == 0 && !span.attributes.contains_key(key) {
- continue;
- }
- let prior = span
- .attributes
- .get(key)
- .and_then(serde_json::Value::as_u64)
- .unwrap_or(0);
- span.attributes
- .insert(key.to_string(), json_u64(prior.saturating_add(add)));
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/span_lifecycle.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/span_lifecycle.rs
deleted file mode 100644
index 5d864f8dc5..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/span_lifecycle.rs
+++ /dev/null
@@ -1,158 +0,0 @@
-//! Turn-span bootstrap, parent resolution, and tool content capture — the
-//! shared span-lifecycle helpers used while folding progress events.
-
-use std::collections::BTreeMap;
-
-use tinyagents_harness::observability::trace_export::serialize::{
- truncate_capture_text, MAX_TOOL_CONTENT_CHARS,
-};
-use tinyagents_harness::observability::trace_export::SpanKind;
-
-use super::state::SpanCollector;
-
-impl SpanCollector {
- /// Lazily open the root turn span so a stream that begins mid-flight
- /// (or never sends `TurnStarted`) still produces a correlated tree.
- pub(in crate::core::observability::progress_tracing) fn ensure_turn_span(
- &mut self,
- start_unix_ms: u64,
- ) -> String {
- if let Some(id) = &self.turn_span_id {
- return id.clone();
- }
- let mut attrs = BTreeMap::new();
- attrs.insert(
- "session.id".to_string(),
- serde_json::Value::String(self.ctx.session_id.clone()),
- );
- if let Some(user) = &self.ctx.user_id {
- attrs.insert(
- "user.id".to_string(),
- serde_json::Value::String(user.clone()),
- );
- }
- if let Some(client) = &self.ctx.client_id {
- attrs.insert(
- "client.id".to_string(),
- serde_json::Value::String(client.clone()),
- );
- }
- if let Some(agent) = &self.ctx.agent_id {
- attrs.insert(
- "agent.id".to_string(),
- serde_json::Value::String(agent.clone()),
- );
- }
- if let Some(source) = &self.ctx.channel_source {
- attrs.insert(
- "channel.source".to_string(),
- serde_json::Value::String(source.clone()),
- );
- }
- attrs.insert(
- "run.type".to_string(),
- serde_json::Value::String(self.ctx.run_type.as_str().to_string()),
- );
- // Every trace must end up with a Langfuse sessionId: prefer the
- // explicit grouping key (thread/conversation id), else fall back to
- // the trace id itself so the trace is never left session-less.
- let group = self
- .ctx
- .session_group
- .clone()
- .unwrap_or_else(|| self.ctx.session_id.clone());
- attrs.insert("thread.id".to_string(), serde_json::Value::String(group));
- // Trace/root-span name carries agent attribution when known.
- let name = match &self.ctx.agent_id {
- Some(agent) => format!("agent.turn:{agent}"),
- None => "agent.turn".to_string(),
- };
- log::debug!(
- "[agent-tracing] opening turn span trace_id={} name={} user_attributed={} client_attributed={} source={:?}",
- self.ctx.session_id,
- name,
- self.ctx.user_id.is_some(),
- self.ctx.client_id.is_some(),
- self.ctx.channel_source,
- );
- let (id, index) = self.open_span(SpanKind::Turn, name, None, start_unix_ms, attrs);
- self.turn_span_id = Some(id.clone());
- self.turn_span_index = Some(index);
- id
- }
-
- /// The parent any iteration / tool / subagent span should hang off:
- /// the current iteration if one is open, else the turn root.
- pub(in crate::core::observability::progress_tracing) fn active_parent_id(
- &mut self,
- now_unix_ms: u64,
- ) -> String {
- if let Some(id) = &self.current_iteration_span_id {
- return id.clone();
- }
- self.ensure_turn_span(now_unix_ms)
- }
-
- /// Record a tool call's arguments as the span's `input`, truncated to
- /// [`MAX_TOOL_CONTENT_CHARS`]. A no-op unless content capture is on
- /// (`observability.agent_tracing.capture_content`) — when off, tool I/O
- /// never even reaches the in-memory span. `Null` arguments are skipped.
- pub(in crate::core::observability::progress_tracing) fn capture_tool_arguments(
- &mut self,
- index: usize,
- arguments: &serde_json::Value,
- ) {
- if !self.ctx.capture_content || arguments.is_null() {
- return;
- }
- let serialized = arguments.to_string();
- let chars = serialized.chars().count();
- if let Some(span) = self.spans.get_mut(index) {
- span.input = Some(serde_json::Value::String(truncate_capture_text(
- &serialized,
- )));
- log::trace!(
- "[agent-tracing] captured tool input span={} chars={chars} truncated={}",
- span.name,
- chars > MAX_TOOL_CONTENT_CHARS,
- );
- }
- }
-
- /// Record a tool call's result as the span's `output`, truncated to
- /// [`MAX_TOOL_CONTENT_CHARS`]. Same capture gate as
- /// [`Self::capture_tool_arguments`]. Empty output is skipped.
- pub(in crate::core::observability::progress_tracing) fn capture_tool_output(
- &mut self,
- index: usize,
- output: &str,
- ) {
- if !self.ctx.capture_content || output.is_empty() {
- return;
- }
- let chars = output.chars().count();
- if let Some(span) = self.spans.get_mut(index) {
- span.output = Some(serde_json::Value::String(truncate_capture_text(output)));
- log::trace!(
- "[agent-tracing] captured tool output span={} chars={chars} truncated={}",
- span.name,
- chars > MAX_TOOL_CONTENT_CHARS,
- );
- }
- }
-
- pub(in crate::core::observability::progress_tracing) fn close_current_iteration(
- &mut self,
- end_unix_ms: u64,
- ) {
- if let Some(index) = self.current_iteration_index.take() {
- self.close_span(
- index,
- end_unix_ms,
- tinyagents_harness::observability::trace_export::SpanStatus::Ok,
- BTreeMap::new(),
- );
- }
- self.current_iteration_span_id = None;
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/state.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/state.rs
deleted file mode 100644
index daf135eb63..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/state.rs
+++ /dev/null
@@ -1,306 +0,0 @@
-//! [`SpanCollector`] data shape, construction, and small accessors.
-
-use std::collections::BTreeMap;
-
-use tinyagents_harness::observability::trace_export::{SpanStatus, TraceContext, TraceSpan};
-
-/// When the in-flight model call streamed its first delta, for
-/// time-to-first-token. Reset when a new iteration (model call) starts and
-/// consumed when that call's usage is recorded.
-#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
-pub(super) struct FirstDeltas {
- /// First delta of any kind: reasoning, text or tool-call arguments.
- pub(super) any_unix_ms: Option<u64>,
- /// First visible text delta.
- pub(super) text_unix_ms: Option<u64>,
- /// Most recent delta of any kind. A call whose every delta lands in the
- /// last instant before completion was not streamed (see
- /// [`super::model_call`]'s unstreamed-call guard).
- pub(super) last_unix_ms: Option<u64>,
-}
-
-impl FirstDeltas {
- /// Stamp `now_unix_ms` as the first delta (and first text, when `is_text`)
- /// unless an earlier one is already recorded.
- pub(super) fn observe(&mut self, now_unix_ms: u64, is_text: bool) {
- self.any_unix_ms.get_or_insert(now_unix_ms);
- self.last_unix_ms = Some(now_unix_ms);
- if is_text {
- self.text_unix_ms.get_or_insert(now_unix_ms);
- }
- }
-}
-
-/// Per-subagent bookkeeping so child iterations / tool calls nest correctly.
-#[derive(Debug)]
-pub(super) struct SubagentState {
- /// Index of the subagent span in [`SpanCollector::spans`].
- pub(super) span_index: usize,
- /// Currently-open child iteration span id, if any.
- pub(super) current_iteration_span_id: Option<String>,
- /// Open child tool spans keyed by `call_id` → span index.
- pub(super) open_tools: BTreeMap<String, usize>,
- /// First streamed delta of the child's in-flight model call.
- pub(super) first_deltas: FirstDeltas,
- /// Langfuse-facing label (`{provider}.{model}`) of the child's latest
- /// model call, stamped on the child tool spans it requests.
- pub(super) last_model: Option<String>,
- /// Raw model of the child's most recent call, the fallback name for a call
- /// that arrives without one.
- pub(super) last_raw_model: Option<String>,
- /// Last child iteration span opened, kept after it closes so a model call
- /// or tool event reported after the subagent finished still nests under it.
- pub(super) last_iteration_span_id: Option<String>,
- /// Start-time bookkeeping for the child's model calls (see [`CallClock`]).
- pub(super) call_clock: CallClock,
-}
-
-impl SubagentState {
- pub(super) fn new(span_index: usize) -> Self {
- Self {
- span_index,
- current_iteration_span_id: None,
- open_tools: BTreeMap::new(),
- first_deltas: FirstDeltas::default(),
- last_model: None,
- last_raw_model: None,
- last_iteration_span_id: None,
- call_clock: CallClock::default(),
- }
- }
-}
-
-/// Per-scope bookkeeping for a model call's start time.
-///
-/// The progress stream carries no per-call request start: a generation used
-/// to start at its enclosing iteration's start, so several calls folded into
-/// one iteration (retries, or a child's calls whose iteration events were
-/// lost) all shared that instant and each one's latency covered every call
-/// before it. A call cannot have started before the previous call in the same
-/// iteration ended, so that end is the tighter bound; an explicit start
-/// (the journal's `ModelCompleted.started_at_ms`) beats both.
-#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
-pub(super) struct CallClock {
- /// End of the previous generation in the current iteration.
- pub(super) last_call_end_unix_ms: Option<u64>,
- /// Explicit request start for the next call, set by a source that knows
- /// it ([`SpanCollector::set_next_call_start`]).
- pub(super) explicit_start_unix_ms: Option<u64>,
-}
-
-/// How a turn ended, for the root span's status.
-///
-/// `AgentProgress` has no aborted/failed turn variant, so a host that knows
-/// the outcome passes it to [`SpanCollector::finish_with_outcome`]; a turn
-/// span still open at [`SpanCollector::finish`] (no `TurnCompleted` arrived)
-/// is sealed as [`TurnOutcome::Incomplete`].
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum TurnOutcome {
- /// The turn produced its reply.
- Completed,
- /// The turn failed with an error.
- Failed { message: String },
- /// A deadline or per-call timeout ended the turn.
- TimedOut { message: String },
- /// The user (or the host) cancelled the turn.
- Cancelled { reason: Option<String> },
- /// The stream closed before the turn reported an outcome.
- Incomplete,
- /// The harness stopped the turn early (failure breaker, deadline
- /// wind-down, iteration cap) and it reached the completion path anyway.
- Stopped {
- stop: tinyagents_harness::turn_stop::TurnStop,
- },
-}
-
-/// Pure state machine that folds an [`crate::progress::AgentProgress`]
-/// stream into spans.
-///
-/// Call [`record`](Self::record) for each event (with a millisecond
-/// timestamp), then [`finish`](Self::finish) once the stream closes to seal
-/// any still-open spans. [`spans`](Self::spans) returns the accumulated tree.
-#[derive(Debug)]
-pub struct SpanCollector {
- pub(super) ctx: TraceContext,
- pub(super) spans: Vec<TraceSpan>,
- pub(super) next_span_seq: u64,
- /// Per-collector (per-turn) random prefix for minted span ids. Langfuse
- /// dedupes observations by id **globally**, so a bare per-turn sequence
- /// (`0000…0001`) collides across turns and silently binds later turns'
- /// observations to whichever trace first claimed the id. Prefixing with a
- /// fresh nonce makes every span id globally unique.
- pub(super) id_prefix: String,
-
- pub(super) turn_span_id: Option<String>,
- pub(super) turn_span_index: Option<usize>,
- pub(super) current_iteration_span_id: Option<String>,
- pub(super) current_iteration_index: Option<usize>,
-
- /// Open parent-turn tool spans keyed by `call_id` → span index.
- pub(super) open_tools: BTreeMap<String, usize>,
- /// Live subagents keyed by `task_id`.
- pub(super) subagents: BTreeMap<String, SubagentState>,
- /// First streamed delta of the parent turn's in-flight model call.
- pub(super) first_deltas: FirstDeltas,
- /// Langfuse-facing label (`{provider}.{model}`) of the parent turn's latest
- /// model call. Tool calls run after the model call that requested them
- /// completes, so this names the model behind every tool span opened next.
- pub(super) last_model: Option<String>,
- /// Raw model of the parent turn's most recent call, the fallback name for
- /// a call that arrives without one.
- pub(super) last_raw_model: Option<String>,
- /// Start-time bookkeeping for the parent turn's model calls.
- pub(super) call_clock: CallClock,
- /// Subagents that already reported completion/failure, kept so their late
- /// events (tool completions, model calls) still resolve to their spans
- /// instead of being dropped or misparented under the parent iteration.
- pub(super) finished_subagents: BTreeMap<String, SubagentState>,
- /// Latest event timestamp seen; the end of a span force-closed at
- /// [`SpanCollector::finish`] when nothing tighter is known.
- pub(super) last_activity_unix_ms: u64,
- /// Whether the turn span's input is already set. The first `TurnContent`
- /// input is the originating user message; later ones (the commit path's
- /// last user-role message can be tool results or a harness nudge) must
- /// not overwrite it.
- pub(super) turn_input_recorded: bool,
-}
-
-impl SpanCollector {
- pub fn new(ctx: TraceContext) -> Self {
- Self {
- ctx,
- spans: Vec::new(),
- next_span_seq: 0,
- id_prefix: uuid::Uuid::new_v4().simple().to_string(),
- turn_span_id: None,
- turn_span_index: None,
- current_iteration_span_id: None,
- current_iteration_index: None,
- open_tools: BTreeMap::new(),
- subagents: BTreeMap::new(),
- first_deltas: FirstDeltas::default(),
- last_model: None,
- last_raw_model: None,
- call_clock: CallClock::default(),
- finished_subagents: BTreeMap::new(),
- last_activity_unix_ms: 0,
- turn_input_recorded: false,
- }
- }
-
- /// Opt into attaching content to spans (prompt/reply, generation
- /// request/completion, tool + subagent I/O). Wire this to
- /// `observability.agent_tracing.capture_content`. Equivalent to setting
- /// [`TraceContext::with_capture_content`] before construction — there is a
- /// single storage-level gate (`ctx.capture_content`), so content dropped
- /// here can never reach any exporter.
- pub fn with_content_capture(mut self, capture_content: bool) -> Self {
- self.ctx.capture_content = capture_content;
- self
- }
-
- /// All spans recorded so far (finished and in-flight).
- pub fn spans(&self) -> &[TraceSpan] {
- &self.spans
- }
-
- /// Record that the next model call in `subagent_task_id`'s scope (`None`
- /// = the parent turn) was dispatched at `start_unix_ms`. Consumed by that
- /// call's generation span. Used by the journal projection, whose
- /// `ModelCompleted` carries the real request start.
- pub(crate) fn set_next_call_start(
- &mut self,
- subagent_task_id: Option<&str>,
- start_unix_ms: u64,
- ) {
- let clock = match subagent_task_id {
- None => Some(&mut self.call_clock),
- Some(id) => self
- .subagents
- .get_mut(id)
- .or_else(|| self.finished_subagents.get_mut(id))
- .map(|state| &mut state.call_clock),
- };
- if let Some(clock) = clock {
- clock.explicit_start_unix_ms = Some(start_unix_ms);
- }
- }
-
- /// Live or finished subagent state for `task_id`.
- pub(super) fn subagent_state(&self, task_id: &str) -> Option<&SubagentState> {
- self.subagents
- .get(task_id)
- .or_else(|| self.finished_subagents.get(task_id))
- }
-
- /// Mutable live or finished subagent state for `task_id`.
- pub(super) fn subagent_state_mut(&mut self, task_id: &str) -> Option<&mut SubagentState> {
- match self.subagents.get_mut(task_id) {
- Some(state) => Some(state),
- None => self.finished_subagents.get_mut(task_id),
- }
- }
-
- /// Index of the span with `span_id`, if any.
- pub(super) fn span_index_by_id(&self, span_id: &str) -> Option<usize> {
- self.spans.iter().position(|sp| sp.span_id == span_id)
- }
-
- /// Consume the collector and return its spans.
- #[cfg(test)]
- pub fn into_spans(self) -> Vec<TraceSpan> {
- self.spans
- }
-
- /// OTel-style 16-hex span id derived from a monotonic sequence. Stable
- /// and deterministic within a run, which keeps the tests reproducible.
- pub(super) fn mint_span_id(&mut self) -> String {
- self.next_span_seq += 1;
- // Nonce prefix keeps the id globally unique across turns (Langfuse
- // dedupes observations by id project-wide).
- format!("{}-{:016x}", self.id_prefix, self.next_span_seq)
- }
-
- pub(super) fn open_span(
- &mut self,
- kind: tinyagents_harness::observability::trace_export::SpanKind,
- name: impl Into<String>,
- parent_span_id: Option<String>,
- start_unix_ms: u64,
- attributes: BTreeMap<String, serde_json::Value>,
- ) -> (String, usize) {
- let span_id = self.mint_span_id();
- let index = self.spans.len();
- self.spans.push(TraceSpan {
- trace_id: self.ctx.session_id.clone(),
- span_id: span_id.clone(),
- parent_span_id,
- name: name.into(),
- kind,
- start_unix_ms,
- end_unix_ms: None,
- status: SpanStatus::Unset,
- attributes,
- input: None,
- output: None,
- });
- (span_id, index)
- }
-
- /// Seal a span: set its end timestamp + status and merge in any extra
- /// attributes. A no-op if `index` is out of range (defensive).
- pub(super) fn close_span(
- &mut self,
- index: usize,
- end_unix_ms: u64,
- status: SpanStatus,
- extra: BTreeMap<String, serde_json::Value>,
- ) {
- if let Some(span) = self.spans.get_mut(index) {
- // Don't let a late event drag end before start.
- span.end_unix_ms = Some(end_unix_ms.max(span.start_unix_ms));
- span.status = status;
- span.attributes.extend(extra);
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
deleted file mode 100644
index d1131007c8..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
+++ /dev/null
@@ -1,726 +0,0 @@
-//! Journal-backed span projection (C4 slice S2).
-//!
-//! Reconstructs a run's [`AgentProgress`] stream from the durable
-//! [`AgentObservation`] journal (the crate `AgentEvent` record) and folds it
-//! through the existing [`SpanCollector`], so trace spans no longer require the
-//! *live* in-run `AgentProgress` side-observer
-//! (`web_chat/progress_bridge.rs`). A UI/supervisor can attach
-//! after a run, read the journal, and rebuild identical spans.
-//!
-//! This is deliberately built on `SpanCollector` (not a re-derivation) so span
-//! *shape* parity holds by construction for every `AgentProgress` the journal
-//! can produce. The one-way mapping here mirrors `OpenhumanEventBridge`
-//! (`tinyagents/observability.rs`) but is **pure** — it depends only on the
-//! journalled event, made possible by the crate carrying tool outcome
-//! (`duration_ms`/`output_bytes`/`error`) on `ToolCompleted` (tinyagents#18).
-//!
-//! Known parity gaps:
-//! - **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.
-//! - **No sub-agent spans are projected at all** (openhuman#6419). The four
-//! `AgentEvent::SubAgent*` arms below are dead in production: a survey of 900
-//! real run journals found **zero** sub-agent events of any kind, and every
-//! journalled run is its own root (`root_run_id == run_id` in all 588
-//! `run_started` records sampled, and no `root_run_id` spans more than one
-//! run file), so a child run is neither recorded in its parent's journal nor
-//! reachable from it. A replayed delegating turn therefore loses the whole
-//! sub-agent subtree — the delegate's turn span, its iterations, and its tool
-//! and model spans — which is the bulk of the span-count divergence the
-//! `[agent-tracing][journal-shadow]` parity check reports. This is a gap in
-//! what the crate journals, not in the projection: the arms are kept so the
-//! projection is correct the moment the events exist.
-//!
-//! An earlier revision of this list said sub-agent spans "carry
-//! lifecycle/timing and child tool/model structure but empty delegated
-//! prompt/final output", i.e. that only their *content* was thin. That was
-//! wrong in kind and stopped readers looking: there are no such spans to
-//! carry anything.
-//! - `AgentProgress::SubagentAwaitingUser` has no journal source either (the
-//! crate emits no matching lifecycle event). Moot while the gap above stands,
-//! and listed separately because it survives it: even once sub-agent
-//! lifecycle events are journalled, a span parked on a user prompt would lose
-//! that attribute on replay.
-//!
-//! Everything else **that the crate journals** 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;
-
-use super::SpanCollector;
-use crate::progress::AgentProgress;
-use replay::{json_content_text, turn_outcome_for_failure, user_message_text, Replay};
-
-#[path = "journal_replay.rs"]
-mod replay;
-use tinyagents_harness::observability::trace_export::{TraceContext, TraceSpan};
-use tinytools::status::classify;
-
-/// Mutable state threaded across a single run's observations while replaying.
-#[derive(Default)]
-struct ReplayState {
- /// 1-based iteration index, bumped once per `ModelStarted` — the same
- /// attribution the live `IterationCursor` provides.
- iteration: u32,
- /// Max iterations configured for the turn (carried onto iteration spans).
- max_iterations: u32,
- /// `call_id → model name`, learned from `ModelStarted` so the matching
- /// `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,
- /// Model of the most recent `ModelStarted` in any scope: the name for a
- /// `ModelCompleted` whose own `ModelStarted` is missing from the journal.
- last_model_any: String,
- /// Collector steps produced by the current observation that must run
- /// before its returned progress (see [`Replay`]). Drained per observation.
- pre: Vec<Replay>,
- /// `call_id → requested tool name` for calls the crate answered as an
- /// unknown tool. The crate's own `ToolStarted`/`ToolCompleted` pair for the
- /// same call id follows; this lets it carry the "unavailable" label and the
- /// `NotFound` class. Mirrors the live bridge's `unknown_calls`.
- unknown_calls: std::collections::HashMap<String, String>,
-}
-
-#[derive(Clone)]
-struct ReplaySubagent {
- agent_id: String,
- task_id: String,
- depth: usize,
- iteration: u32,
- started_ts_ms: u64,
-}
-
-impl ReplayState {
- fn active_subagent(&self) -> Option<&ReplaySubagent> {
- self.subagents.last()
- }
-
- fn active_subagent_mut(&mut self) -> Option<&mut ReplaySubagent> {
- self.subagents.last_mut()
- }
-
- /// The "unavailable" label/detail for a call recorded as an unknown tool.
- fn unknown_tool_display(&self, call_id: &str) -> (Option<String>, Option<String>) {
- match self.unknown_calls.get(call_id) {
- Some(requested) => (
- Some(format!(
- "{} (unavailable)",
- tinytools::humanize_tool_name(requested)
- )),
- Some("tool not available".to_string()),
- ),
- None => (None, None),
- }
- }
-}
-
-/// Maps one journalled observation to zero or more [`AgentProgress`] events,
-/// updating `state`. Non-span-bearing events (deltas, budget/cache/steering
-/// diagnostics) map to nothing — `SpanCollector` ignores them anyway.
-fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> Vec<AgentProgress> {
- let event = &obs.event;
- match event {
- AgentEvent::RunStarted { .. } => {
- if state.active_subagent().is_some() {
- Vec::new()
- } else {
- vec![AgentProgress::TurnStarted]
- }
- }
-
- AgentEvent::ModelStarted { call_id, model } => {
- let iteration = match state.active_subagent_mut() {
- Some(scope) => {
- scope.iteration += 1;
- scope.iteration
- }
- 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
- }
- };
- state
- .models
- .insert(call_id.as_str().to_string(), model.clone());
- state.last_model_any = model.clone();
- match state.active_subagent() {
- Some(scope) => vec![AgentProgress::SubagentIterationStarted {
- agent_id: scope.agent_id.clone(),
- task_id: scope.task_id.clone(),
- iteration,
- max_iterations: state.max_iterations,
- extended_policy: false,
- }],
- None => vec![AgentProgress::IterationStarted {
- iteration,
- max_iterations: state.max_iterations,
- }],
- }
- }
-
- // The harness answers `tool_search` without running a tool, so the
- // journal carries no `ToolStarted`/`ToolCompleted` for it. Replay the
- // same synthetic pair the live bridge emits, so a replayed trace has
- // the `tool.tool_search` span with the ranking facts.
- AgentEvent::ToolSearched {
- call_id,
- query,
- matched,
- ranker,
- top_confidence,
- fallback,
- shadow_matched,
- latency_ms,
- } => {
- let tool_name = tinyagents_harness::tool::discover::TOOL_SEARCH_NAME.to_string();
- let arguments = serde_json::json!({ "query": query });
- let output = serde_json::json!({
- "matched": matched,
- "ranker": ranker,
- "top_confidence": top_confidence,
- "fallback": fallback,
- "shadow_matched": shadow_matched,
- "latency_ms": latency_ms,
- })
- .to_string();
- let output_chars = output.chars().count();
- 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: tool_name.clone(),
- arguments: arguments.clone(),
- iteration: scope.iteration,
- display_label: Some("Searching tools".to_string()),
- display_detail: None,
- },
- AgentProgress::SubagentToolCallCompleted {
- agent_id: scope.agent_id.clone(),
- task_id: scope.task_id.clone(),
- call_id: call_id.as_str().to_string(),
- tool_name,
- success: true,
- output_chars,
- output,
- arguments: Some(arguments),
- elapsed_ms: *latency_ms,
- iteration: scope.iteration,
- failure: None,
- display_label: Some("Searching tools".to_string()),
- display_detail: None,
- structured: None,
- },
- ],
- None => vec![
- AgentProgress::ToolCallStarted {
- call_id: call_id.as_str().to_string(),
- tool_name: tool_name.clone(),
- arguments: arguments.clone(),
- iteration: state.iteration,
- display_label: Some("Searching tools".to_string()),
- display_detail: None,
- },
- AgentProgress::ToolCallCompleted {
- call_id: call_id.as_str().to_string(),
- tool_name,
- success: true,
- output_chars,
- output,
- arguments: Some(arguments),
- elapsed_ms: *latency_ms,
- iteration: state.iteration,
- failure: None,
- display_label: Some("Searching tools".to_string()),
- display_detail: None,
- structured: None,
- },
- ],
- }
- }
-
- AgentEvent::ToolStarted {
- call_id, tool_name, ..
- } => {
- let (display_label, display_detail) = state.unknown_tool_display(call_id.as_str());
- 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: tool_name.clone(),
- arguments: serde_json::Value::Null,
- iteration: scope.iteration,
- display_label,
- display_detail,
- }],
- None => vec![AgentProgress::ToolCallStarted {
- call_id: call_id.as_str().to_string(),
- tool_name: tool_name.clone(),
- // The journal does not carry the model's raw argument JSON in
- // payload-free mode; the tool span still renders from name + id.
- arguments: serde_json::Value::Null,
- iteration: state.iteration,
- display_label,
- display_detail,
- }],
- }
- }
-
- AgentEvent::ToolCompleted {
- call_id,
- tool_name,
- input,
- output,
- duration_ms,
- output_bytes,
- error,
- ..
- } => {
- // Outcome now rides the event (tinyagents#18): success, duration and
- // size are self-describing, and the same `classify` the live path
- // uses reproduces the identical `ClassifiedFailure` from the
- // journalled error string. `output` is present only when the run
- // captured payloads (full-content journals).
- let (display_label, display_detail) = state.unknown_tool_display(call_id.as_str());
- let was_unknown = state.unknown_calls.remove(call_id.as_str()).is_some();
- // An unknown tool is `NotFound` from the typed event (#6277),
- // whatever the text classifier made of the echoed names.
- let failure = if was_unknown {
- Some(tinytools::status::describe(
- tinytools::status::ToolFailureClass::NotFound,
- ))
- } else {
- error.as_ref().map(|text| classify(text, false))
- };
- let success = error.is_none() && !was_unknown;
- let output_text = match output {
- Some(serde_json::Value::String(text)) => text.clone(),
- Some(value) => value.to_string(),
- None => String::new(),
- };
- match state.active_subagent() {
- Some(scope) => vec![AgentProgress::SubagentToolCallCompleted {
- agent_id: scope.agent_id.clone(),
- task_id: scope.task_id.clone(),
- call_id: call_id.as_str().to_string(),
- tool_name: tool_name.clone(),
- success,
- output_chars: output_bytes.unwrap_or(0) as usize,
- output: output_text,
- arguments: input.clone(),
- elapsed_ms: duration_ms.unwrap_or(0),
- iteration: scope.iteration,
- failure,
- // The journal has no live tool registry to recompute a
- // real label/detail from, and no `ToolResult.metadata` to
- // replay structured payloads from.
- display_label,
- display_detail,
- structured: None,
- }],
- None => vec![AgentProgress::ToolCallCompleted {
- call_id: call_id.as_str().to_string(),
- tool_name: tool_name.clone(),
- success,
- output_chars: output_bytes.unwrap_or(0) as usize,
- output: output_text,
- arguments: input.clone(),
- elapsed_ms: duration_ms.unwrap_or(0),
- iteration: state.iteration,
- failure,
- display_label,
- display_detail,
- structured: None,
- }],
- }
- }
-
- AgentEvent::UnknownToolCall {
- call_id,
- requested_name,
- recovery,
- ..
- } => {
- // #4118 synthesised a failed Started/Completed pair here because
- // the crate emitted none for an unknown tool. Since TOOL-11 the
- // crate answers it through `recover_tool_call`, which journals an
- // ordinary `ToolStarted`/`ToolCompleted` pair under the same call
- // id, so a synthesised pair doubled the tool span. Record the call
- // so that pair carries the "unavailable" label and the `NotFound`
- // class instead. Mirrors `observability/event_projection.rs`. A
- // `rewrite:` recovery runs its target under its own name.
- if !recovery.starts_with("rewrite:") {
- state
- .unknown_calls
- .insert(call_id.as_str().to_string(), requested_name.clone());
- }
- Vec::new()
- }
-
- AgentEvent::ModelCompleted {
- call_id,
- started_at_ms,
- usage,
- input,
- output,
- } => {
- let usage = usage.unwrap_or_default();
- let start = started_at_ms.unwrap_or(obs.ts_ms).min(obs.ts_ms);
- let model = match state.models.remove(call_id.as_str()) {
- Some(model) => model,
- None => {
- // The harness emits one `ModelStarted` per `ModelCompleted`,
- // so a completion with no start means the journal lost the
- // start. Without one the call joined the previous iteration,
- // shared its start instant and carried no model name (seen
- // in production as several `llm.` generations starting in
- // the same millisecond). Open the iteration it belongs to at
- // the call's own start instead.
- log::debug!(
- "[agent-tracing][journal] ModelCompleted without ModelStarted \
- call_id={} run_id={}; synthesizing its iteration",
- call_id.as_str(),
- obs.run_id.as_str()
- );
- let iteration = match state.active_subagent_mut() {
- Some(scope) => {
- scope.iteration += 1;
- scope.iteration
- }
- None => {
- state.iteration += 1;
- state.iteration
- }
- };
- let started = match state.active_subagent() {
- Some(scope) => AgentProgress::SubagentIterationStarted {
- agent_id: scope.agent_id.clone(),
- task_id: scope.task_id.clone(),
- iteration,
- max_iterations: state.max_iterations,
- extended_policy: false,
- },
- None => AgentProgress::IterationStarted {
- iteration,
- max_iterations: state.max_iterations,
- },
- };
- state.pre.push(Replay::At(started, start));
- state.last_model_any.clone()
- }
- };
- let scope = state.active_subagent().cloned();
- state.pre.push(Replay::CallStart(
- scope.as_ref().map(|s| s.task_id.clone()),
- start,
- ));
- let iteration = scope
- .as_ref()
- .map(|s| s.iteration)
- .unwrap_or(state.iteration);
- let mut progress = vec![AgentProgress::ModelCallCompleted {
- model,
- // Provider qualification/cost are filled at export time from the
- // persisted cost store, not the journal (§2a).
- provider_id: String::new(),
- subagent_task_id: scope.as_ref().map(|s| s.task_id.clone()),
- input: input.clone(),
- output: output.clone(),
- iteration,
- input_tokens: usage.input_tokens,
- output_tokens: usage.output_tokens,
- cached_input_tokens: usage.cache_read_tokens,
- // 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: None,
- }];
- if scope.is_none() {
- // The request's last user message is the user's own words on
- // the turn's first call; the collector keeps only the first
- // turn input, so later calls (whose last user message is tool
- // results or a harness nudge) do not replace it.
- let turn_input = input.as_ref().map(user_message_text);
- let turn_output = output.as_ref().map(json_content_text);
- if turn_input.is_some() || turn_output.is_some() {
- progress.push(AgentProgress::TurnContent {
- input: turn_input,
- output: turn_output,
- });
- }
- }
- progress
- }
-
- AgentEvent::UsageRecorded { usage } => {
- // The cost footer is a top-level surface: the live bridge suppresses
- // the per-child roll-up (`observability/event_bridge.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.
- // An unpriced model adds nothing rather than a placeholder rate.
- state.cost_usd += crate::agent::cost::estimate_call_cost_usd(
- &state.model,
- &crate::inference::provider::BilledUsage::from_counts(
- usage.input_tokens,
- usage.output_tokens,
- )
- .with_cached_input_tokens(usage.cache_read_tokens)
- .with_cache_creation_tokens(usage.cache_creation_tokens)
- .with_reasoning_tokens(usage.reasoning_tokens),
- )
- .unwrap_or(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);
- state.subagents.push(ReplaySubagent {
- agent_id: name.clone(),
- task_id: task_id.clone(),
- depth: *depth,
- iteration: 0,
- started_ts_ms: obs.ts_ms,
- });
- vec![AgentProgress::SubagentSpawned {
- agent_id: name.clone(),
- task_id,
- mode: "typed".to_string(),
- dedicated_thread: false,
- prompt_chars: 0,
- worker_thread_id: None,
- display_name: Some(name.clone()),
- prompt: String::new(),
- parent_call_id: None,
- }]
- }
-
- AgentEvent::SubAgentCompleted { name, depth } => {
- let pos = state
- .subagents
- .iter()
- .rposition(|scope| scope.agent_id == *name && scope.depth == *depth);
- let Some(scope) = pos.map(|index| state.subagents.remove(index)) else {
- return Vec::new();
- };
- vec![AgentProgress::SubagentCompleted {
- agent_id: scope.agent_id,
- task_id: scope.task_id,
- elapsed_ms: obs.ts_ms.saturating_sub(scope.started_ts_ms),
- iterations: scope.iteration,
- output_chars: 0,
- output: String::new(),
- // Projection rebuild, not an originating emit; it has no
- // outcome to read usage from. See the field's docs.
- usage: None,
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- stop: None,
- }]
- }
-
- AgentEvent::RunCompleted { .. } => {
- if state.active_subagent().is_some() {
- Vec::new()
- } else {
- vec![AgentProgress::TurnCompleted {
- iterations: state.iteration,
- stop: None,
- }]
- }
- }
-
- AgentEvent::RunFailed { error, outcome, .. } => {
- let Some(scope) = state.subagents.pop() else {
- // The top-level run failed: the turn span reports it instead of
- // closing as an unremarkable, status-less span.
- state
- .pre
- .push(Replay::Outcome(turn_outcome_for_failure(error, outcome.as_ref())));
- return Vec::new();
- };
- vec![AgentProgress::SubagentFailed {
- agent_id: scope.agent_id,
- task_id: scope.task_id,
- error: error.clone(),
- }]
- }
-
- // 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::ToolsAdvertised { .. }
- | AgentEvent::DeferredToolCall { .. }
- | 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(),
- // `AgentEvent` is `#[non_exhaustive]`: a variant added upstream after
- // this projection was written carries no span this replay models.
- _ => Vec::new(),
- }
-}
-
-/// Projects a run's journalled `observations` into trace spans by replaying
-/// them into [`AgentProgress`] and folding through a fresh [`SpanCollector`],
-/// stamped with each observation's journal timestamp (`ts_ms`).
-pub(crate) fn spans_from_observations(
- ctx: TraceContext,
- max_iterations: u32,
- observations: &[AgentObservation],
-) -> Vec<TraceSpan> {
- let capture_content = ctx.capture_content;
- let mut collector = SpanCollector::new(ctx).with_content_capture(capture_content);
- let mut state = ReplayState {
- max_iterations,
- ..ReplayState::default()
- };
- let mut last_ts = 0;
- for obs in observations {
- last_ts = obs.ts_ms;
- let progress = observation_to_progress(obs, &mut state);
- for step in std::mem::take(&mut state.pre) {
- match step {
- Replay::At(event, at) => collector.record(&event, at),
- Replay::CallStart(task_id, at) => {
- collector.set_next_call_start(task_id.as_deref(), at)
- }
- Replay::Outcome(outcome) => collector.apply_turn_outcome(outcome, obs.ts_ms),
- }
- }
- for progress in progress {
- collector.record(&progress, obs.ts_ms);
- }
- }
- collector.finish(last_ts);
- collector.spans().to_vec()
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_projection_accuracy_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_projection_accuracy_tests.rs
deleted file mode 100644
index 9f5b667496..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection_accuracy_tests.rs
+++ /dev/null
@@ -1,231 +0,0 @@
-//! Journal-projection regressions from production trace d1f1562f (a
-//! `workflow_builder` sub-agent trace): completions whose `ModelStarted` was
-//! lost, tools that never completed, unlabeled models, failed runs, and the
-//! turn input.
-
-use super::*;
-use tinyagents_harness::terminal::{TerminalOutcome, TerminalReason};
-
-fn run_started() -> AgentObservation {
- obs(
- 0,
- 1_000,
- AgentEvent::RunStarted {
- run_id: RunId::new("run-1"),
- thread_id: None,
- },
- )
-}
-
-fn model_started(offset: u64, ts: u64, call: &str) -> AgentObservation {
- obs(
- offset,
- ts,
- AgentEvent::ModelStarted {
- call_id: CallId::new(call),
- model: "openrouter/deepseek/deepseek-v4-flash".to_string(),
- },
- )
-}
-
-fn model_completed(
- offset: u64,
- ts: u64,
- call: &str,
- started: u64,
- input: Option<serde_json::Value>,
-) -> AgentObservation {
- obs(
- offset,
- ts,
- AgentEvent::ModelCompleted {
- call_id: CallId::new(call),
- started_at_ms: Some(started),
- usage: Some(Usage::new(100, 10)),
- input,
- output: None,
- },
- )
-}
-
-fn tool_started(offset: u64, ts: u64, call: &str, name: &str) -> AgentObservation {
- obs(
- offset,
- ts,
- AgentEvent::ToolStarted {
- parent_call_id: None,
- call_id: CallId::new(call),
- tool_name: name.to_string(),
- input: None,
- },
- )
-}
-
-fn run_completed(offset: u64, ts: u64) -> AgentObservation {
- obs(
- offset,
- ts,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- )
-}
-
-fn generations(spans: &[super::super::TraceSpan]) -> Vec<&super::super::TraceSpan> {
- spans
- .iter()
- .filter(|s| s.kind == SpanKind::Generation)
- .collect()
-}
-
-#[test]
-fn completion_without_model_started_gets_its_own_iteration_and_start() {
- let observations = vec![
- run_started(),
- model_started(1, 1_000, "m1"),
- model_completed(2, 3_000, "m1", 1_000, None),
- // `ModelStarted` for m2 / m3 lost from the journal.
- model_completed(3, 5_000, "m2", 3_100, None),
- model_completed(4, 9_000, "m3", 5_200, None),
- run_completed(5, 9_100),
- ];
- let spans = spans_from_observations(ctx(), 10, &observations);
- let gens = generations(&spans);
- let timing: Vec<(u64, Option<u64>)> = gens
- .iter()
- .map(|g| (g.start_unix_ms, g.end_unix_ms))
- .collect();
- assert_eq!(
- timing,
- vec![
- (1_000, Some(3_000)),
- (3_100, Some(5_000)),
- (5_200, Some(9_000))
- ],
- "each call starts at its own started_at_ms"
- );
- for g in &gens {
- assert_eq!(g.name, "llm.openrouter/deepseek/deepseek-v4-flash");
- assert_eq!(
- g.attributes["gen_ai.request.model"],
- serde_json::json!("openrouter/deepseek/deepseek-v4-flash"),
- "no empty provider prefix or empty model"
- );
- }
- let iterations = spans
- .iter()
- .filter(|s| s.kind == SpanKind::Iteration)
- .count();
- assert_eq!(
- iterations, 3,
- "a lost ModelStarted still yields its iteration"
- );
-}
-
-#[test]
-fn tool_that_never_completed_is_force_closed_at_its_iteration_end() {
- let observations = vec![
- run_started(),
- model_started(1, 1_000, "m1"),
- model_completed(2, 2_000, "m1", 1_000, None),
- tool_started(3, 2_010, "t1", "get_node_kind_contract"),
- // ToolCompleted for t1 lost; the next model call starts at 2_500.
- model_started(4, 2_500, "m2"),
- model_completed(5, 3_000, "m2", 2_500, None),
- run_completed(6, 400_000),
- ];
- let spans = spans_from_observations(ctx(), 10, &observations);
- let tool = spans
- .iter()
- .find(|s| s.name == "tool.get_node_kind_contract")
- .unwrap();
- assert_eq!(tool.end_unix_ms, Some(2_500));
- assert_eq!(tool.attributes["force_closed"], serde_json::json!(true));
- assert_eq!(
- tool.attributes["observation.level"],
- serde_json::json!("WARNING")
- );
-}
-
-#[test]
-fn top_level_run_failure_marks_the_turn_span() {
- let observations = vec![
- run_started(),
- model_started(1, 1_000, "m1"),
- obs(
- 2,
- 2_000,
- AgentEvent::RunFailed {
- run_id: RunId::new("run-1"),
- error: "provider unavailable".to_string(),
- outcome: None,
- },
- ),
- ];
- let spans = spans_from_observations(ctx(), 10, &observations);
- let turn = spans.iter().find(|s| s.kind == SpanKind::Turn).unwrap();
- assert_eq!(turn.status, SpanStatus::Error);
- assert_eq!(turn.attributes["turn.outcome"], serde_json::json!("failed"));
- assert_eq!(turn.end_unix_ms, Some(2_000));
-}
-
-#[test]
-fn cancelled_run_is_a_warning() {
- let observations = vec![
- run_started(),
- obs(
- 1,
- 2_000,
- AgentEvent::RunFailed {
- run_id: RunId::new("run-1"),
- error: "cancelled".to_string(),
- outcome: Some(TerminalOutcome::new(TerminalReason::Cancelled, "cancelled")),
- },
- ),
- ];
- let spans = spans_from_observations(ctx(), 10, &observations);
- let turn = spans.iter().find(|s| s.kind == SpanKind::Turn).unwrap();
- assert_eq!(turn.status, SpanStatus::Unset);
- assert_eq!(
- turn.attributes["turn.outcome"],
- serde_json::json!("cancelled")
- );
-}
-
-#[test]
-fn turn_input_is_the_user_message_not_the_last_call_input() {
- let observations = vec![
- run_started(),
- model_started(1, 1_000, "m1"),
- model_completed(
- 2,
- 2_000,
- "m1",
- 1_000,
- Some(serde_json::json!([
- {"system": {"content": [{"text": "You are OpenHuman."}]}},
- {"user": {"content": [{"text": "build a daily digest"}]}}
- ])),
- ),
- model_started(3, 2_100, "m2"),
- model_completed(
- 4,
- 3_000,
- "m2",
- 2_100,
- Some(serde_json::json!([
- {"user": {"content": [{"text": "build a daily digest"}]}},
- {"assistant": {"content": [{"text": "calling tools"}]}},
- {"user": {"content": [{"text": "[Tool results]\\n{}"}]}}
- ])),
- ),
- run_completed(5, 3_100),
- ];
- let spans = spans_from_observations(ctx().with_capture_content(true), 10, &observations);
- let turn = spans.iter().find(|s| s.kind == SpanKind::Turn).unwrap();
- assert_eq!(
- turn.input.as_ref().unwrap(),
- &serde_json::json!("build a daily digest")
- );
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_projection_cost_rollup_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_projection_cost_rollup_tests.rs
deleted file mode 100644
index 86ba9eeb36..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection_cost_rollup_tests.rs
+++ /dev/null
@@ -1,527 +0,0 @@
-//! Journal-projection tests for the turn cost roll-up, the recovered
-//! unknown-tool call, and the exhaustive no-op arms (openhuman#6148).
-
-use super::*;
-use tinyagents_harness::observability::trace_export::TraceSpan;
-
-/// 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"),
- outcome: None,
- },
- ));
- events
-}
-
-fn turn_span(spans: &[TraceSpan]) -> &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"),
- outcome: None,
- },
- ),
- ];
-
- 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)
- );
-}
-
-/// The answer the crate injects for an unknown tool (`unknown_tool_message`).
-const UNKNOWN_TOOL_ANSWER: &str =
- "unknown tool `send_fax` (arguments: {\"to\":\"1234\"}): no tool \
- with that name is available to you, and calling it again will fail the same way.";
-
-/// The crate's recovered pair for an unknown tool (TOOL-11 `recover_tool_call`):
-/// an ordinary `ToolStarted`/`ToolCompleted` under the same call id, after the
-/// typed `UnknownToolCall`.
-fn recovered_unknown_tool_pair(offset: u64, ts: u64) -> Vec<AgentObservation> {
- vec![
- obs(
- offset,
- ts,
- AgentEvent::ToolStarted {
- parent_call_id: None,
- call_id: CallId::new("t1"),
- tool_name: "send_fax".to_string(),
- input: None,
- },
- ),
- obs(
- offset + 1,
- ts + 1,
- AgentEvent::ToolCompleted {
- parent_call_id: None,
- call_id: CallId::new("t1"),
- tool_name: "send_fax".to_string(),
- started_at_ms: Some(ts),
- input: None,
- output: None,
- duration_ms: Some(0),
- output_bytes: Some(UNKNOWN_TOOL_ANSWER.len() as u64),
- error: Some(UNKNOWN_TOOL_ANSWER.to_string()),
- metadata: None,
- },
- ),
- ]
-}
-
-/// An unknown-tool call projects exactly one failed tool span. The projection
-/// used to synthesise a pair off `UnknownToolCall` while the crate journals its
-/// own recovered pair, so production Langfuse showed two ERROR observations per
-/// unknown-tool call (one with null output, one with the error text).
-#[test]
-fn unknown_tool_call_projects_exactly_one_failed_tool_span() {
- let mut 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: "tool_error".to_string(),
- },
- ),
- ];
- observations.extend(recovered_unknown_tool_pair(10, 1_021));
- observations.push(obs(
- 3,
- 1_030,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ));
-
- let spans = spans_from_observations(ctx().with_capture_content(true), 10, &observations);
- let tools: Vec<&TraceSpan> = spans.iter().filter(|s| s.kind == SpanKind::Tool).collect();
- assert_eq!(
- tools.len(),
- 1,
- "exactly one tool span per unknown-tool call"
- );
- let tool = tools[0];
- assert_eq!(tool.name, "tool.send_fax");
- assert_eq!(tool.attributes["tool.success"], serde_json::json!(false));
- assert_eq!(tool.status, SpanStatus::Error);
- assert_eq!(
- tool.attributes["error.message"],
- serde_json::json!(
- tinytools::status::describe(tinytools::status::ToolFailureClass::NotFound).cause_plain
- ),
- "the one span carries the NotFound cause"
- );
-}
-
-/// The child-scope half of the `UnknownToolCall` projection: a sub-agent that
-/// names an unavailable tool gets the same single failed tool span, nested
-/// under its subagent span rather than the root turn.
-#[test]
-fn unknown_tool_call_inside_a_subagent_projects_a_child_tool_span() {
- let mut 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: "tool_error".to_string(),
- },
- ),
- ];
- observations.extend(recovered_unknown_tool_pair(10, 1_031));
- observations.extend([
- obs(
- 4,
- 1_040,
- AgentEvent::SubAgentCompleted {
- name: "researcher".to_string(),
- depth: 1,
- },
- ),
- obs(
- 5,
- 1_050,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ),
- ]);
-
- 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!(
- spans.iter().filter(|s| s.kind == SpanKind::Tool).count(),
- 1,
- "exactly one child tool span per unknown-tool call"
- );
- assert_eq!(tool.name, "tool.send_fax");
- assert_eq!(tool.attributes["tool.success"], serde_json::json!(false));
- assert_eq!(tool.status, SpanStatus::Error);
- // Assert the exact chain, not merely that a parent exists: the tool hangs
- // off the child's *iteration* span (`SubagentToolCallStarted` prefers the
- // sub-agent's `current_iteration_span_id`), which in turn hangs off the
- // sub-agent span. A presence check would pass even if the tool attached to
- // an unrelated iteration.
- let child_iteration = spans
- .iter()
- .find(|s| s.kind == SpanKind::SubagentIteration)
- .expect("the child iteration span brackets the recovered call");
- assert_eq!(
- child_iteration.parent_span_id.as_deref(),
- Some(subagent.span_id.as_str()),
- "child iteration hangs off the subagent span"
- );
- assert_eq!(
- tool.parent_span_id.as_deref(),
- Some(child_iteration.span_id.as_str()),
- "the recovered tool span hangs off the child iteration"
- );
-}
-
-/// 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"
- );
- // Counts and kinds alone would still pass if a diagnostic event changed an
- // attribute, a name, a status or a parent link, so compare every stable
- // field. `trace_id`/`span_id` are generated per projection and are excluded;
- // the parent link is compared as an *index* into the span list, which pins
- // the tree shape without depending on generated ids.
- assert_eq!(span_shape(&projected), span_shape(&baseline));
-}
-
-/// Reduces spans to the fields that must be identical across two projections of
-/// the same run — everything but the generated `trace_id`/`span_id`, with the
-/// parent expressed positionally.
-fn span_shape(spans: &[TraceSpan]) -> Vec<String> {
- spans
- .iter()
- .map(|span| {
- let parent = span
- .parent_span_id
- .as_ref()
- .and_then(|id| spans.iter().position(|other| &other.span_id == id));
- format!(
- "{:?}|{}|{:?}|parent={parent:?}|start={}|end={:?}|attrs={:?}|in={:?}|out={:?}",
- span.kind,
- span.name,
- span.status,
- span.start_unix_ms,
- span.end_unix_ms,
- span.attributes,
- span.input,
- span.output,
- )
- })
- .collect()
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_projection_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_projection_tests.rs
deleted file mode 100644
index 48ec1ecc05..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection_tests.rs
+++ /dev/null
@@ -1,568 +0,0 @@
-use super::journal_projection::spans_from_observations;
-use super::{SpanKind, SpanStatus, TraceContext};
-use tinyagents_harness::events::AgentEvent;
-use tinyagents_harness::ids::{CallId, EventId, RunId};
-use tinyagents_harness::observability::AgentObservation;
-use tinyinference_llm::usage::Usage;
-
-/// Wraps an event as a journalled observation stamped at `ts`.
-fn obs(offset: u64, ts: u64, event: AgentEvent) -> AgentObservation {
- AgentObservation {
- event_id: EventId::new(format!("run-1-evt-{offset}")),
- run_id: RunId::new("run-1"),
- parent_run_id: None,
- root_run_id: RunId::new("run-1"),
- offset,
- ts_ms: ts,
- event,
- }
-}
-
-fn tool_completed(call: &str, name: &str, error: Option<&str>) -> AgentEvent {
- AgentEvent::ToolCompleted {
- parent_call_id: None,
- call_id: CallId::new(call),
- tool_name: name.to_string(),
- started_at_ms: Some(1_020),
- input: None,
- output: None,
- duration_ms: Some(30),
- output_bytes: Some(12),
- error: error.map(str::to_string),
- metadata: None,
- }
-}
-
-fn single_turn(tool_error: Option<&str>) -> Vec<AgentObservation> {
- 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::ToolStarted {
- parent_call_id: None,
- call_id: CallId::new("t1"),
- tool_name: "lookup".to_string(),
- input: None,
- },
- ),
- obs(3, 1_050, tool_completed("t1", "lookup", tool_error)),
- obs(
- 4,
- 1_060,
- AgentEvent::ModelCompleted {
- call_id: CallId::new("c1"),
- started_at_ms: Some(1_010),
- usage: Some(Usage::new(100, 20)),
- input: None,
- output: None,
- },
- ),
- obs(
- 5,
- 1_070,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ),
- ]
-}
-
-fn subagent_turn() -> Vec<AgentObservation> {
- 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("scout-model"),
- model: "gpt-4".to_string(),
- },
- ),
- obs(
- 3,
- 1_090,
- AgentEvent::ToolStarted {
- parent_call_id: None,
- call_id: CallId::new("scout-tool"),
- tool_name: "read_file".to_string(),
- input: None,
- },
- ),
- obs(4, 1_060, tool_completed("scout-tool", "read_file", None)),
- obs(
- 5,
- 1_070,
- AgentEvent::ModelCompleted {
- call_id: CallId::new("scout-model"),
- started_at_ms: Some(1_020),
- usage: Some(Usage::new(11, 7)),
- input: None,
- output: None,
- },
- ),
- obs(
- 6,
- 1_090,
- AgentEvent::SubAgentCompleted {
- name: "researcher".to_string(),
- depth: 1,
- },
- ),
- obs(
- 7,
- 1_100,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ),
- ]
-}
-
-fn ctx() -> TraceContext {
- TraceContext::new("session-1", Some("user-1".into()))
-}
-
-/// A stable projection snapshot for the collector migration. Keep this fixture
-/// at the export boundary so the native owner collector can be compared with
-/// the current host projection before that projection is removed.
-#[test]
-fn legacy_export_snapshot_for_root_and_child_with_reused_call_ids() {
- use tinyagents_harness::observability::trace_export::serialize::{
- SpanEnvelope, spans_to_ndjson,
- };
-
- let mut 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("same-call"),
- model: "gpt-4".to_string(),
- },
- ),
- obs(
- 2,
- 1_020,
- AgentEvent::ToolStarted {
- parent_call_id: None,
- call_id: CallId::new("tool-1"),
- tool_name: "lookup".to_string(),
- input: Some(serde_json::json!({"query":"CONTENT_SENTINEL_INPUT"})),
- },
- ),
- obs(
- 3,
- 1_030,
- AgentEvent::SubAgentStarted {
- name: "researcher".to_string(),
- depth: 1,
- },
- ),
- ];
- observations.push(AgentObservation {
- event_id: EventId::new("child-evt-0"),
- run_id: RunId::new("child-run"),
- parent_run_id: Some(RunId::new("run-1")),
- root_run_id: RunId::new("run-1"),
- offset: 0,
- ts_ms: 1_040,
- event: AgentEvent::RunStarted {
- run_id: RunId::new("child-run"),
- thread_id: None,
- },
- });
- observations.push(AgentObservation {
- event_id: EventId::new("child-evt-1"),
- run_id: RunId::new("child-run"),
- parent_run_id: Some(RunId::new("run-1")),
- root_run_id: RunId::new("run-1"),
- offset: 1,
- ts_ms: 1_050,
- event: AgentEvent::ModelStarted {
- call_id: CallId::new("same-call"),
- model: "gpt-4-mini".to_string(),
- },
- });
- observations.push(AgentObservation {
- event_id: EventId::new("child-evt-2"),
- run_id: RunId::new("child-run"),
- parent_run_id: Some(RunId::new("run-1")),
- root_run_id: RunId::new("run-1"),
- offset: 2,
- ts_ms: 1_060,
- event: AgentEvent::ModelCompleted {
- call_id: CallId::new("same-call"),
- started_at_ms: Some(1_050),
- usage: Some(Usage::new(7, 3)),
- input: None,
- output: None,
- },
- });
- observations.push(AgentObservation {
- event_id: EventId::new("child-evt-3"),
- run_id: RunId::new("child-run"),
- parent_run_id: Some(RunId::new("run-1")),
- root_run_id: RunId::new("run-1"),
- offset: 3,
- ts_ms: 1_070,
- event: AgentEvent::RunCompleted {
- run_id: RunId::new("child-run"),
- outcome: None,
- },
- });
- observations.push(obs(
- 4,
- 1_080,
- AgentEvent::SubAgentCompleted {
- name: "researcher".to_string(),
- depth: 1,
- },
- ));
- observations.push(obs(
- 5,
- 1_090,
- AgentEvent::ToolCompleted {
- parent_call_id: None,
- call_id: CallId::new("tool-1"),
- tool_name: "lookup".to_string(),
- started_at_ms: Some(1_020),
- input: Some(serde_json::json!({"query":"CONTENT_SENTINEL_INPUT"})),
- output: Some(serde_json::json!({"result":"CONTENT_SENTINEL_OUTPUT"})),
- duration_ms: Some(70),
- output_bytes: Some(33),
- error: None,
- metadata: None,
- },
- ));
- observations.push(obs(
- 6,
- 1_100,
- AgentEvent::ModelCompleted {
- call_id: CallId::new("same-call"),
- started_at_ms: Some(1_010),
- usage: Some(Usage::new(100, 20)),
- input: Some(serde_json::json!(["CONTENT_SENTINEL_PROMPT"])),
- output: Some(serde_json::json!(["CONTENT_SENTINEL_REPLY"])),
- },
- ));
- observations.push(obs(
- 7,
- 1_110,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ));
- let spans = spans_from_observations(ctx(), 10, &observations);
- let snapshot = spans_to_ndjson(SpanEnvelope::Otel, &spans);
- assert!(
- !snapshot.contains("CONTENT_SENTINEL"),
- "content-off export must not contain captured payloads"
- );
- let mut native = tinyagents_harness::observability::trace_export::collector::SpanCollector::new(ctx());
- for observation in &observations {
- native.record(observation);
- }
- native.finish(1_110);
- let native_spans = native.spans();
- let native_by_id: std::collections::HashMap<_, _> = native_spans
- .iter()
- .map(|span| (span.span_id.as_str(), span))
- .collect();
- let native_normalized: Vec<_> = native_spans
- .iter()
- .map(|span| {
- serde_json::json!({
- "name": span.name,
- "kind": format!("{:?}", span.kind),
- "parent": span.parent_span_id.as_deref().and_then(|id| native_by_id.get(id)).map(|parent| parent.name.as_str()),
- "start_unix_ms": span.start_unix_ms,
- "end_unix_ms": span.end_unix_ms,
- "status": format!("{:?}", span.status),
- "attributes": span.attributes,
- })
- })
- .collect();
- println!(
- "NATIVE:{}",
- serde_json::to_string_pretty(&native_normalized).unwrap()
- );
- let spans_by_id: std::collections::HashMap<_, _> = spans
- .iter()
- .map(|span| (span.span_id.as_str(), span))
- .collect();
- let normalized: Vec<_> = spans
- .iter()
- .map(|span| {
- serde_json::json!({
- "name": span.name,
- "kind": format!("{:?}", span.kind),
- "parent": span.parent_span_id.as_deref().and_then(|id| spans_by_id.get(id)).map(|parent| parent.name.as_str()),
- "start_unix_ms": span.start_unix_ms,
- "end_unix_ms": span.end_unix_ms,
- "status": format!("{:?}", span.status),
- "attributes": span.attributes,
- })
- })
- .collect();
- println!("NORMALIZED:{}", serde_json::to_string_pretty(&normalized).unwrap());
- let root = spans.iter().find(|span| span.parent_span_id.is_none()).unwrap();
- assert_eq!(root.start_unix_ms, 1_000);
- assert_eq!(root.end_unix_ms, Some(1_110));
- let generation_names: Vec<_> = spans
- .iter()
- .filter(|span| span.kind == SpanKind::Generation)
- .map(|span| span.name.as_str())
- .collect();
- assert_eq!(generation_names, ["llm.gpt-4", "llm.gpt-4-mini"]);
- assert_eq!(
- spans.iter().find(|span| span.name == "llm.gpt-4").unwrap().attributes["gen_ai.usage.input_tokens"],
- serde_json::json!(100)
- );
- assert_eq!(
- spans.iter().find(|span| span.name == "llm.gpt-4-mini").unwrap().attributes["gen_ai.usage.input_tokens"],
- serde_json::json!(7),
- "the repeated call id in a child run must retain its own usage"
- );
- let captured = spans_from_observations(ctx().with_capture_content(true), 10, &observations);
- assert!(
- spans_to_ndjson(SpanEnvelope::Otel, &captured).contains("CONTENT_SENTINEL_PROMPT"),
- "content-on export retains opted-in prompt content"
- );
- println!("{snapshot}");
-}
-
-#[test]
-fn projects_single_agent_turn_span_tree() {
- let spans = spans_from_observations(ctx(), 10, &single_turn(None));
-
- // Turn + iteration + tool + generation spans are all present.
- let by_kind = |k: SpanKind| spans.iter().filter(|s| s.kind == k).count();
- assert_eq!(by_kind(SpanKind::Turn), 1, "one turn span");
- assert_eq!(by_kind(SpanKind::Iteration), 1, "one iteration span");
- assert_eq!(by_kind(SpanKind::Tool), 1, "one tool span");
- assert_eq!(by_kind(SpanKind::Generation), 1, "one generation span");
-
- let tool = spans.iter().find(|s| s.kind == SpanKind::Tool).unwrap();
- assert_eq!(tool.name, "tool.lookup");
- assert_eq!(tool.attributes["tool.success"], serde_json::json!(true));
- assert_eq!(tool.attributes["tool.output_chars"], serde_json::json!(12));
- assert_eq!(tool.attributes["tool.elapsed_ms"], serde_json::json!(30));
-
- let generation = spans
- .iter()
- .find(|s| s.kind == SpanKind::Generation)
- .unwrap();
- assert!(
- generation.name.contains("gpt-4"),
- "gen span names the model"
- );
-}
-
-#[test]
-fn failed_tool_projects_error_outcome() {
- // With content capture on, a failed tool span carries the classified
- // cause reconstructed from the journalled error string, reproducing the
- // live path's `classify(error, false)` exactly.
- let spans = spans_from_observations(
- ctx().with_capture_content(true),
- 10,
- &single_turn(Some("permission denied opening /etc/x")),
- );
- let tool = spans.iter().find(|s| s.kind == SpanKind::Tool).unwrap();
- assert_eq!(tool.attributes["tool.success"], serde_json::json!(false));
- assert!(
- tool.attributes.contains_key("error.message"),
- "failed tool span carries a classified error message"
- );
-}
-
-#[test]
-fn projects_subagent_scope_from_lifecycle_brackets() {
- let spans = spans_from_observations(ctx(), 10, &subagent_turn());
-
- let by_kind = |k: SpanKind| spans.iter().filter(|s| s.kind == k).count();
- assert_eq!(by_kind(SpanKind::Subagent), 1, "one subagent span");
- assert_eq!(
- by_kind(SpanKind::SubagentIteration),
- 1,
- "one child iteration span"
- );
- assert_eq!(by_kind(SpanKind::Tool), 1, "one child tool span");
- assert_eq!(by_kind(SpanKind::Generation), 1, "one child generation");
-
- let subagent = spans.iter().find(|s| s.kind == SpanKind::Subagent).unwrap();
- assert_eq!(
- subagent.attributes["subagent.agent_id"],
- serde_json::json!("researcher")
- );
- assert_eq!(
- subagent.attributes["subagent.iterations"],
- serde_json::json!(1)
- );
-
- let child_iteration = spans
- .iter()
- .find(|s| s.kind == SpanKind::SubagentIteration)
- .unwrap();
- assert_eq!(
- child_iteration.parent_span_id.as_deref(),
- Some(subagent.span_id.as_str())
- );
-}
-
-#[test]
-fn projects_failed_subagent_from_child_run_failed() {
- 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::RunFailed {
- run_id: RunId::new("run-1"),
- error: "provider unavailable".to_string(),
- outcome: None,
- },
- ),
- obs(
- 3,
- 1_030,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ),
- ];
-
- let spans = spans_from_observations(ctx(), 10, &observations);
- let subagent = spans.iter().find(|s| s.kind == SpanKind::Subagent).unwrap();
-
- assert_eq!(subagent.status, SpanStatus::Error);
- assert_eq!(subagent.attributes["error"], serde_json::json!(true));
- assert!(
- subagent.attributes.contains_key("error.length"),
- "failed subagent span carries redacted error metadata"
- );
-}
-
-#[test]
-fn projects_turn_content_from_root_model_io() {
- 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("m1"),
- model: "gpt-4".to_string(),
- },
- ),
- obs(
- 2,
- 1_020,
- AgentEvent::ModelCompleted {
- call_id: CallId::new("m1"),
- started_at_ms: Some(1_010),
- usage: Some(Usage::new(5, 3)),
- input: Some(serde_json::json!([
- {"role": "user", "content": "summarize this"}
- ])),
- output: Some(serde_json::json!({
- "role": "assistant",
- "content": "short summary"
- })),
- },
- ),
- obs(
- 3,
- 1_030,
- AgentEvent::RunCompleted {
- run_id: RunId::new("run-1"),
- outcome: None,
- },
- ),
- ];
- let spans = spans_from_observations(ctx().with_capture_content(true), 10, &observations);
- let turn = spans.iter().find(|s| s.kind == SpanKind::Turn).unwrap();
-
- assert!(
- turn.input
- .as_ref()
- .unwrap()
- .to_string()
- .contains("summarize this"),
- "root model input is attached through TurnContent"
- );
- assert_eq!(
- turn.output.as_ref().unwrap(),
- &serde_json::json!("short summary")
- );
-}
-
-#[path = "journal_projection_accuracy_tests.rs"]
-mod accuracy_tests;
-#[path = "journal_projection_cost_rollup_tests.rs"]
-mod cost_rollup_tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_replay.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_replay.rs
deleted file mode 100644
index 29358c2e1c..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_replay.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-//! Support types for the journal projection: collector actions that are not
-//! [`AgentProgress`] events, and the pure text/outcome extraction helpers.
-
-use tinyagents_harness::terminal::{TerminalClass, TerminalOutcome};
-
-use crate::core::observability::progress_tracing::TurnOutcome;
-use crate::progress::AgentProgress;
-
-/// One step applied to the [`super::SpanCollector`] while replaying a journal.
-///
-/// Most observations map to [`AgentProgress`] stamped at the observation's
-/// own time; a few carry facts `AgentProgress` cannot express (a model call's
-/// real request start, the turn's failure) or need a different timestamp.
-#[derive(Debug)]
-pub(super) enum Replay {
- /// A progress event stamped at an explicit time (not the observation's).
- At(AgentProgress, u64),
- /// The next model call in this scope (`None` = top level) started here.
- CallStart(Option<String>, u64),
- /// The top-level run ended this way.
- Outcome(TurnOutcome),
-}
-
-/// Map a top-level `RunFailed` onto the turn outcome its span reports.
-pub(super) fn turn_outcome_for_failure(
- error: &str,
- outcome: Option<&TerminalOutcome>,
-) -> TurnOutcome {
- let message = outcome
- .map(|o| o.message.clone())
- .filter(|m| !m.trim().is_empty())
- .unwrap_or_else(|| error.to_string());
- match outcome.map(|o| o.class) {
- Some(TerminalClass::Cancellation) => TurnOutcome::Cancelled {
- reason: Some(message),
- },
- Some(TerminalClass::Timeout) => TurnOutcome::TimedOut { message },
- _ => TurnOutcome::Failed { message },
- }
-}
-
-/// Text of a captured message payload: a bare string, an object's `content`
-/// string, else its JSON.
-pub(super) fn json_content_text(value: &serde_json::Value) -> String {
- match value {
- serde_json::Value::String(text) => text.clone(),
- serde_json::Value::Object(map) => map
- .get("content")
- .and_then(serde_json::Value::as_str)
- .map(str::to_string)
- .unwrap_or_else(|| value.to_string()),
- _ => value.to_string(),
- }
-}
-
-/// The user's message from a captured model request: the text of the last
-/// user-role message in the request array. Handles both the role-tagged shape
-/// (`{"role": "user", "content": …}`) and the crate's externally tagged
-/// `Message` (`{"user": {"content": [{"text": …}]}}`). Falls back to
-/// [`json_content_text`] when the payload holds no user message.
-pub(super) fn user_message_text(value: &serde_json::Value) -> String {
- let user_payload = value.as_array().and_then(|messages| {
- messages.iter().rev().find_map(|message| {
- let object = message.as_object()?;
- if object.get("role").and_then(serde_json::Value::as_str) == Some("user") {
- return Some(message);
- }
- object.get("user")
- })
- });
- match user_payload {
- Some(payload) => content_text(payload.get("content").unwrap_or(payload)),
- None => json_content_text(value),
- }
-}
-
-/// Visible text of a `content` value: a string, or the text blocks of a
-/// content-block array joined by newlines.
-fn content_text(content: &serde_json::Value) -> String {
- match content {
- serde_json::Value::String(text) => text.clone(),
- serde_json::Value::Array(blocks) => blocks
- .iter()
- .filter_map(|block| match block {
- serde_json::Value::String(text) => Some(text.clone()),
- serde_json::Value::Object(object) => object
- .get("text")
- .and_then(serde_json::Value::as_str)
- .map(str::to_string),
- _ => None,
- })
- .collect::<Vec<_>>()
- .join("\n"),
- other => other.to_string(),
- }
-}
-
-#[cfg(test)]
-#[path = "journal_replay_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_replay_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_replay_tests.rs
deleted file mode 100644
index 4113035a2b..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_replay_tests.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-use super::*;
-use tinyagents_harness::terminal::TerminalReason;
-
-#[test]
-fn user_message_text_reads_the_last_user_message_in_both_shapes() {
- let role_tagged = serde_json::json!([
- {"role": "system", "content": "You are OpenHuman."},
- {"role": "user", "content": "first question"},
- {"role": "assistant", "content": "answer"},
- {"role": "user", "content": "follow-up"}
- ]);
- assert_eq!(user_message_text(&role_tagged), "follow-up");
-
- let crate_tagged = serde_json::json!([
- {"system": {"content": [{"text": "sys"}]}},
- {"user": {"content": [{"text": "build me a workflow"}, {"image": {}}]}}
- ]);
- assert_eq!(user_message_text(&crate_tagged), "build me a workflow");
-}
-
-#[test]
-fn user_message_text_falls_back_without_a_user_message() {
- assert_eq!(user_message_text(&serde_json::json!("plain")), "plain");
- assert_eq!(
- user_message_text(&serde_json::json!({"content": "obj"})),
- "obj"
- );
-}
-
-#[test]
-fn failure_outcome_maps_terminal_class() {
- let cancelled = TerminalOutcome::new(TerminalReason::Cancelled, "user stopped");
- assert_eq!(
- turn_outcome_for_failure("ignored", Some(&cancelled)),
- TurnOutcome::Cancelled {
- reason: Some("user stopped".into())
- }
- );
- let timeout = TerminalOutcome::new(TerminalReason::Timeout, "deadline");
- assert_eq!(
- turn_outcome_for_failure("ignored", Some(&timeout)),
- TurnOutcome::TimedOut {
- message: "deadline".into()
- }
- );
- assert_eq!(
- turn_outcome_for_failure("provider down", None),
- TurnOutcome::Failed {
- message: "provider down".into()
- }
- );
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rs
deleted file mode 100644
index 7bcc9b2588..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rs
+++ /dev/null
@@ -1,126 +0,0 @@
-use super::*;
-
-// The canonical production and staging APIs accept traces. Unknown origins
-// must remain closed before a session bearer is read.
-
-#[test]
-fn push_is_allowed_for_our_backends() {
- assert!(push_allowed("production"));
- assert!(push_allowed("staging"));
- assert!(push_allowed("development"));
- assert!(!push_allowed("external"));
-}
-
-#[test]
-fn an_unrecognised_environment_fails_closed() {
- // The allowlist, not a `!= "production"` negation, is what makes this
- // true: a bucket nobody has thought of yet does not push.
- for unknown in ["preview", "prod", "PRODUCTION", "", "qa", "external"] {
- assert!(
- !push_allowed(unknown),
- "{unknown:?} must not push — the allowlist is the fail-closed guard"
- );
- }
-}
-
-#[test]
-fn every_environment_for_base_bucket_is_classified_deliberately() {
- // Ties the two functions together: if `environment_for_base` grows a
- // bucket, this fails until someone decides which side it belongs on.
- assert!(push_allowed(environment_for_base(
- "https://staging-api.tinyhumans.ai"
- )));
- assert!(push_allowed(environment_for_base("http://localhost:7788")));
- assert!(push_allowed(environment_for_base(
- "https://api.tinyhumans.ai"
- )));
-}
-
-#[test]
-fn ingestion_url_uses_backend_origin_and_ingestion_path() {
- let mut config = Config::default();
- config.api_url = Some("https://staging-api.tinyhumans.ai/api/v1".to_string());
- assert_eq!(
- ingestion_url(&config),
- "https://staging-api.tinyhumans.ai/telemetry/langfuse/ingestion",
- "endpoint is the backend's Langfuse proxy route on the base server \
- host, replacing any inference path the base carried"
- );
-
- // A base carrying an inference path resolves to the proxy route on the
- // SAME host — the ingestion host tracks the base server URL, not a fixed
- // literal.
- let mut with_inference_path = Config::default();
- with_inference_path.api_url =
- Some("https://api.tinyhumans.ai/openai/v1/chat/completions".to_string());
- assert_eq!(
- ingestion_url(&with_inference_path),
- "https://api.tinyhumans.ai/telemetry/langfuse/ingestion"
- );
-}
-
-#[test]
-fn environment_derivation_from_backend_base() {
- assert_eq!(
- environment_for_base("https://staging-api.tinyhumans.ai"),
- "staging"
- );
- assert_eq!(environment_for_base("http://localhost:5000"), "development");
- assert_eq!(environment_for_base("http://127.0.0.1:5000"), "development");
- assert_eq!(
- environment_for_base("https://api.tinyhumans.ai"),
- "production"
- );
-}
-
-/// A hostname that merely *contains* `staging` is not ours. The classifier
-/// gates whether a live session token leaves the process, so anything it
-/// cannot positively recognise has to land on `external` — which does
-/// not push.
-#[test]
-fn a_lookalike_staging_host_is_external_not_staging() {
- for base in [
- // The substring match this replaced classified all of these as
- // staging, and `push_allowed` would then have let them through.
- "https://staging-attacker.invalid",
- "https://staging.evil.example",
- "http://staging-api.tinyhumans.ai.evil.example",
- // Right domain, wrong label position.
- "https://api-staging-mirror.tinyhumans.ai",
- // A public IP literal is never a deployment of ours.
- "https://93.184.216.34",
- // Never send a session bearer to a public backend over plaintext.
- "http://api.tinyhumans.ai",
- ] {
- let environment = environment_for_base(base);
- assert_eq!(
- environment, "external",
- "{base} must classify as external, got {environment}"
- );
- assert!(!push_allowed(environment), "{base} must not be pushable");
- }
-}
-
-/// The local buckets the substring form missed. An IPv6 loopback backend
-/// is an ordinary local setup, and before the parse it classified as
-/// external — so turning the push gate on would have silently stopped
-/// exports that had been working.
-#[test]
-fn local_backends_are_development_including_ipv6_and_private_ranges() {
- for base in [
- "http://[::1]:7788",
- "http://[0:0:0:0:0:0:0:1]:7788",
- "http://[::]:7788",
- "http://192.168.1.20:5000",
- "http://10.0.0.5:5000",
- "http://api.localhost:5000",
- "http://0.0.0.0:5000",
- ] {
- let environment = environment_for_base(base);
- assert_eq!(
- environment, "development",
- "{base} must classify as development, got {environment}"
- );
- assert!(push_allowed(environment), "{base} must stay pushable");
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse_tests.rs
deleted file mode 100644
index fdb287f841..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse_tests.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-use super::*;
-use serde_json::json;
-use std::collections::BTreeMap;
-use tinyagents_harness::events::AgentEvent;
-use tinyagents_harness::observability::trace_export::{SpanStatus, TraceSpan};
-use tinyagents_harness::observability::AgentObservation;
-
-use tinyagents_harness::ids::{EventId, RunId};
-use tinyagents_harness::observability::trace_export::SpanKind;
-
-fn span(
- trace: &str,
- id: &str,
- parent: Option<&str>,
- name: &str,
- kind: SpanKind,
- status: SpanStatus,
- start: u64,
- end: Option<u64>,
-) -> TraceSpan {
- let mut attributes = BTreeMap::new();
- attributes.insert("tokens".to_string(), json!(42));
- TraceSpan {
- trace_id: trace.to_string(),
- span_id: id.to_string(),
- parent_span_id: parent.map(str::to_string),
- name: name.to_string(),
- kind,
- start_unix_ms: start,
- end_unix_ms: end,
- status,
- attributes,
- input: None,
- output: None,
- }
-}
-
-fn obs(offset: u64, event: AgentEvent) -> AgentObservation {
- AgentObservation {
- event_id: EventId::new(format!("run-1-evt-{offset}")),
- run_id: RunId::new("run-1"),
- parent_run_id: None,
- root_run_id: RunId::new("run-1"),
- offset,
- ts_ms: 1_000 + offset,
- event,
- }
-}
-
-#[path = "langfuse_batch_tests.rs"]
-mod batch_tests;
-#[path = "langfuse_trace_fields_tests.rs"]
-mod trace_fields_tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rs
deleted file mode 100644
index 8fa13a538f..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-use super::*;
-
-/// An unparseable base is the fail-closed default rather than a panic or a
-/// pushable bucket. `ingestion_url` returns a non-URL placeholder when no
-/// backend host resolves.
-#[test]
-fn an_unparseable_base_is_external() {
- for base in ["", "not a url", "/api/v1/ingestion"] {
- assert_eq!(
- environment_for_base(base),
- "external",
- "{base:?} must fail closed"
- );
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp.rs
deleted file mode 100644
index 4a6cf69b81..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-//! Bounded OTLP/HTTP JSON export through the authenticated backend proxy.
-//!
-//! The span-to-OTLP conversion is upstream
-//! (`tinyagents_harness::observability::trace_export::otlp`); this module only
-//! resolves the backend URL and credential and posts the requests.
-
-use std::time::Duration;
-
-use tinyagents_harness::observability::trace_export::otlp::otlp_requests;
-use tinyagents_harness::observability::trace_export::TraceSpan;
-use tinyagents_harness::observability::LangfuseClient;
-
-use super::langfuse::{environment_for_base, ingestion_url, skip_push};
-use crate::config::Config;
-use crate::security::credentials::session_support::direct_backend_credential;
-
-const PUSH_TIMEOUT: Duration = Duration::from_secs(10);
-
-pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {
- if spans.is_empty() {
- return Ok(());
- }
- let url = ingestion_url(config);
- let environment = environment_for_base(&url);
- if skip_push(environment) {
- return Ok(());
- }
- if !url.starts_with("http") {
- return Err("Langfuse backend proxy URL is unavailable".to_string());
- }
- // No TinyHumans connection, or no usable credential (signed out, offline
- // local session): a configured state, so skip quietly rather than failing
- // every turn's push.
- let token = match direct_backend_credential(config, "langfuse otlp push") {
- Some(crate::security::credentials::session_support::BackendCredential::Session(token)) => {
- token
- }
- _ => return Ok(()),
- };
- // Reuse the host's configured API transport for TLS, attribution headers,
- // and route policy. LangfuseClient owns the proxy route, bearer header,
- // OTLP v4 header, and response validation.
- let transport = crate::backend::resolve_backend_transport()
- .map_err(|err| format!("Langfuse OTLP push has no backend transport: {err}"))?;
- let client = LangfuseClient::proxy_with_transport(
- url,
- token,
- transport.http_client(crate::backend::TransportProfile::Api),
- transport.attribution_headers(),
- )
- .map_err(|_| "Langfuse OTLP proxy client could not be configured".to_string())?;
- for payload in otlp_requests(spans, environment, &super::export_brand()) {
- tokio::time::timeout(PUSH_TIMEOUT, client.send_otlp(payload))
- .await
- .map_err(|_| "Langfuse OTLP proxy request timed out".to_string())?
- .map_err(|_| "Langfuse OTLP proxy request failed".to_string())?;
- }
- Ok(())
-}
-
-#[cfg(test)]
-#[path = "otlp_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs
deleted file mode 100644
index 8429643aca..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use super::*;
-use std::collections::BTreeMap;
-use tinyagents_harness::observability::trace_export::{SpanKind, SpanStatus};
-
-#[tokio::test]
-async fn external_backend_is_skipped_before_session_lookup() {
- let mut config = Config::default();
- config.api_url = Some("https://external.example.invalid/openai/v1".into());
- let spans = [TraceSpan {
- trace_id: "thread-one:turn-one".into(),
- span_id: "root".into(),
- parent_span_id: None,
- name: "agent.turn".into(),
- kind: SpanKind::Turn,
- start_unix_ms: 1_000,
- end_unix_ms: Some(2_000),
- status: SpanStatus::Ok,
- attributes: BTreeMap::new(),
- input: None,
- output: None,
- }];
- assert!(push_spans(&config, &spans).await.is_ok());
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_accuracy_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_accuracy_tests.rs
deleted file mode 100644
index 834c7022f8..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_accuracy_tests.rs
+++ /dev/null
@@ -1,557 +0,0 @@
-//! Trace accuracy regressions from production Langfuse traces (Oct 2026):
-//! per-call generation start, unstreamed TTFT, late/missing tool completions,
-//! turn outcome, turn input, model labels, unpriced cost and usage totals.
-
-use super::*;
-
-use tinyagents_harness::observability::trace_export::otlp::otlp_requests;
-
-fn iteration(iteration: u32) -> AgentProgress {
- AgentProgress::IterationStarted {
- iteration,
- max_iterations: 15,
- }
-}
-
-#[allow(clippy::too_many_arguments)]
-fn call(
- model: &str,
- provider: &str,
- task: Option<&str>,
- input: u64,
- output: u64,
- cache_read: u64,
- cache_write: u64,
- cost: impl Into<Option<f64>>,
-) -> AgentProgress {
- AgentProgress::ModelCallCompleted {
- model: model.to_string(),
- provider_id: provider.to_string(),
- subagent_task_id: task.map(str::to_string),
- input: None,
- output: None,
- iteration: 1,
- input_tokens: input,
- output_tokens: output,
- cached_input_tokens: cache_read,
- cache_creation_tokens: cache_write,
- reasoning_tokens: 0,
- cost_usd: cost.into(),
- }
-}
-
-fn simple_call(model: &str) -> AgentProgress {
- call(model, "managed", None, 100, 10, 0, 0, 0.001)
-}
-
-fn child_iteration(task: &str, iteration: u32) -> AgentProgress {
- AgentProgress::SubagentIterationStarted {
- agent_id: "researcher".to_string(),
- task_id: task.to_string(),
- iteration,
- max_iterations: 10,
- extended_policy: false,
- }
-}
-
-fn child_tool_started(task: &str, call_id: &str, tool: &str) -> AgentProgress {
- AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".to_string(),
- task_id: task.to_string(),
- call_id: call_id.to_string(),
- tool_name: tool.to_string(),
- arguments: serde_json::Value::Null,
- iteration: 1,
- display_label: None,
- display_detail: None,
- }
-}
-
-fn child_tool_completed(task: &str, call_id: &str, tool: &str, elapsed: u64) -> AgentProgress {
- AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".to_string(),
- task_id: task.to_string(),
- call_id: call_id.to_string(),
- tool_name: tool.to_string(),
- success: true,
- output_chars: 3,
- output: String::new(),
- arguments: None,
- elapsed_ms: elapsed,
- iteration: 1,
- failure: None,
- display_label: None,
- display_detail: None,
- structured: None,
- }
-}
-
-fn child_completed(task: &str, elapsed: u64) -> AgentProgress {
- AgentProgress::SubagentCompleted {
- agent_id: "researcher".to_string(),
- task_id: task.to_string(),
- elapsed_ms: elapsed,
- iterations: 1,
- output_chars: 0,
- output: String::new(),
- usage: None,
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- stop: None,
- }
-}
-
-fn generations(spans: &[TraceSpan]) -> Vec<&TraceSpan> {
- spans
- .iter()
- .filter(|span| span.kind == SpanKind::Generation)
- .collect()
-}
-
-fn exported_attr(spans: &[TraceSpan], name: &str, key: &str) -> Option<String> {
- let payloads = otlp_requests(spans, "production", &super::export_brand());
- payloads.iter().find_map(|payload| {
- payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
- .as_array()?
- .iter()
- .find(|span| span["name"] == name)?["attributes"]
- .as_array()?
- .iter()
- .find(|item| item["key"] == key)
- .and_then(|item| item["value"]["stringValue"].as_str())
- .map(str::to_string)
- })
-}
-
-// ── 1. each model call starts at its own request start ──────────────────────
-
-#[test]
-fn calls_folded_into_one_iteration_do_not_share_its_start() {
- // Production d1f1562f: four generations in one iteration all started at
- // the iteration's first millisecond, so each latency covered the calls
- // before it. A later call cannot start before the previous one ended.
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (simple_call("chat-v1"), 3_000),
- (simple_call("chat-v1"), 5_000),
- (simple_call("chat-v1"), 9_000),
- ]);
- c.finish(9_500);
- let spans = c.spans();
- let starts: Vec<(u64, Option<u64>)> = generations(spans)
- .iter()
- .map(|g| (g.start_unix_ms, g.end_unix_ms))
- .collect();
- assert_eq!(
- starts,
- vec![
- (1_000, Some(3_000)),
- (3_000, Some(5_000)),
- (5_000, Some(9_000))
- ]
- );
-}
-
-#[test]
-fn explicit_call_start_wins() {
- let mut c = SpanCollector::new(ctx());
- c.record(&AgentProgress::TurnStarted, 1_000);
- c.record(&iteration(1), 1_000);
- c.set_next_call_start(None, 2_500);
- c.record(&simple_call("chat-v1"), 3_000);
- assert_eq!(generations(c.spans())[0].start_unix_ms, 2_500);
-}
-
-// ── 2. TTFT is not recorded for a non-streamed call ─────────────────────────
-
-#[test]
-fn single_synthetic_delta_at_completion_records_no_ttft() {
- // The OpenAI Responses path is unary and emits the whole reply as one
- // delta right before completing; its "first token" is the latency.
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (
- AgentProgress::TextDelta {
- delta: "whole reply".into(),
- iteration: 1,
- },
- 8_995,
- ),
- (simple_call("gpt-6.1-sol"), 9_000),
- ]);
- let g = generations(c.spans())[0];
- assert!(!g
- .attributes
- .contains_key("gen_ai.response.first_token_unix_ms"));
- assert!(!g
- .attributes
- .contains_key("gen_ai.response.time_to_first_token_ms"));
- assert_eq!(
- g.attributes["gen_ai.response.streamed"],
- serde_json::json!(false)
- );
- assert_eq!(
- exported_attr(
- c.spans(),
- "llm.gpt-6.1-sol",
- "langfuse.observation.completion_start_time"
- ),
- None
- );
-}
-
-// ── 3. sub-agent tool completions and force-closed spans ────────────────────
-
-#[test]
-fn late_child_tool_completion_after_subagent_completed_closes_the_span() {
- // Under channel backpressure the child bridge's completion can reach the
- // collector after the orchestrator's `SubagentCompleted`; it used to be
- // dropped, leaving the tool open until the turn ended (407 s spans).
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (spawn("t1", "Builder"), 1_100),
- (child_iteration("t1", 1), 1_200),
- (
- child_tool_started("t1", "c1", "get_node_kind_contract"),
- 1_300,
- ),
- (child_completed("t1", 900), 2_000),
- (
- child_tool_completed("t1", "c1", "get_node_kind_contract", 4),
- 2_050,
- ),
- (
- AgentProgress::TurnCompleted {
- iterations: 1,
- stop: None,
- },
- 400_000,
- ),
- ]);
- c.finish(400_000);
- let tool = find(c.spans(), "tool.get_node_kind_contract");
- assert_eq!(tool.end_unix_ms, Some(1_304));
- assert_eq!(tool.status, SpanStatus::Ok);
- assert!(!tool.attributes.contains_key("force_closed"));
-}
-
-#[test]
-fn late_child_model_call_nests_under_its_subagent() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (spawn("t1", "Builder"), 1_100),
- (child_iteration("t1", 1), 1_200),
- (child_completed("t1", 900), 2_000),
- (call("", "", Some("t1"), 10, 1, 0, 0, 0.0), 2_050),
- ]);
- c.finish(3_000);
- let spans = c.spans();
- let child_iter = find(spans, "subagent.iteration#1");
- let g = generations(spans)[0];
- assert_eq!(
- g.parent_span_id.as_deref(),
- Some(child_iter.span_id.as_str()),
- "a late child call must not land in the parent's iteration"
- );
-}
-
-#[test]
-fn tool_without_completion_is_force_closed_at_its_parent_end() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (tool_started("c1", "composio_list_toolkits", 1), 1_500),
- (iteration(2), 2_000),
- (simple_call("chat-v1"), 3_000),
- (
- AgentProgress::TurnCompleted {
- iterations: 2,
- stop: None,
- },
- 440_000,
- ),
- ]);
- c.finish(440_000);
- let tool = find(c.spans(), "tool.composio_list_toolkits");
- assert_eq!(
- tool.end_unix_ms,
- Some(2_000),
- "bounded by the iteration end, not the turn end"
- );
- assert_eq!(tool.attributes["force_closed"], serde_json::json!(true));
- assert_eq!(
- tool.attributes["observation.level"],
- serde_json::json!("WARNING")
- );
- assert_eq!(tool.status, SpanStatus::Unset);
-}
-
-// ── 4. the root turn span reflects the outcome ──────────────────────────────
-
-#[test]
-fn turn_without_completion_is_an_error() {
- let mut c = collect(&[(AgentProgress::TurnStarted, 1_000), (iteration(1), 1_000)]);
- c.finish(5_000);
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(turn.status, SpanStatus::Error);
- assert_eq!(
- turn.attributes["turn.outcome"],
- serde_json::json!("incomplete")
- );
- assert_eq!(
- exported_attr(c.spans(), "agent.turn", "langfuse.observation.level").as_deref(),
- Some("ERROR")
- );
- assert!(exported_attr(
- c.spans(),
- "agent.turn",
- "langfuse.observation.status_message"
- )
- .is_some());
-}
-
-#[test]
-fn failed_turn_message_is_content_gated() {
- let failed = || TurnOutcome::Failed {
- message: "provider rejected /Users/alice/secret.txt".into(),
- };
- let mut gated = collect(&[(AgentProgress::TurnStarted, 1_000)]);
- gated.finish_with_outcome(2_000, Some(failed()));
- let turn = find(gated.spans(), "agent.turn");
- assert_eq!(turn.status, SpanStatus::Error);
- assert_eq!(
- turn.attributes["error.message"],
- serde_json::json!("Turn failed")
- );
-
- let mut captured = collect_with_capture(&[(AgentProgress::TurnStarted, 1_000)]);
- captured.finish_with_outcome(2_000, Some(failed()));
- let turn = find(captured.spans(), "agent.turn");
- assert!(turn.attributes["error.message"]
- .as_str()
- .unwrap()
- .contains("provider rejected"));
-}
-
-#[test]
-fn cancelled_turn_is_a_warning_not_an_error() {
- let mut c = collect(&[(AgentProgress::TurnStarted, 1_000)]);
- c.finish_with_outcome(2_000, Some(TurnOutcome::Cancelled { reason: None }));
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(turn.status, SpanStatus::Unset);
- assert_eq!(
- turn.attributes["turn.outcome"],
- serde_json::json!("cancelled")
- );
- assert_eq!(
- turn.attributes["observation.level"],
- serde_json::json!("WARNING")
- );
-}
-
-#[test]
-fn completed_turn_is_not_reclassified_by_finish() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (
- AgentProgress::TurnCompleted {
- iterations: 1,
- stop: None,
- },
- 2_000,
- ),
- ]);
- c.finish_with_outcome(
- 3_000,
- Some(TurnOutcome::Failed {
- message: "x".into(),
- }),
- );
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(turn.status, SpanStatus::Ok);
- assert_eq!(turn.end_unix_ms, Some(2_000));
-}
-
-// ── 5. the turn input is the user's message ─────────────────────────────────
-
-#[test]
-fn first_turn_input_is_kept() {
- let c = collect_with_capture(&[
- (AgentProgress::TurnStarted, 1_000),
- (
- AgentProgress::TurnContent {
- input: Some("what's on my calendar?".into()),
- output: None,
- },
- 1_000,
- ),
- (
- AgentProgress::TurnContent {
- input: Some("[Tool results]\n…".into()),
- output: Some("You have two meetings.".into()),
- },
- 5_000,
- ),
- ]);
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.input.as_ref().unwrap(),
- &serde_json::json!("what's on my calendar?")
- );
- assert_eq!(
- turn.output.as_ref().unwrap(),
- &serde_json::json!("You have two meetings.")
- );
-}
-
-// ── 6. model labels ─────────────────────────────────────────────────────────
-
-#[test]
-fn empty_provider_and_model_do_not_produce_dot_labels() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (
- call(
- "openrouter/deepseek/deepseek-v4-flash",
- "",
- None,
- 10,
- 1,
- 0,
- 0,
- 0.0,
- ),
- 2_000,
- ),
- (iteration(2), 3_000),
- (call("", "", None, 10, 1, 0, 0, 0.0), 4_000),
- ]);
- c.finish(4_000);
- for g in generations(c.spans()) {
- assert_eq!(g.name, "llm.openrouter/deepseek/deepseek-v4-flash");
- assert_eq!(
- g.attributes["gen_ai.request.model"],
- serde_json::json!("openrouter/deepseek/deepseek-v4-flash")
- );
- }
-}
-
-// ── 7. unpriced / free models ───────────────────────────────────────────────
-
-#[test]
-fn unpriced_model_unknown_cost_is_not_recorded() {
- let model = "acme/never-heard-of-it";
- let placeholder = crate::agent::cost::estimate_call_cost_usd(
- model,
- &crate::inference::provider::BilledUsage::from_counts(1_000, 100),
- );
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (
- call(model, "openrouter", None, 1_000, 100, 0, 0, placeholder),
- 2_000,
- ),
- ]);
- let g = generations(c.spans())[0];
- assert!(!g.attributes.contains_key("gen_ai.usage.cost_usd"));
- assert_eq!(
- g.attributes["gen_ai.cost.source"],
- serde_json::json!("unpriced")
- );
- assert!(!g
- .attributes
- .contains_key("gen_ai.pricing.input_per_mtok_usd"));
- assert_eq!(
- exported_attr(
- c.spans(),
- "llm.acme/never-heard-of-it",
- "langfuse.observation.cost_details"
- ),
- None,
- "no fabricated costDetails reach Langfuse"
- );
-}
-
-#[test]
-fn free_model_is_priced_at_zero() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (
- call(
- "deepseek/deepseek-chat-v3.1:free",
- "openrouter",
- None,
- 1_000,
- 100,
- 0,
- 0,
- 0.0,
- ),
- 2_000,
- ),
- ]);
- let g = generations(c.spans())[0];
- assert_eq!(
- g.attributes["gen_ai.usage.cost_usd"],
- serde_json::json!(0.0)
- );
- assert_eq!(
- g.attributes["gen_ai.pricing.output_per_mtok_usd"],
- serde_json::json!(0.0)
- );
-}
-
-// ── 8. usage totals are consistent across routes ────────────────────────────
-
-#[test]
-fn uncached_only_input_route_reports_a_consistent_total() {
- // Claude Code route: raw Anthropic `input_tokens` (uncached remainder).
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (
- call(
- "claude-sonnet-4-5",
- "claude-code",
- None,
- 12,
- 300,
- 40_000,
- 2_000,
- 0.0,
- ),
- 2_000,
- ),
- ]);
- let g = generations(c.spans())[0];
- let a = &g.attributes;
- assert_eq!(a["gen_ai.usage.input_tokens"], serde_json::json!(42_012));
- assert_eq!(
- a["gen_ai.usage.uncached_input_tokens"],
- serde_json::json!(12)
- );
- assert_eq!(
- a["gen_ai.usage.cache_creation_tokens"],
- serde_json::json!(2_000)
- );
- assert_eq!(a["gen_ai.usage.total_tokens"], serde_json::json!(42_312));
- let usage: serde_json::Value = serde_json::from_str(
- &exported_attr(
- c.spans(),
- "llm.claude-sonnet-4-5",
- "langfuse.observation.usage_details",
- )
- .unwrap(),
- )
- .unwrap();
- assert_eq!(usage["total"], serde_json::json!(42_312));
- assert!(usage["total"].as_u64().unwrap() >= usage["cache_read_input_tokens"].as_u64().unwrap());
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs
deleted file mode 100644
index 6b6bab88b4..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_attribution_tests.rs
+++ /dev/null
@@ -1,652 +0,0 @@
-use super::*;
-
-use tinyagents_harness::observability::trace_export::SpanKind;
-// ── identity / attribution / content capture ───────────────────────────────
-
-#[test]
-fn turn_span_carries_agent_client_and_source_attribution() {
- let mut c = SpanCollector::new(
- TraceContext::new("trace:req-9", Some("user-123".to_string()))
- .with_client_id("socket-abc")
- .with_agent_id("researcher")
- .with_channel_source("autonomous"),
- );
- c.record(&AgentProgress::TurnStarted, 0);
- // Trace name folds in the agent id.
- let turn = find(c.spans(), "agent.turn:researcher");
- assert_eq!(turn.kind, SpanKind::Turn);
- // Real user id is the user attribution; the transport client id is a
- // separate attribute, never conflated with the user.
- assert_eq!(turn.attributes["user.id"], serde_json::json!("user-123"));
- assert_eq!(
- turn.attributes["client.id"],
- serde_json::json!("socket-abc")
- );
- assert_eq!(turn.attributes["agent.id"], serde_json::json!("researcher"));
- assert_eq!(
- turn.attributes["channel.source"],
- serde_json::json!("autonomous")
- );
-}
-
-#[test]
-fn turn_span_name_stays_plain_without_agent_id() {
- let mut c = SpanCollector::new(ctx());
- c.record(&AgentProgress::TurnStarted, 0);
- assert!(names(c.spans()).contains(&"agent.turn".to_string()));
-}
-
-#[test]
-fn thread_id_falls_back_to_trace_id_without_session_group() {
- // Every trace must end up with a Langfuse sessionId: with no explicit
- // session group, the trace id itself is stamped as thread.id.
- let mut c = SpanCollector::new(TraceContext::new("sess-42:req-1", None));
- c.record(&AgentProgress::TurnStarted, 0);
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.attributes["thread.id"],
- serde_json::json!("sess-42:req-1")
- );
-}
-
-#[test]
-fn tool_io_is_captured_when_capture_content_is_on() {
- let mut c = SpanCollector::new(ctx().with_capture_content(true));
- c.record(&AgentProgress::TurnStarted, 0);
- c.record(&tool_started("c1", "web_search", 1), 1);
- let tool = find(c.spans(), "tool.web_search");
- let input = tool.input.as_ref().and_then(|v| v.as_str()).unwrap();
- assert!(
- input.contains("do-not-export"),
- "tool arguments must be recorded as span input when capture is on"
- );
-
- // Subagent tool result → span output.
- c.record(&spawn("task-1", "Researcher"), 2);
- c.record(
- &AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "read_file".to_string(),
- arguments: serde_json::json!({"path": "notes.md"}),
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 3,
- );
- c.record(
- &AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "read_file".to_string(),
- success: true,
- output_chars: 13,
- output: "file contents".to_string(),
- arguments: None,
- elapsed_ms: 4,
- iteration: 1,
- failure: None,
- display_label: None,
- display_detail: None,
- structured: None,
- },
- 4,
- );
- let child_tool = find(c.spans(), "tool.read_file");
- assert!(child_tool
- .input
- .as_ref()
- .and_then(|v| v.as_str())
- .unwrap()
- .contains("notes.md"));
- assert_eq!(
- child_tool.output.as_ref().and_then(|v| v.as_str()),
- Some("file contents")
- );
-}
-
-#[test]
-fn tool_io_is_never_recorded_when_capture_content_is_off() {
- // Default ctx() has capture_content = false.
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (tool_started("c1", "web_search", 1), 1),
- (spawn("task-1", "Researcher"), 2),
- (
- AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "read_file".to_string(),
- arguments: serde_json::json!({"path": "secret.md"}),
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 3,
- ),
- (
- AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "read_file".to_string(),
- success: true,
- output_chars: 6,
- output: "sekrit".to_string(),
- arguments: None,
- elapsed_ms: 4,
- iteration: 1,
- failure: None,
- display_label: None,
- display_detail: None,
- structured: None,
- },
- 4,
- ),
- ]);
- c.finish(100);
- for span in c.spans() {
- if span.kind == SpanKind::Tool {
- assert!(span.input.is_none(), "no tool input with capture off");
- assert!(span.output.is_none(), "no tool output with capture off");
- }
- }
- let blob = serde_json::to_string(c.spans()).unwrap();
- assert!(!blob.contains("do-not-export"));
- assert!(!blob.contains("sekrit"));
-}
-
-#[test]
-fn captured_tool_io_is_truncated_with_marker() {
- let mut c = SpanCollector::new(ctx().with_capture_content(true));
- c.record(&AgentProgress::TurnStarted, 0);
- let huge = "x".repeat(10_000);
- c.record(
- &AgentProgress::ToolCallStarted {
- call_id: "c1".to_string(),
- tool_name: "shell".to_string(),
- arguments: serde_json::json!({ "cmd": huge }),
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 1,
- );
- let tool = find(c.spans(), "tool.shell");
- let input = tool.input.as_ref().and_then(|v| v.as_str()).unwrap();
- assert!(input.contains("[truncated"), "marker must flag truncation");
- assert!(
- input.chars().count() < 4_100,
- "captured input must be capped near 4000 chars, got {}",
- input.chars().count()
- );
-}
-
-#[test]
-fn model_call_completed_emits_generation_span_with_usage_cost_and_pricing() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 5,
- },
- 1_010,
- ),
- (model_call("claude-sonnet-4-6", 0, 0), 1_500),
- ]);
- c.finish(2_000);
- let spans = c.spans();
-
- let generation = find(spans, "llm.claude-sonnet-4-6");
- assert_eq!(generation.kind, SpanKind::Generation);
- // Parented under the live iteration; starts at the iteration start
- // (ModelStarted) and ends when the usage record was observed.
- let iter = find(spans, "agent.iteration#1");
- assert_eq!(
- generation.parent_span_id.as_deref(),
- Some(iter.span_id.as_str())
- );
- assert_eq!(generation.start_unix_ms, 1_010);
- assert_eq!(generation.end_unix_ms, Some(1_500));
- assert_eq!(generation.status, SpanStatus::Ok);
-
- let a = &generation.attributes;
- // Provider-labeled model: `{provider_id}.{model}`.
- assert_eq!(
- a["gen_ai.request.model"],
- serde_json::json!("managed.claude-sonnet-4-6")
- );
- assert_eq!(a["gen_ai.usage.input_tokens"], serde_json::json!(1_000));
- assert_eq!(a["gen_ai.usage.output_tokens"], serde_json::json!(200));
- // Cache reads always flow, even when other calls happen to be zero.
- assert_eq!(
- a["gen_ai.usage.cached_input_tokens"],
- serde_json::json!(300)
- );
- assert_eq!(a["gen_ai.usage.cost_usd"], serde_json::json!(0.0042));
- // Managed tier handle → managed provenance.
- assert_eq!(a["gen_ai.provider"], serde_json::json!("managed"));
- // Pricing basis is auditable.
- assert_eq!(
- a["gen_ai.pricing.input_per_mtok_usd"],
- serde_json::json!(3.0)
- );
- assert!(a.contains_key("gen_ai.pricing.output_per_mtok_usd"));
- // Zero reasoning tokens are omitted; cache writes always flow (even 0)
- // so every route reports the same usage dimensions.
- assert!(!a.contains_key("gen_ai.usage.reasoning_tokens"));
- assert_eq!(
- a["gen_ai.usage.cache_creation_tokens"],
- serde_json::json!(0)
- );
- assert_eq!(a["gen_ai.usage.total_tokens"], serde_json::json!(1_200));
- assert_eq!(a["gen_ai.cost.source"], serde_json::json!("priced"));
-}
-
-#[test]
-fn custom_model_generation_is_stamped_custom_provenance() {
- // A BYO model rides whatever provider id the event carries ("openai",
- // "ollama", or the "custom" default) — both on the generation and the root.
- let event = AgentProgress::ModelCallCompleted {
- model: "claude-imaginary-9".to_string(),
- provider_id: "custom".to_string(),
- subagent_task_id: None,
- input: None,
- output: None,
- iteration: 1,
- input_tokens: 10,
- output_tokens: 2,
- cached_input_tokens: 0,
- cache_creation_tokens: 0,
- reasoning_tokens: 0,
- cost_usd: Some(0.0001),
- };
- let mut c = collect(&[(AgentProgress::TurnStarted, 0), (event, 10)]);
- c.finish(20);
- let generation = find(c.spans(), "llm.claude-imaginary-9");
- assert_eq!(
- generation.attributes["gen_ai.provider"],
- serde_json::json!("custom")
- );
- assert_eq!(
- generation.attributes["gen_ai.request.model"],
- serde_json::json!("custom.claude-imaginary-9")
- );
- // Provenance also lands on the root turn span (→ trace metadata).
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.attributes["gen_ai.provider"],
- serde_json::json!("custom")
- );
-}
-
-#[test]
-fn reasoning_and_cache_write_tokens_flow_to_generation_and_root_rollup() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (model_call("agentic-v1", 128, 64), 10),
- (model_call("agentic-v1", 72, 0), 20),
- ]);
- c.finish(30);
- let spans = c.spans();
-
- // Per-call values on the generations.
- let generations: Vec<&TraceSpan> = spans
- .iter()
- .filter(|s| s.kind == SpanKind::Generation)
- .collect();
- assert_eq!(generations.len(), 2, "one generation per model call");
- assert_eq!(
- generations[0].attributes["gen_ai.usage.reasoning_tokens"],
- serde_json::json!(128)
- );
- assert_eq!(
- generations[0].attributes["gen_ai.usage.cache_creation_tokens"],
- serde_json::json!(64)
- );
- assert_eq!(
- generations[1].attributes["gen_ai.usage.reasoning_tokens"],
- serde_json::json!(72)
- );
-
- // Cumulative rollup on the root turn span (TurnCostUpdated doesn't carry
- // these dimensions).
- let turn = find(spans, "agent.turn");
- assert_eq!(
- turn.attributes["gen_ai.usage.reasoning_tokens"],
- serde_json::json!(200)
- );
- assert_eq!(
- turn.attributes["gen_ai.usage.cache_creation_tokens"],
- serde_json::json!(64)
- );
-}
-
-#[test]
-fn zero_reasoning_turn_leaves_root_without_reasoning_attr() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (model_call("agentic-v1", 0, 0), 10),
- ]);
- c.finish(20);
- let turn = find(c.spans(), "agent.turn");
- assert!(!turn
- .attributes
- .contains_key("gen_ai.usage.reasoning_tokens"));
- assert!(!turn
- .attributes
- .contains_key("gen_ai.usage.cache_creation_tokens"));
-}
-
-// ── run-type classification ─────────────────────────────────────────────────
-
-#[test]
-fn run_type_classifies_known_sources() {
- assert_eq!(RunType::from_source(None), RunType::InteractiveChat);
- assert_eq!(RunType::from_source(Some("ptt")), RunType::InteractiveChat);
- assert_eq!(RunType::from_source(Some("type")), RunType::InteractiveChat);
- assert_eq!(
- RunType::from_source(Some("autonomous")),
- RunType::AutonomousTask
- );
- assert_eq!(
- RunType::from_source(Some("channel_inbound")),
- RunType::ChannelInbound
- );
- assert_eq!(RunType::AutonomousTask.as_str(), "autonomous_task");
-}
-
-#[test]
-fn run_type_is_stamped_on_the_turn_span() {
- // Default: interactive chat.
- let mut c = SpanCollector::new(ctx());
- c.record(&AgentProgress::TurnStarted, 0);
- assert_eq!(
- find(c.spans(), "agent.turn").attributes["run.type"],
- serde_json::json!("interactive_chat")
- );
-
- // Explicit autonomous run.
- let mut c = SpanCollector::new(ctx().with_run_type(RunType::AutonomousTask));
- c.record(&AgentProgress::TurnStarted, 0);
- assert_eq!(
- find(c.spans(), "agent.turn").attributes["run.type"],
- serde_json::json!("autonomous_task")
- );
-}
-
-// ── error text capture (Langfuse statusMessage source) ─────────────────────
-
-#[test]
-fn subagent_failure_records_truncated_error_message_when_capture_on() {
- let mut c = SpanCollector::new(ctx().with_capture_content(true));
- c.record(&AgentProgress::TurnStarted, 0);
- c.record(&spawn("task-9", "Coder"), 5);
- let long_error = "boom ".repeat(200); // 1000 chars > 500 cap
- c.record(
- &AgentProgress::SubagentFailed {
- agent_id: "coder".to_string(),
- task_id: "task-9".to_string(),
- error: long_error,
- },
- 10,
- );
- let sub = find(c.spans(), "subagent.Coder");
- assert_eq!(sub.status, SpanStatus::Error);
- let message = sub.attributes["error.message"].as_str().unwrap();
- assert!(message.starts_with("boom "));
- assert!(message.contains("[truncated"), "500-char cap must apply");
- assert!(message.chars().count() < 600);
-}
-
-#[test]
-fn failed_tool_records_classified_cause_only_when_capture_on() {
- use tinytools::status::{ClassifiedFailure, FailureCategory, ToolFailureClass};
- let failed = AgentProgress::ToolCallCompleted {
- call_id: "c1".to_string(),
- tool_name: "shell".to_string(),
- success: false,
- output_chars: 0,
- output: String::new(),
- arguments: None,
- elapsed_ms: 5,
- iteration: 1,
- failure: Some(ClassifiedFailure {
- class: ToolFailureClass::Timeout,
- category: FailureCategory::Recoverable,
- cause_plain: "The command ran past its deadline".to_string(),
- next_action: "Try again".to_string(),
- recoverable: true,
- }),
- display_label: None,
- display_detail: None,
- structured: None,
- };
-
- // Capture ON → plain-language cause lands as error.message.
- let mut on = SpanCollector::new(ctx().with_capture_content(true));
- on.record(&AgentProgress::TurnStarted, 0);
- on.record(&tool_started("c1", "shell", 1), 1);
- on.record(&failed, 2);
- let tool = find(on.spans(), "tool.shell");
- assert_eq!(tool.status, SpanStatus::Error);
- assert_eq!(
- tool.attributes["error.message"],
- serde_json::json!("The command ran past its deadline")
- );
-
- // Capture OFF → no error text on the span.
- let mut off = SpanCollector::new(ctx());
- off.record(&AgentProgress::TurnStarted, 0);
- off.record(&tool_started("c1", "shell", 1), 1);
- off.record(&failed, 2);
- let tool = find(off.spans(), "tool.shell");
- assert_eq!(tool.status, SpanStatus::Error);
- assert!(!tool.attributes.contains_key("error.message"));
-}
-
-#[test]
-fn subagent_error_text_stays_out_without_capture() {
- // The pre-existing privacy behavior (length-only) holds with capture off —
- // covered by `subagent_failure_records_error_without_raw_text` above; here
- // we double-check error.message is absent.
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("task-9", "Coder"), 5),
- (
- AgentProgress::SubagentFailed {
- agent_id: "coder".to_string(),
- task_id: "task-9".to_string(),
- error: "secret path /Users/x".to_string(),
- },
- 10,
- ),
- ]);
- c.finish(50);
- let sub = find(c.spans(), "subagent.Coder");
- assert!(!sub.attributes.contains_key("error.message"));
-}
-
-#[test]
-fn span_ids_are_unique_across_turns() {
- // Two separate collectors (two turns) must not reuse span ids, or Langfuse
- // dedupes their observations onto whichever trace claimed the id first.
- let a = collect(&[(AgentProgress::TurnStarted, 1)]);
- let b = collect(&[(AgentProgress::TurnStarted, 1)]);
- assert_ne!(
- find(a.spans(), "agent.turn").span_id,
- find(b.spans(), "agent.turn").span_id,
- "span ids must be globally unique across turns"
- );
-}
-
-#[test]
-fn generation_records_request_messages_and_completion_when_capture_on() {
- let mut c = collect_with_capture(&[
- (AgentProgress::TurnStarted, 0),
- (model_call_with_content(None), 10),
- ]);
- c.finish(20);
- let generation = find(c.spans(), "llm.chat-v1");
- let input = generation.input.as_ref().expect("generation input");
- assert!(
- input.to_string().contains("You are OpenHuman."),
- "system prompt must land in the generation input: {input}"
- );
- assert!(generation
- .output
- .as_ref()
- .expect("generation output")
- .to_string()
- .contains("hello"));
-}
-
-#[test]
-fn generation_withholds_content_when_capture_off() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (model_call_with_content(None), 10),
- ]);
- c.finish(20);
- let generation = find(c.spans(), "llm.chat-v1");
- assert!(generation.input.is_none(), "capture off → no prompt");
- assert!(generation.output.is_none(), "capture off → no completion");
-}
-
-#[test]
-fn subagent_model_call_nests_generation_and_stamps_model_on_subagent_span() {
- let mut c = collect_with_capture(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("task-9", "Critic"), 5),
- (
- AgentProgress::SubagentIterationStarted {
- agent_id: "critic".to_string(),
- task_id: "task-9".to_string(),
- iteration: 1,
- max_iterations: 8,
- extended_policy: true,
- },
- 6,
- ),
- (model_call_with_content(Some("task-9")), 10),
- ]);
- c.finish(20);
- let spans = c.spans();
-
- // Generation nests under the subagent's iteration, not the parent turn.
- let generation = find(spans, "llm.chat-v1");
- let child_iter = find(spans, "subagent.iteration#1");
- assert_eq!(
- generation.parent_span_id.as_deref(),
- Some(child_iter.span_id.as_str())
- );
- assert!(generation.input.is_some(), "child generation carries input");
-
- // The subagent span itself surfaces the provider-labeled model + usage.
- let sub = find(spans, "subagent.Critic");
- assert_eq!(
- sub.attributes["gen_ai.request.model"],
- serde_json::json!("managed.chat-v1")
- );
- assert_eq!(
- sub.attributes["gen_ai.usage.input_tokens"],
- serde_json::json!(100)
- );
- assert_eq!(
- sub.attributes["gen_ai.usage.cost_usd"],
- serde_json::json!(0.001)
- );
-
- // The parent turn's rollup is NOT polluted by the child call.
- let turn = find(spans, "agent.turn");
- assert!(!turn.attributes.contains_key("gen_ai.request.model"));
-}
-
-#[test]
-fn parent_tool_completion_backfills_arguments_and_records_output() {
- let mut c = collect_with_capture(&[
- (AgentProgress::TurnStarted, 0),
- (
- // tinyagents path: Started carries Null arguments.
- AgentProgress::ToolCallStarted {
- call_id: "c1".to_string(),
- tool_name: "web_search".to_string(),
- arguments: serde_json::Value::Null,
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 5,
- ),
- (
- AgentProgress::ToolCallCompleted {
- call_id: "c1".to_string(),
- tool_name: "web_search".to_string(),
- success: true,
- output_chars: 7,
- output: "results".to_string(),
- arguments: Some(serde_json::json!({"query": "weather"})),
- elapsed_ms: 40,
- iteration: 1,
- failure: None,
- display_label: None,
- display_detail: None,
- structured: None,
- },
- 45,
- ),
- ]);
- c.finish(50);
- let tool = find(c.spans(), "tool.web_search");
- assert!(
- tool.input
- .as_ref()
- .expect("tool input backfilled from completion")
- .to_string()
- .contains("weather"),
- "arguments from the completion event must backfill the span input"
- );
- assert_eq!(
- tool.output,
- Some(serde_json::Value::String("results".to_string()))
- );
-}
-
-#[test]
-fn subagent_span_records_prompt_and_final_output_when_capture_on() {
- let mut c = collect_with_capture(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("task-1", "Researcher"), 5),
- (
- AgentProgress::SubagentCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- elapsed_ms: 100,
- iterations: 2,
- output_chars: 12,
- usage: None,
- output: "final answer".to_string(),
- worktree_path: None,
- changed_files: vec![],
- dirty_status: None,
- stop: None,
- },
- 105,
- ),
- ]);
- c.finish(110);
- let sub = find(c.spans(), "subagent.Researcher");
- assert_eq!(
- sub.input,
- Some(serde_json::Value::String("delegated prompt".to_string()))
- );
- assert_eq!(
- sub.output,
- Some(serde_json::Value::String("final answer".to_string()))
- );
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs
deleted file mode 100644
index 9620e6b68e..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-use super::*;
-
-#[test]
-fn subagent_content_is_withheld_when_capture_off() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("task-1", "Researcher"), 5),
- (
- AgentProgress::SubagentCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- elapsed_ms: 100,
- iterations: 2,
- output_chars: 12,
- usage: None,
- output: "final answer".to_string(),
- worktree_path: None,
- changed_files: vec![],
- dirty_status: None,
- stop: None,
- },
- 105,
- ),
- ]);
- c.finish(110);
- let sub = find(c.spans(), "subagent.Researcher");
- assert!(sub.input.is_none());
- assert!(sub.output.is_none());
-}
-
-#[test]
-fn turn_content_respects_the_trace_context_capture_gate() {
- // Regression (PR #4506 review): the collector briefly carried TWO capture
- // gates — a collector-level flag (checked by the TurnContent arm) and the
- // TraceContext flag (checked everywhere else). The web progress bridge only
- // sets the TraceContext flag, so TurnContent silently dropped the turn's
- // prompt/reply even with capture_content enabled. There is now a single
- // gate: both construction styles must attach TurnContent.
- for collector in [
- SpanCollector::new(ctx().with_capture_content(true)),
- SpanCollector::new(ctx()).with_content_capture(true),
- ] {
- let mut c = collector;
- c.record(&AgentProgress::TurnStarted, 0);
- c.record(
- &AgentProgress::TurnContent {
- input: Some("the prompt".to_string()),
- output: Some("the reply".to_string()),
- },
- 5,
- );
- c.finish(10);
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.input,
- Some(serde_json::Value::String("the prompt".to_string()))
- );
- assert_eq!(
- turn.output,
- Some(serde_json::Value::String("the reply".to_string()))
- );
- }
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
deleted file mode 100644
index c7e508662f..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
+++ /dev/null
@@ -1,620 +0,0 @@
-use super::*;
-
-use crate::core::observability::progress_tracing::export::export_spans;
-use tinyagents_harness::observability::trace_export::serialize::SpanEnvelope;
-use tinyagents_harness::observability::trace_export::SpanKind;
-// ── config ────────────────────────────────────────────────────────────────
-
-#[test]
-fn local_tracing_exporter_is_off_by_default() {
- let cfg = AgentTracingConfig::default();
- assert!(!cfg.enabled, "local exporter is opt-in");
- assert_eq!(cfg.backend, AgentTracingBackend::Otel);
- assert!(cfg.export_path.is_none());
-}
-
-#[test]
-fn observability_default_shares_usage_but_keeps_local_exporter_off() {
- let obs = ObservabilityConfig::default();
- assert!(obs.share_usage_data, "usage-data sharing is on by default");
- assert!(!obs.agent_tracing.enabled, "local exporter stays opt-in");
-}
-
-#[test]
-fn tracing_config_round_trips_through_json() {
- let cfg = AgentTracingConfig {
- enabled: true,
- backend: AgentTracingBackend::Langfuse,
- export_path: Some("/tmp/spans.ndjson".to_string()),
- capture_content: false,
- };
- let s = serde_json::to_string(&cfg).unwrap();
- let back: AgentTracingConfig = serde_json::from_str(&s).unwrap();
- assert!(back.enabled);
- assert_eq!(back.backend, AgentTracingBackend::Langfuse);
- assert_eq!(back.export_path.as_deref(), Some("/tmp/spans.ndjson"));
- // lowercase serde rename.
- assert!(s.contains("\"langfuse\""));
-}
-
-#[test]
-fn full_turn_builds_correlated_span_tree() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 5,
- },
- 1_010,
- ),
- (tool_started("call-1", "web_search", 1), 1_020),
- (
- tool_completed("call-1", "web_search", true, 321, 200),
- 1_020,
- ),
- (
- AgentProgress::TurnCostUpdated {
- model: "claude-opus-4-8".to_string(),
- iteration: 1,
- input_tokens: 1_200,
- output_tokens: 480,
- cached_input_tokens: 64,
- total_usd: 0.042,
- },
- 1_030,
- ),
- (
- AgentProgress::TurnCompleted {
- iterations: 1,
- stop: None,
- },
- 1_040,
- ),
- ]);
- c.finish(2_000);
- let spans = c.spans();
-
- // Root turn: trace = session id, user attribution present.
- let turn = find(spans, "agent.turn");
- assert_eq!(turn.kind, SpanKind::Turn);
- assert_eq!(turn.trace_id, "sess-42");
- assert!(turn.parent_span_id.is_none());
- assert_eq!(turn.attributes["session.id"], serde_json::json!("sess-42"));
- assert_eq!(turn.attributes["user.id"], serde_json::json!("client-7"));
- // Cost / usage attributes ride on the root.
- assert_eq!(
- turn.attributes["gen_ai.usage.input_tokens"],
- serde_json::json!(1_200)
- );
- assert_eq!(
- turn.attributes["gen_ai.usage.output_tokens"],
- serde_json::json!(480)
- );
- assert_eq!(
- turn.attributes["gen_ai.usage.cached_input_tokens"],
- serde_json::json!(64)
- );
- assert_eq!(
- turn.attributes["gen_ai.request.model"],
- serde_json::json!("claude-opus-4-8")
- );
- assert_eq!(turn.attributes["agent.iterations"], serde_json::json!(1));
- assert_eq!(turn.status, SpanStatus::Ok);
- assert!(turn.attributes.contains_key("gen_ai.usage.cost_usd"));
-
- // Iteration parented to the turn.
- let iter = find(spans, "agent.iteration#1");
- assert_eq!(iter.kind, SpanKind::Iteration);
- assert_eq!(iter.parent_span_id.as_deref(), Some(turn.span_id.as_str()));
- assert_eq!(
- iter.attributes["agent.max_iterations"],
- serde_json::json!(5)
- );
-
- // Tool parented to the iteration.
- let tool = find(spans, "tool.web_search");
- assert_eq!(tool.kind, SpanKind::Tool);
- assert_eq!(tool.parent_span_id.as_deref(), Some(iter.span_id.as_str()));
- assert_eq!(tool.status, SpanStatus::Ok);
- assert_eq!(tool.attributes["tool.output_chars"], serde_json::json!(321));
- // end = start + elapsed_ms.
- assert_eq!(tool.duration_ms(), Some(200));
-
- // Everything sealed.
- assert!(spans.iter().all(|s| s.end_unix_ms.is_some()));
-}
-
-#[test]
-fn failed_tool_marks_error_status() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 3,
- },
- 1,
- ),
- (tool_started("c1", "shell", 1), 2),
- (tool_completed("c1", "shell", false, 12, 5), 2),
- ]);
- c.finish(100);
- let tool = find(c.spans(), "tool.shell");
- assert_eq!(tool.status, SpanStatus::Error);
- assert_eq!(tool.attributes["tool.success"], serde_json::json!(false));
-}
-
-#[test]
-fn iteration_started_closes_the_previous_iteration() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 3,
- },
- 10,
- ),
- (
- AgentProgress::IterationStarted {
- iteration: 2,
- max_iterations: 3,
- },
- 20,
- ),
- ]);
- let first = find(c.spans(), "agent.iteration#1");
- assert_eq!(
- first.end_unix_ms,
- Some(20),
- "iter#1 closes when iter#2 opens"
- );
- let second = find(c.spans(), "agent.iteration#2");
- assert!(
- second.end_unix_ms.is_none(),
- "iter#2 still open until finish"
- );
-}
-
-#[test]
-fn subagent_lifecycle_nests_under_the_turn() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 5,
- },
- 5,
- ),
- (spawn("task-1", "Researcher"), 10),
- (
- AgentProgress::SubagentIterationStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- iteration: 1,
- max_iterations: 8,
- extended_policy: true,
- },
- 20,
- ),
- (
- AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "read_file".to_string(),
- arguments: serde_json::Value::Null,
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 30,
- ),
- (
- AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "read_file".to_string(),
- success: true,
- output_chars: 99,
- output: "file contents".to_string(),
- arguments: None,
- elapsed_ms: 40,
- iteration: 1,
- failure: None,
- display_label: None,
- display_detail: None,
- structured: None,
- },
- 30,
- ),
- (
- AgentProgress::SubagentCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- elapsed_ms: 500,
- iterations: 3,
- output_chars: 1024,
- usage: None,
- output: String::new(),
- worktree_path: Some("/private/should/not/leak".to_string()),
- changed_files: vec!["secret_file.rs".to_string()],
- dirty_status: Some(true),
- stop: None,
- },
- 40,
- ),
- ]);
- c.finish(1_000);
- let spans = c.spans();
-
- let iter = find(spans, "agent.iteration#1");
- let sub = find(spans, "subagent.Researcher");
- assert_eq!(sub.kind, SpanKind::Subagent);
- assert_eq!(sub.parent_span_id.as_deref(), Some(iter.span_id.as_str()));
- assert_eq!(
- sub.attributes["subagent.task_id"],
- serde_json::json!("task-1")
- );
- assert_eq!(sub.attributes["subagent.iterations"], serde_json::json!(3));
- assert_eq!(
- sub.attributes["subagent.output_chars"],
- serde_json::json!(1024)
- );
- assert_eq!(sub.duration_ms(), Some(500));
-
- let child_iter = find(spans, "subagent.iteration#1");
- assert_eq!(child_iter.kind, SpanKind::SubagentIteration);
- assert_eq!(
- child_iter.parent_span_id.as_deref(),
- Some(sub.span_id.as_str())
- );
- assert_eq!(
- child_iter.attributes["agent.extended_policy"],
- serde_json::json!(true)
- );
-
- let child_tool = find(spans, "tool.read_file");
- assert_eq!(
- child_tool.parent_span_id.as_deref(),
- Some(child_iter.span_id.as_str())
- );
- assert_eq!(child_tool.status, SpanStatus::Ok);
-
- // Worktree paths / changed file names must never be exported.
- let blob = serde_json::to_string(spans).unwrap();
- assert!(!blob.contains("should/not/leak"));
- assert!(!blob.contains("secret_file.rs"));
-}
-
-#[test]
-fn subagent_failure_records_error_without_raw_text() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("task-9", "Coder"), 5),
- (
- AgentProgress::SubagentFailed {
- agent_id: "coder".to_string(),
- task_id: "task-9".to_string(),
- error: "API key sk-secret-123 leaked in stacktrace".to_string(),
- },
- 10,
- ),
- ]);
- c.finish(50);
- let sub = find(c.spans(), "subagent.Coder");
- assert_eq!(sub.status, SpanStatus::Error);
- assert_eq!(sub.attributes["error"], serde_json::json!(true));
- assert!(sub.attributes.contains_key("error.length"));
-
- let blob = serde_json::to_string(c.spans()).unwrap();
- assert!(
- !blob.contains("sk-secret-123"),
- "raw error text must not leak"
- );
-}
-
-#[test]
-fn unknown_subagent_task_ids_are_ignored() {
- // Completion/tool events with no matching spawn must not panic or spawn.
- let mut c = SpanCollector::new(ctx());
- c.record(&AgentProgress::TurnStarted, 0);
- c.record(
- &AgentProgress::SubagentCompleted {
- agent_id: "x".to_string(),
- task_id: "ghost".to_string(),
- elapsed_ms: 1,
- iterations: 1,
- output_chars: 1,
- usage: None,
- output: String::new(),
- worktree_path: None,
- changed_files: vec![],
- dirty_status: None,
- stop: None,
- },
- 10,
- );
- // Only the turn span exists.
- assert_eq!(names(c.spans()), vec!["agent.turn".to_string()]);
-}
-
-// ── privacy ─────────────────────────────────────────────────────────────────
-
-#[test]
-fn content_bearing_events_produce_no_spans_and_no_leak() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::TextDelta {
- delta: "TOP-SECRET-REPLY".to_string(),
- iteration: 1,
- },
- 1,
- ),
- (
- AgentProgress::ThinkingDelta {
- delta: "secret reasoning".to_string(),
- iteration: 1,
- },
- 2,
- ),
- (
- AgentProgress::ToolCallArgsDelta {
- call_id: "c".to_string(),
- tool_name: "shell".to_string(),
- delta: "rm -rf /secret".to_string(),
- iteration: 1,
- },
- 3,
- ),
- ]);
- // Only the lazily-opened turn span, nothing from the deltas.
- assert_eq!(names(c.spans()), vec!["agent.turn".to_string()]);
- let blob = serde_json::to_string(c.spans()).unwrap();
- assert!(!blob.contains("TOP-SECRET-REPLY"));
- assert!(!blob.contains("secret reasoning"));
- assert!(!blob.contains("rm -rf"));
-}
-
-#[test]
-fn tool_arguments_are_never_serialized() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (tool_started("c1", "shell", 1), 1),
- ]);
- c.finish(10);
- let blob = serde_json::to_string(c.spans()).unwrap();
- assert!(
- !blob.contains("do-not-export"),
- "tool args must not be exported"
- );
-}
-
-// ── lazy root + finish ──────────────────────────────────────────────────────
-
-#[test]
-fn first_event_lazily_opens_the_turn_span() {
- // Stream that begins mid-flight (no TurnStarted) still correlates.
- let mut c = SpanCollector::new(ctx());
- c.record(
- &AgentProgress::IterationStarted {
- iteration: 4,
- max_iterations: 9,
- },
- 100,
- );
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(turn.trace_id, "sess-42");
- let iter = find(c.spans(), "agent.iteration#4");
- assert_eq!(iter.parent_span_id.as_deref(), Some(turn.span_id.as_str()));
-}
-
-#[test]
-fn finish_seals_all_open_spans_idempotently() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 2,
- },
- 5,
- ),
- (tool_started("c1", "x", 1), 6),
- ]);
- assert!(c.spans().iter().any(|s| s.end_unix_ms.is_none()));
- c.finish(99);
- assert!(c.spans().iter().all(|s| s.end_unix_ms.is_some()));
- // idempotent.
- c.finish(200);
- assert!(c
- .spans()
- .iter()
- .all(|s| s.end_unix_ms == Some(s.end_unix_ms.unwrap())));
-}
-
-#[test]
-fn cost_update_before_turn_start_lazily_opens_root() {
- let mut c = SpanCollector::new(ctx());
- c.record(
- &AgentProgress::TurnCostUpdated {
- model: "m".to_string(),
- iteration: 1,
- input_tokens: 10,
- output_tokens: 5,
- cached_input_tokens: 0,
- total_usd: 0.001,
- },
- 100,
- );
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.attributes["gen_ai.usage.input_tokens"],
- serde_json::json!(10)
- );
-}
-
-#[test]
-fn no_user_attribution_omits_user_id() {
- let mut c = SpanCollector::new(TraceContext::new("anon-1", None));
- c.record(&AgentProgress::TurnStarted, 0);
- let turn = find(c.spans(), "agent.turn");
- assert!(!turn.attributes.contains_key("user.id"));
- assert_eq!(turn.attributes["session.id"], serde_json::json!("anon-1"));
-}
-
-#[test]
-fn export_disabled_is_a_noop_and_writes_nothing() {
- let dir = std::env::temp_dir().join(format!("oh-trace-noop-{}", std::process::id()));
- let _ = std::fs::create_dir_all(&dir);
- let path = dir.join("spans.ndjson");
- let cfg = AgentTracingConfig {
- enabled: false,
- backend: AgentTracingBackend::Otel,
- export_path: Some(path.to_string_lossy().to_string()),
- capture_content: false,
- };
- export_spans(&cfg, &one_turn_spans());
- assert!(
- !path.exists(),
- "disabled tracing must not create the export file"
- );
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-#[test]
-fn export_appends_ndjson_to_the_configured_file() {
- let dir = std::env::temp_dir().join(format!("oh-trace-export-{}", std::process::id()));
- let _ = std::fs::create_dir_all(&dir);
- let path = dir.join("spans.ndjson");
- let cfg = AgentTracingConfig {
- enabled: true,
- backend: AgentTracingBackend::Otel,
- export_path: Some(path.to_string_lossy().to_string()),
- capture_content: false,
- };
- let spans = one_turn_spans();
- export_spans(&cfg, &spans);
- // Append, not truncate: a second export grows the file.
- export_spans(&cfg, &spans);
-
- let body = std::fs::read_to_string(&path).unwrap();
- assert_eq!(body.lines().count(), spans.len() * 2);
- // Each line is valid, parseable JSON.
- for line in body.lines() {
- let v: serde_json::Value = serde_json::from_str(line).unwrap();
- assert_eq!(v["trace_id"], serde_json::json!("sess-42"));
- }
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-#[test]
-fn export_with_no_path_does_not_panic() {
- // Path-less export logs instead of writing; must be safe to call.
- let cfg = AgentTracingConfig {
- enabled: true,
- backend: AgentTracingBackend::Langfuse,
- export_path: None,
- capture_content: false,
- };
- export_spans(&cfg, &one_turn_spans());
- export_spans(&cfg, &[]); // empty slice short-circuits.
-}
-
-#[tokio::test]
-async fn export_run_trace_is_noop_when_disabled_or_empty() {
- // Both sharing AND the local exporter off → no-op regardless of spans.
- let mut disabled = crate::config::Config::default();
- disabled.observability.share_usage_data = false;
- disabled.observability.agent_tracing.enabled = false;
- export_run_trace(&disabled, &one_turn_spans()).await;
-
- // No spans → no-op even with sharing on (the default).
- let enabled = crate::config::Config::default();
- export_run_trace(&enabled, &[]).await;
-}
-
-#[tokio::test]
-async fn export_run_trace_otel_backend_uses_local_sink() {
- // The Otel local exporter never touches the network — it writes the
- // file/log sink. Disable usage-data sharing to isolate that path (no push).
- let dir = std::env::temp_dir().join(format!("oh-trace-{}", std::process::id()));
- let _ = std::fs::create_dir_all(&dir);
- let path = dir.join("spans.ndjson");
-
- let mut config = crate::config::Config::default();
- config.observability.share_usage_data = false;
- config.observability.agent_tracing = AgentTracingConfig {
- enabled: true,
- backend: AgentTracingBackend::Otel,
- export_path: Some(path.to_string_lossy().to_string()),
- capture_content: false,
- };
- export_run_trace(&config, &one_turn_spans()).await;
-
- let written = std::fs::read_to_string(&path).expect("otel export should write the file");
- assert!(
- !written.trim().is_empty(),
- "spans should be appended locally"
- );
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-// ── Route A: content + grouping + span-id uniqueness ────────────────────────
-
-#[test]
-fn turn_content_attaches_input_output_to_turn_span_when_capture_enabled() {
- // Content lands on the span ONLY when capture is opted in (#4454).
- let mut c = SpanCollector::new(ctx()).with_content_capture(true);
- c.record(&AgentProgress::TurnStarted, 1_000);
- c.record(
- &AgentProgress::TurnContent {
- input: Some("what is your favorite color?".to_string()),
- output: Some("i'm partial to teal".to_string()),
- },
- 1_100,
- );
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.input.as_ref().and_then(|v| v.as_str()),
- Some("what is your favorite color?"),
- "TurnContent input must land on the turn span when capture_content=true"
- );
- assert_eq!(
- turn.output.as_ref().and_then(|v| v.as_str()),
- Some("i'm partial to teal")
- );
-}
-
-#[test]
-fn turn_span_stamps_user_and_thread_grouping_attributes() {
- let mut c = SpanCollector::new(
- TraceContext::new("trace:req-1", Some("client-7".to_string()))
- .with_session_group("thread-abc"),
- );
- c.record(&AgentProgress::TurnStarted, 1_000);
- let turn = find(c.spans(), "agent.turn");
- assert_eq!(
- turn.attributes.get("user.id").and_then(|v| v.as_str()),
- Some("client-7")
- );
- assert_eq!(
- turn.attributes.get("thread.id").and_then(|v| v.as_str()),
- Some("thread-abc"),
- "session_group must be stamped as thread.id for the Langfuse sessionId"
- );
-}
-
-#[test]
-fn envelope_for_maps_configured_backend() {
- use crate::core::observability::progress_tracing::export::envelope_for;
- assert_eq!(envelope_for(AgentTracingBackend::Otel), SpanEnvelope::Otel);
- assert_eq!(
- envelope_for(AgentTracingBackend::Langfuse),
- SpanEnvelope::Langfuse
- );
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_stop_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_stop_tests.rs
deleted file mode 100644
index 6e9b8a24e6..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_stop_tests.rs
+++ /dev/null
@@ -1,221 +0,0 @@
-//! Turns and sub-agents the harness stopped early (failure breaker, deadline
-//! wind-down, iteration cap) reach the normal completion path. Their spans
-//! must still say so: `WARNING` level, a content-free status message and
-//! `turn.stop_*` attributes, so a level filter finds them.
-
-use super::*;
-
-use tinyagents_harness::observability::trace_export::otlp::otlp_requests;
-use tinyagents_harness::observability::trace_export::SpanStatus;
-use tinyagents_harness::turn_stop::TurnStop;
-
-const BREAKER_NOTE: &str = "Stopping after 2 attempt(s): failure class \
- `uncertain_side_effect` still blocks operation `web_answer_tool` on \
- `https://example.com/a`. Resolve this blocker before retrying.";
-
-fn attr<'a>(span: &'a TraceSpan, key: &str) -> Option<&'a str> {
- span.attributes.get(key).and_then(|value| value.as_str())
-}
-
-fn root(spans: &[TraceSpan]) -> &TraceSpan {
- spans
- .iter()
- .find(|span| span.parent_span_id.is_none())
- .expect("turn span")
-}
-
-fn exported_level(spans: &[TraceSpan], name: &str) -> Option<String> {
- let payloads = otlp_requests(
- spans,
- "production",
- &crate::core::observability::progress_tracing::export_brand(),
- );
- payloads
- .iter()
- .flat_map(|payload| {
- payload["resourceSpans"][0]["scopeSpans"][0]["spans"]
- .as_array()
- .cloned()
- .unwrap_or_default()
- })
- .find(|span| span["name"] == name)
- .and_then(|span| {
- span["attributes"]
- .as_array()
- .unwrap()
- .iter()
- .find(|item| item["key"] == "langfuse.observation.level")
- .and_then(|item| item["value"]["stringValue"].as_str())
- .map(str::to_string)
- })
-}
-
-#[test]
-fn a_breaker_stopped_turn_closes_at_warning_with_stop_attributes() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::TurnCompleted {
- iterations: 4,
- stop: Some(tinyagents_harness::TurnStop::breaker_with_cause(
- BREAKER_NOTE,
- tinyagents_harness::TurnFailureClass::new("uncertain_side_effect"),
- Some("web_answer_tool".to_owned()),
- )),
- },
- 50,
- ),
- ]);
- c.finish(50);
- let spans = c.into_spans();
- let turn = root(&spans);
- assert_ne!(
- turn.status,
- SpanStatus::Error,
- "a stop is not a harness error"
- );
- assert_ne!(
- turn.status,
- SpanStatus::Ok,
- "a stop is not a clean completion"
- );
- assert_eq!(attr(turn, "observation.level"), Some("WARNING"));
- assert_eq!(attr(turn, "turn.outcome"), Some("stopped"));
- assert_eq!(attr(turn, "turn.stop_kind"), Some("breaker"));
- assert_eq!(attr(turn, "turn.stop_class"), Some("uncertain_side_effect"));
- assert_eq!(attr(turn, "turn.stop_operation"), Some("web_answer_tool"));
- let message = "stopped: breaker uncertain_side_effect on web_answer_tool";
- assert_eq!(attr(turn, "observation.status_message"), Some(message));
- // The OTLP converter reads the Langfuse statusMessage from `error.message`.
- assert_eq!(attr(turn, "error.message"), Some(message));
- assert_eq!(
- turn.attributes.get("agent.iterations"),
- Some(&serde_json::json!(4))
- );
- assert_eq!(
- exported_level(&spans, &turn.name).as_deref(),
- Some("WARNING"),
- "the OTLP export must carry the WARNING level"
- );
-}
-
-#[test]
-fn a_wind_down_or_capped_turn_is_stopped_too() {
- for (stop, kind) in [
- (TurnStop::wind_down(), "wind_down"),
- (TurnStop::iteration_cap(), "iteration_cap"),
- ] {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::TurnCompleted {
- iterations: 2,
- stop: Some(stop),
- },
- 10,
- ),
- ]);
- c.finish(10);
- let spans = c.into_spans();
- let turn = root(&spans);
- assert_eq!(attr(turn, "observation.level"), Some("WARNING"), "{kind}");
- assert_eq!(attr(turn, "turn.stop_kind"), Some(kind));
- assert_eq!(attr(turn, "turn.stop_class"), None);
- assert_eq!(
- attr(turn, "observation.status_message").map(str::to_string),
- Some(format!("stopped: {kind}"))
- );
- }
-}
-
-#[test]
-fn a_turn_that_finished_on_its_own_stays_completed() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::TurnCompleted {
- iterations: 1,
- stop: None,
- },
- 10,
- ),
- ]);
- c.finish(10);
- let spans = c.into_spans();
- let turn = root(&spans);
- assert_eq!(turn.status, SpanStatus::Ok);
- assert_eq!(attr(turn, "turn.outcome"), Some("completed"));
- assert_eq!(attr(turn, "observation.level"), None);
- assert_eq!(attr(turn, "turn.stop_kind"), None);
-}
-
-fn subagent_completed(task: &str, stop: Option<TurnStop>) -> AgentProgress {
- AgentProgress::SubagentCompleted {
- agent_id: "researcher".to_string(),
- task_id: task.to_string(),
- elapsed_ms: 30,
- iterations: 3,
- output_chars: 10,
- output: "partial".to_string(),
- usage: None,
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- stop,
- }
-}
-
-#[test]
-fn a_stopped_subagent_span_closes_at_warning_with_stop_attributes() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("t-stop", "Research"), 5),
- (
- subagent_completed(
- "t-stop",
- Some(tinyagents_harness::TurnStop::breaker_with_cause(
- BREAKER_NOTE,
- tinyagents_harness::TurnFailureClass::new("uncertain_side_effect"),
- Some("web_answer_tool".to_owned()),
- )),
- ),
- 40,
- ),
- ]);
- c.finish(50);
- let spans = c.into_spans();
- let sub = find(&spans, "subagent.Research");
- assert_ne!(
- sub.status,
- SpanStatus::Ok,
- "a stopped child is not a clean finish"
- );
- assert_eq!(attr(sub, "observation.level"), Some("WARNING"));
- assert_eq!(attr(sub, "turn.outcome"), Some("stopped"));
- assert_eq!(attr(sub, "turn.stop_kind"), Some("breaker"));
- assert_eq!(attr(sub, "turn.stop_class"), Some("uncertain_side_effect"));
- assert_eq!(attr(sub, "turn.stop_operation"), Some("web_answer_tool"));
- assert_eq!(
- attr(sub, "observation.status_message"),
- Some("stopped: breaker uncertain_side_effect on web_answer_tool")
- );
- assert_eq!(
- exported_level(&spans, "subagent.Research").as_deref(),
- Some("WARNING")
- );
-}
-
-#[test]
-fn a_subagent_that_finished_normally_stays_ok() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (spawn("t-ok", "Research"), 5),
- (subagent_completed("t-ok", None), 40),
- ]);
- c.finish(50);
- let spans = c.into_spans();
- let sub = find(&spans, "subagent.Research");
- assert_eq!(sub.status, SpanStatus::Ok);
- assert_eq!(attr(sub, "observation.level"), None);
- assert_eq!(attr(sub, "turn.stop_kind"), None);
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs
deleted file mode 100644
index 033ae117d3..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs
+++ /dev/null
@@ -1,165 +0,0 @@
-//! Unit tests for the structured tracing export (issue #3886).
-
-use super::*;
-use crate::config::schema::{AgentTracingBackend, AgentTracingConfig, ObservabilityConfig};
-use crate::progress::AgentProgress;
-
-fn ctx() -> TraceContext {
- TraceContext::new("sess-42", Some("client-7".to_string()))
-}
-
-fn collect(events: &[(AgentProgress, u64)]) -> SpanCollector {
- let mut c = SpanCollector::new(ctx());
- for (event, ts) in events {
- c.record(event, *ts);
- }
- c
-}
-
-fn find<'a>(spans: &'a [TraceSpan], name: &str) -> &'a TraceSpan {
- spans
- .iter()
- .find(|s| s.name == name)
- .unwrap_or_else(|| panic!("no span named {name:?} in {:?}", names(spans)))
-}
-
-fn names(spans: &[TraceSpan]) -> Vec<String> {
- spans.iter().map(|s| s.name.clone()).collect()
-}
-
-// ── parent turn ─────────────────────────────────────────────────────────────
-
-fn tool_started(call_id: &str, tool: &str, iter: u32) -> AgentProgress {
- AgentProgress::ToolCallStarted {
- call_id: call_id.to_string(),
- tool_name: tool.to_string(),
- arguments: serde_json::json!({"secret": "do-not-export"}),
- iteration: iter,
- display_label: None,
- display_detail: None,
- }
-}
-
-fn tool_completed(
- call_id: &str,
- tool: &str,
- success: bool,
- chars: usize,
- elapsed: u64,
-) -> AgentProgress {
- AgentProgress::ToolCallCompleted {
- call_id: call_id.to_string(),
- tool_name: tool.to_string(),
- success,
- output_chars: chars,
- output: String::new(),
- arguments: None,
- elapsed_ms: elapsed,
- iteration: 1,
- failure: None,
- display_label: None,
- display_detail: None,
- structured: None,
- }
-}
-
-// ── subagents ───────────────────────────────────────────────────────────────
-
-fn spawn(task: &str, display: &str) -> AgentProgress {
- AgentProgress::SubagentSpawned {
- agent_id: "researcher".to_string(),
- task_id: task.to_string(),
- mode: "typed".to_string(),
- dedicated_thread: true,
- prompt_chars: 256,
- prompt: "delegated prompt".to_string(),
- worker_thread_id: Some("worker-abc".to_string()),
- display_name: Some(display.to_string()),
- parent_call_id: None,
- }
-}
-
-// ── serialization + export ──────────────────────────────────────────────────
-
-fn one_turn_spans() -> Vec<TraceSpan> {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::TurnCompleted {
- iterations: 1,
- stop: None,
- },
- 10,
- ),
- ]);
- c.finish(10);
- c.into_spans()
-}
-
-// ── per-call generations + provenance + reasoning/cache-write usage ─────────
-
-fn model_call(model: &str, reasoning: u64, cache_write: u64) -> AgentProgress {
- AgentProgress::ModelCallCompleted {
- model: model.to_string(),
- provider_id: "managed".to_string(),
- subagent_task_id: None,
- input: None,
- output: None,
- iteration: 1,
- input_tokens: 1_000,
- output_tokens: 200,
- cached_input_tokens: 300,
- cache_creation_tokens: cache_write,
- reasoning_tokens: reasoning,
- cost_usd: Some(0.0042),
- }
-}
-
-// ── content-bearing wiring (system prompt / tool IO / subagent IO) ──────────
-
-fn capture_ctx() -> TraceContext {
- ctx().with_capture_content(true)
-}
-
-fn collect_with_capture(events: &[(AgentProgress, u64)]) -> SpanCollector {
- let mut c = SpanCollector::new(capture_ctx());
- for (event, ts) in events {
- c.record(event, *ts);
- }
- c
-}
-
-fn model_call_with_content(subagent_task_id: Option<&str>) -> AgentProgress {
- AgentProgress::ModelCallCompleted {
- model: "chat-v1".to_string(),
- provider_id: "managed".to_string(),
- subagent_task_id: subagent_task_id.map(str::to_string),
- input: Some(serde_json::json!([
- {"role": "system", "content": "You are OpenHuman."},
- {"role": "user", "content": "hi"}
- ])),
- output: Some(serde_json::json!({"role": "assistant", "content": "hello"})),
- iteration: 1,
- input_tokens: 100,
- output_tokens: 10,
- cached_input_tokens: 0,
- cache_creation_tokens: 0,
- reasoning_tokens: 0,
- cost_usd: Some(0.001),
- }
-}
-
-#[path = "progress_tracing_accuracy_tests.rs"]
-mod accuracy_tests;
-#[path = "progress_tracing_attribution_tests.rs"]
-mod attribution_tests;
-#[path = "progress_tracing_content_gate_tests.rs"]
-mod content_gate_tests;
-#[path = "progress_tracing_span_tree_tests.rs"]
-mod span_tree_tests;
-#[path = "progress_tracing_stop_tests.rs"]
-mod stop_tests;
-#[path = "progress_tracing_tool_span_tests.rs"]
-mod tool_span_tests;
-#[path = "progress_tracing_ttft_tests.rs"]
-mod ttft_tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tool_span_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tool_span_tests.rs
deleted file mode 100644
index f0e8548409..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tool_span_tests.rs
+++ /dev/null
@@ -1,197 +0,0 @@
-//! Tool-span attributes: the classified failure class and the model whose
-//! call requested the tool.
-
-use super::*;
-
-// ── tool spans: failure class + model attribution ───────────────────────────
-
-fn failed_tool_completed(call_id: &str, tool: &str, output: &str) -> AgentProgress {
- AgentProgress::ToolCallCompleted {
- call_id: call_id.to_string(),
- tool_name: tool.to_string(),
- success: false,
- output_chars: output.chars().count(),
- output: output.to_string(),
- arguments: None,
- elapsed_ms: 5,
- iteration: 1,
- failure: Some(tinytools::status::classify(output, false)),
- display_label: None,
- display_detail: None,
- structured: None,
- }
-}
-
-/// A plain non-zero command exit and a harness failure both close as an error
-/// span, so the class rides the span (content-free, so not gated on capture):
-/// it is what separates "the program exited 1" from "the harness failed" in
-/// Langfuse, and a plain exit is exported at WARNING instead of ERROR.
-#[test]
-fn failed_tool_span_carries_its_failure_class() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 3,
- },
- 1,
- ),
- (tool_started("c1", "shell", 1), 2),
- (
- failed_tool_completed(
- "c1",
- "shell",
- "Command failed (exit code 1)\n[stderr]\nollama: timed out",
- ),
- 3,
- ),
- (tool_started("c2", "shell", 1), 4),
- (
- failed_tool_completed(
- "c2",
- "shell",
- "invalid arguments for tool `shell`: missing `command`; expected schema: {}",
- ),
- 5,
- ),
- (tool_started("c3", "web_search", 1), 6),
- (tool_completed("c3", "web_search", true, 3, 1), 7),
- ]);
- c.finish(100);
- let class_of = |call: &str| {
- c.spans()
- .iter()
- .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
- .and_then(|s| s.attributes.get("tool.failure_class").cloned())
- };
- assert_eq!(class_of("c1"), Some(serde_json::json!("CommandFailed")));
- assert_eq!(class_of("c2"), Some(serde_json::json!("InvalidArguments")));
- assert_eq!(class_of("c3"), None, "a successful call carries no class");
- let level_of = |call: &str| {
- c.spans()
- .iter()
- .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
- .and_then(|s| s.attributes.get("observation.level").cloned())
- };
- // A program that exited non-zero exports at WARNING (Langfuse showed 27%
- // of `shell` calls as errors, ~70% of them ordinary non-zero exits); a
- // harness failure stays ERROR.
- assert_eq!(level_of("c1"), Some(serde_json::json!("WARNING")));
- assert_eq!(level_of("c2"), None);
-}
-
-/// Tool observations name the model whose call requested them, so tool errors
-/// correlate to a model without joining against the generation span.
-#[test]
-fn tool_spans_carry_the_model_that_requested_them() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 3,
- },
- 1,
- ),
- (tool_started("early", "shell", 1), 2),
- (tool_completed("early", "shell", true, 1, 1), 3),
- (model_call("chat-v1", 0, 0), 4),
- (tool_started("c1", "shell", 1), 5),
- (
- failed_tool_completed("c1", "shell", "Command failed (exit code 2)"),
- 6,
- ),
- (spawn("task-1", "Researcher"), 7),
- (
- AgentProgress::SubagentIterationStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- iteration: 1,
- max_iterations: 8,
- extended_policy: false,
- },
- 8,
- ),
- (
- AgentProgress::ModelCallCompleted {
- model: "scout-v2".to_string(),
- provider_id: "openai".to_string(),
- subagent_task_id: Some("task-1".to_string()),
- input: None,
- output: None,
- iteration: 1,
- input_tokens: 10,
- output_tokens: 1,
- cached_input_tokens: 0,
- cache_creation_tokens: 0,
- reasoning_tokens: 0,
- cost_usd: Some(0.0),
- },
- 9,
- ),
- (
- AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "file_read".to_string(),
- arguments: serde_json::Value::Null,
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 10,
- ),
- (
- AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "file_read".to_string(),
- success: false,
- output_chars: 0,
- output: String::new(),
- arguments: None,
- elapsed_ms: 1,
- iteration: 1,
- failure: Some(tinytools::status::classify(
- "Command failed (exit code 1)",
- false,
- )),
- display_label: None,
- display_detail: None,
- structured: None,
- },
- 11,
- ),
- (tool_started("c2", "shell", 2), 12),
- ]);
- c.finish(100);
- let attr = |call: &str, key: &str| {
- c.spans()
- .iter()
- .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
- .and_then(|s| s.attributes.get(key).cloned())
- };
- assert_eq!(attr("early", "tool.model"), None, "no model call seen yet");
- assert_eq!(
- attr("c1", "tool.model"),
- Some(serde_json::json!("managed.chat-v1"))
- );
- assert_eq!(
- attr("sc-1", "tool.model"),
- Some(serde_json::json!("openai.scout-v2")),
- "a child tool names the child's model, not the parent's"
- );
- assert_eq!(
- attr("sc-1", "tool.failure_class"),
- Some(serde_json::json!("CommandFailed")),
- "a child tool span carries its failure class too"
- );
- assert_eq!(
- attr("c2", "tool.model"),
- Some(serde_json::json!("managed.chat-v1")),
- "the parent keeps its own model after a child ran"
- );
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_ttft_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_ttft_tests.rs
deleted file mode 100644
index 1e10b61a32..0000000000
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_ttft_tests.rs
+++ /dev/null
@@ -1,153 +0,0 @@
-//! Time to first token on generation spans: when a streamed model call's first
-//! delta arrived, relative to the call's start, and its export to Langfuse.
-
-use super::*;
-
-use tinyagents_harness::observability::trace_export::otlp::otlp_requests;
-use tinyagents_harness::observability::trace_export::SpanKind;
-
-fn iteration(iteration: u32) -> AgentProgress {
- AgentProgress::IterationStarted {
- iteration,
- max_iterations: 15,
- }
-}
-
-fn thinking(iteration: u32) -> AgentProgress {
- AgentProgress::ThinkingDelta {
- delta: "…".to_string(),
- iteration,
- }
-}
-
-fn text(iteration: u32) -> AgentProgress {
- AgentProgress::TextDelta {
- delta: "Hi".to_string(),
- iteration,
- }
-}
-
-fn completed(iteration: u32) -> AgentProgress {
- AgentProgress::ModelCallCompleted {
- model: "chat-v1".to_string(),
- provider_id: "managed".to_string(),
- subagent_task_id: None,
- input: None,
- output: None,
- iteration,
- input_tokens: 100,
- output_tokens: 10,
- cached_input_tokens: 90,
- cache_creation_tokens: 0,
- reasoning_tokens: 5,
- cost_usd: Some(0.001),
- }
-}
-
-fn generations(spans: &[TraceSpan]) -> Vec<&TraceSpan> {
- spans
- .iter()
- .filter(|span| span.kind == SpanKind::Generation)
- .collect()
-}
-
-fn attr_u64(span: &TraceSpan, key: &str) -> Option<u64> {
- span.attributes.get(key).and_then(serde_json::Value::as_u64)
-}
-
-#[test]
-fn streamed_call_records_first_token_and_first_text() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (thinking(1), 1_300),
- (thinking(1), 1_400),
- (text(1), 1_800),
- (text(1), 1_900),
- (completed(1), 2_500),
- ]);
- let spans = c.spans();
- let generation = generations(spans)[0];
- assert_eq!(
- attr_u64(generation, "gen_ai.response.first_token_unix_ms"),
- Some(1_300)
- );
- assert_eq!(
- attr_u64(generation, "gen_ai.response.time_to_first_token_ms"),
- Some(300)
- );
- assert_eq!(
- attr_u64(generation, "gen_ai.response.time_to_first_text_ms"),
- Some(800)
- );
-}
-
-#[test]
-fn unary_call_carries_no_first_token_attributes() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (completed(1), 2_500),
- ]);
- let generation = generations(c.spans())[0];
- assert!(!generation
- .attributes
- .contains_key("gen_ai.response.first_token_unix_ms"));
- assert!(!generation
- .attributes
- .contains_key("gen_ai.response.time_to_first_text_ms"));
-}
-
-#[test]
-fn each_iteration_measures_its_own_first_token() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_000),
- (iteration(1), 1_000),
- (text(1), 1_200),
- (completed(1), 1_500),
- (iteration(2), 2_000),
- (text(2), 2_700),
- (completed(2), 3_000),
- ]);
- let spans = c.spans();
- let generations = generations(spans);
- assert_eq!(generations.len(), 2);
- assert_eq!(
- attr_u64(generations[0], "gen_ai.response.time_to_first_token_ms"),
- Some(200)
- );
- assert_eq!(
- attr_u64(generations[1], "gen_ai.response.time_to_first_token_ms"),
- Some(700)
- );
-}
-
-#[test]
-fn otlp_exports_completion_start_time_for_langfuse_ttft() {
- let c = collect(&[
- (AgentProgress::TurnStarted, 1_700_000_000_000),
- (iteration(1), 1_700_000_000_000),
- (text(1), 1_700_000_000_250),
- (completed(1), 1_700_000_001_000),
- ]);
- let spans = c.spans().to_vec();
- let payloads = otlp_requests(
- &spans,
- "production",
- &crate::core::observability::progress_tracing::export_brand(),
- );
- let exported = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]
- .as_array()
- .unwrap();
- let generation = exported
- .iter()
- .find(|span| span["name"] == "llm.chat-v1")
- .expect("generation span exported");
- let completion_start = generation["attributes"]
- .as_array()
- .unwrap()
- .iter()
- .find(|item| item["key"] == "langfuse.observation.completion_start_time")
- .and_then(|item| item["value"]["stringValue"].as_str());
- assert_eq!(completion_start, Some("2023-11-14T22:13:20.250Z"));
-}
diff --git a/crates/openhuman-core/src/web_chat/journal_shadow.rs b/crates/openhuman-core/src/web_chat/journal_shadow.rs
deleted file mode 100644
index fe16a4437c..0000000000
--- a/crates/openhuman-core/src/web_chat/journal_shadow.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-//! Journal-shadow parity: compare the live trace spans for a turn against the
-//! spans reprojected from the durable journal, and say what differs.
-//!
-//! Extracted from `progress_bridge` (openhuman#6419) — that file sits on a
-//! grandfathered line-limit ratchet in `scripts/ci/check-openhuman-rust-layout.mjs`,
-//! so this grew out of it rather than being trimmed to fit. The three functions
-//! here are one unit: build a comparable signature per span, diff two signature
-//! lists, and drive the comparison for one request.
-//!
-//! What the comparison means is documented on
-//! [`journal_projection`](crate::core::observability::progress_tracing::journal_projection):
-//! both sides fold through the same `SpanCollector`, so span-shape parity holds
-//! by construction and a divergence is a real gap rather than an artefact of
-//! comparing two different abstractions. The largest such gap today is that the
-//! crate journals no sub-agent events at all, so every delegating turn loses
-//! that subtree on replay.
-
-fn span_projection_signature(
- spans: &[tinyagents_harness::observability::trace_export::TraceSpan],
-) -> Vec<String> {
- spans
- .iter()
- .map(|span| {
- let attr_keys = span
- .attributes
- .keys()
- .map(String::as_str)
- .collect::<Vec<_>>()
- .join(",");
- format!(
- "{:?}|{}|{:?}|attrs:[{}]",
- span.kind, span.name, span.status, attr_keys
- )
- })
- .collect()
-}
-
-/// Summarise a signature mismatch as *what* differs, not how many.
-///
-/// The parity warning used to print two counts and two full signature vectors,
-/// which for a delegating turn meant ~64 and ~21 entries of `kind|name|status`
-/// on one line. That is a diff the reader has to do by eye, every turn, so the
-/// warning went unactioned for long enough to be filed as noise (#6419) when the
-/// signal was real: the journal carries no sub-agent events at all, so every
-/// delegating turn loses that whole subtree.
-///
-/// Spans are matched as a multiset by signature, so a span present twice live
-/// and once in the projection is reported as one missing occurrence rather than
-/// as identical. Names are truncated and the list is capped — this is a log
-/// line, and the point is to name the shape of the gap, not to reproduce it.
-fn describe_signature_divergence(live: &[String], projected: &[String]) -> String {
- fn counts(sigs: &[String]) -> std::collections::BTreeMap<&str, i64> {
- let mut out = std::collections::BTreeMap::new();
- for sig in sigs {
- *out.entry(sig.as_str()).or_insert(0) += 1;
- }
- out
- }
- let (live_counts, projected_counts) = (counts(live), counts(projected));
- let mut missing: Vec<String> = Vec::new();
- let mut extra: Vec<String> = Vec::new();
- for (sig, live_n) in &live_counts {
- let delta = live_n - projected_counts.get(sig).copied().unwrap_or(0);
- if delta > 0 {
- missing.push(format!(
- "{delta}x {}",
- sig.chars().take(70).collect::<String>()
- ));
- }
- }
- for (sig, projected_n) in &projected_counts {
- let delta = projected_n - live_counts.get(sig).copied().unwrap_or(0);
- if delta > 0 {
- extra.push(format!(
- "{delta}x {}",
- sig.chars().take(70).collect::<String>()
- ));
- }
- }
- const MAX: usize = 6;
- let render = |label: &str, mut items: Vec<String>| -> String {
- if items.is_empty() {
- return String::new();
- }
- let total = items.len();
- items.truncate(MAX);
- let more = total.saturating_sub(MAX);
- let suffix = if more > 0 {
- format!(" (+{more} more)")
- } else {
- String::new()
- };
- format!(" {label}=[{}]{suffix}", items.join("; "))
- };
- format!(
- "{}{}",
- render("live_only", missing),
- render("journal_only", extra)
- )
-}
-
-pub(super) async fn shadow_compare_journal_projection(
- ctx: &crate::core::runtime::DispatchCtx,
- request_id: &str,
- trace_ctx: tinyagents_harness::observability::trace_export::TraceContext,
- max_iterations: u32,
- live_spans: &[tinyagents_harness::observability::trace_export::TraceSpan],
-) -> Option<Vec<tinyagents_harness::observability::AgentObservation>> {
- let Some(journal_run_id) =
- crate::agent::tinyagents::journal::take_request_journal_run(ctx, request_id)
- else {
- log::debug!(
- "[agent-tracing][journal-shadow] no journal run registered request_id={}",
- request_id
- );
- return None;
- };
-
- let observations = match crate::agent::tinyagents::journal::read_run_events(
- ctx,
- &journal_run_id,
- 0,
- )
- .await
- {
- Ok(observations) => observations,
- Err(err) => {
- log::warn!(
- "[agent-tracing][journal-shadow] read failed request_id={} journal_run_id={} err={err}",
- request_id,
- journal_run_id
- );
- return None;
- }
- };
- if observations.is_empty() {
- log::warn!(
- "[agent-tracing][journal-shadow] journal empty request_id={} journal_run_id={}",
- request_id,
- journal_run_id
- );
- return None;
- }
-
- let projected =
- crate::core::observability::progress_tracing::journal_projection::spans_from_observations(
- trace_ctx,
- max_iterations,
- &observations,
- );
- let live_sig = span_projection_signature(live_spans);
- let projected_sig = span_projection_signature(&projected);
- if live_sig == projected_sig {
- log::debug!(
- "[agent-tracing][journal-shadow] parity ok request_id={} journal_run_id={} spans={} observations={}",
- request_id,
- journal_run_id,
- live_spans.len(),
- observations.len()
- );
- } else {
- log::warn!(
- "[agent-tracing][journal-shadow] parity divergence request_id={} journal_run_id={} live_spans={} journal_spans={} observations={}{}",
- request_id,
- journal_run_id,
- live_spans.len(),
- projected.len(),
- observations.len(),
- describe_signature_divergence(&live_sig, &projected_sig)
- );
- }
- Some(observations)
-}
-
-#[cfg(test)]
-#[path = "journal_shadow_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web_chat/journal_shadow_tests.rs b/crates/openhuman-core/src/web_chat/journal_shadow_tests.rs
deleted file mode 100644
index 4dc377fe70..0000000000
--- a/crates/openhuman-core/src/web_chat/journal_shadow_tests.rs
+++ /dev/null
@@ -1,73 +0,0 @@
-use super::describe_signature_divergence;
-
-/// #6419: the parity warning has to name *what* diverged.
-///
-/// These assert the rendered description, not that the two vectors differ —
-/// "they differ" is what the old warning already told us, every turn, for long
-/// enough that a true signal got filed as noise.
-#[test]
-fn divergence_description_names_the_spans_present_live_and_absent_in_the_journal() {
- let live = vec![
- "Turn|agent.turn:orchestrator|Ok|attrs:[a]".to_string(),
- "SubAgent|subagent:researcher|Ok|attrs:[b]".to_string(),
- "Tool|tool:file_read|Ok|attrs:[c]".to_string(),
- ];
- let projected = vec![
- "Turn|agent.turn:orchestrator|Ok|attrs:[a]".to_string(),
- "Tool|tool:file_read|Ok|attrs:[c]".to_string(),
- ];
-
- let described = describe_signature_divergence(&live, &projected);
- assert!(
- described.contains("live_only"),
- "a span present live and absent in the journal must be named: {described}"
- );
- assert!(
- described.contains("subagent:researcher"),
- "the missing span's identity is the whole point: {described}"
- );
- // The spans both sides agree on must NOT be listed — a description that
- // repeats the whole signature set is the blob this replaces.
- assert!(
- !described.contains("file_read"),
- "agreed spans must not be reported as divergent: {described}"
- );
- assert!(
- !described.contains("journal_only"),
- "nothing was projected that the live path lacked: {described}"
- );
-}
-
-#[test]
-fn divergence_description_counts_repeats_as_a_multiset() {
- // Three iterations live, one projected. Matching as sets would call these
- // "identical" and report nothing; the gap is two occurrences.
- let sig = "Iteration|agent.iteration|Ok|attrs:[i]".to_string();
- let live = vec![sig.clone(), sig.clone(), sig.clone()];
- let projected = vec![sig.clone()];
-
- let described = describe_signature_divergence(&live, &projected);
- assert!(
- described.contains("2x"),
- "two missing occurrences, not a set difference of zero: {described}"
- );
-}
-
-#[test]
-fn divergence_description_reports_journal_only_spans_too() {
- // The projection producing something the live path did not is a different
- // bug from the projection missing something, and must read differently.
- let live: Vec<String> = Vec::new();
- let projected = vec!["Tool|tool:ghost|Ok|attrs:[]".to_string()];
-
- let described = describe_signature_divergence(&live, &projected);
- assert!(described.contains("journal_only"), "{described}");
- assert!(!described.contains("live_only"), "{described}");
-}
-
-#[test]
-fn divergence_description_is_empty_when_the_two_agree() {
- let sig = vec!["Turn|agent.turn:orchestrator|Ok|attrs:[a]".to_string()];
- assert_eq!(describe_signature_divergence(&sig, &sig), "");
- assert_eq!(describe_signature_divergence(&[], &[]), "");
-}
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 1e3a8c90fb..c8b77a9ce6 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -30,7 +30,6 @@ mod channel_event;
mod egress_surface;
mod event_bus;
mod event_bus_channel;
-mod journal_shadow;
mod ops;
// Response delivery/segmentation for the web surface (folded in from the former
// standalone `presentation` provider — it is the web channel's delivery formatter).