The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(progress_tracing): correct OTLP serialization of empty attribute arrays
Steven Enamakel9d28f334f172
diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/ingestion_batch.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/ingestion_batch.rsdeleted file mode 100644index 8532ebf5dd..0000000000--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse/ingestion_batch.rs+++ /dev/null@@ -1,49 +0,0 @@-//! Shared ingestion-batch helpers: ISO timestamps, per-event ids, and the-//! 500-event chunking Langfuse imposes on a single ingestion request.--use serde_json::Value;--/// Epoch-milliseconds → RFC 3339 / ISO-8601 string (Langfuse requires ISO-/// timestamps, not epoch integers). Falls back to "now" only if the value is-/// somehow out of range — `start_unix_ms` comes from a monotonic wall clock so-/// this is defensive.-pub(super) fn iso_millis(unix_ms: u64) -> String {- chrono::DateTime::from_timestamp_millis(unix_ms as i64)- .unwrap_or_else(chrono::Utc::now)- .to_rfc3339()-}--/// Fresh per-event id. Langfuse dedupes ingestion events by this id, so it must-/// be unique per event (distinct from the observation/trace id in `body`).-pub(super) fn new_event_id() -> String {- uuid::Uuid::new_v4().to_string()-}--/// is explicitly enabled.-/// Langfuse rejects an ingestion request whose `batch` holds more than 500-/// events (`400 "Langfuse ingestion batch cannot exceed 500 events"`). Large-/// turns — especially ones that spawn sub-agents — routinely exceed this.-pub(super) const LANGFUSE_MAX_BATCH_EVENTS: usize = 500;--/// Split a `{"batch": [...]}` ingestion payload into multiple payloads, each-/// carrying at most `max` events and preserving any other top-level keys.-///-/// Langfuse dedupes ingestion events by id and resolves each observation to its-/// trace by `traceId`, so delivering one run's events across several requests is-/// safe (the `trace-create` event stays in the first chunk). A payload at or-/// under the limit — or without a `batch` array — passes through unchanged as a-/// single element.-pub(super) fn split_ingestion_batch(payload: Value, max: usize) -> Vec<Value> {- let events = match payload.get("batch").and_then(Value::as_array) {- Some(events) if max > 0 && events.len() > max => events.clone(),- _ => return vec![payload],- };- events- .chunks(max)- .map(|chunk| {- let mut part = payload.clone();- part["batch"] = Value::Array(chunk.to_vec());- part- })- .collect()-}diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp.rsindex d3bf808da4..a850ec2dae 100644--- a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/otlp.rs@@ -1,463 +1,18 @@//! 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::collections::{BTreeMap, HashMap};--use serde_json::{json, Value};-use sha2::{Digest, Sha256};+use serde_json::Value;+use tinyagents_harness::observability::trace_export::otlp::otlp_requests;+use tinyagents_harness::observability::trace_export::TraceSpan;use super::langfuse::{environment_for_base, ingestion_url, skip_push};-use super::types::{SpanKind, SpanStatus, TraceSpan};use crate::config::Config;use crate::security::credentials::jwt::bearer_authorization_value;use crate::security::credentials::session_support::direct_backend_credential;-// The backend JSON parser caps requests at 10 MiB. A generation can carry a-// 200 KiB structured prompt, so use a much smaller transport batch.-const MAX_SPANS_PER_REQUEST: usize = 20;-const MAX_REQUEST_BYTES: usize = 8_000_000;--fn hex_id(source: &str, bytes: usize) -> String {- let digest = Sha256::digest(source.as_bytes());- digest[..bytes]- .iter()- .map(|byte| format!("{byte:02x}"))- .collect()-}--fn attribute(key: &str, value: impl Into<String>) -> Value {- json!({ "key": key, "value": { "stringValue": value.into() } })-}--fn json_attribute(key: &str, value: &Value) -> Value {- attribute(key, value.to_string())-}--fn string_attr<'a>(span: &'a TraceSpan, key: &str) -> Option<&'a str> {- span.attributes.get(key).and_then(Value::as_str)-}--fn usage_details(span: &TraceSpan) -> Option<Value> {- let input = span.attributes.get("gen_ai.usage.input_tokens")?.as_u64()?;- let output = span- .attributes- .get("gen_ai.usage.output_tokens")?- .as_u64()?;- let cached = span- .attributes- .get("gen_ai.usage.cached_input_tokens")- .and_then(Value::as_u64)- .unwrap_or(0);- Some(json!({- "input": input.saturating_sub(cached),- "cache_read_input_tokens": cached,- "output": output,- "total": input.saturating_add(output),- }))-}--fn message_content(payload: &Value) -> String {- if let Some(content) = payload.get("content").and_then(Value::as_str) {- return content.to_string();- }- payload- .get("content")- .and_then(Value::as_array)- .map(|blocks| {- blocks- .iter()- .filter_map(|block| {- if let Some(text) = block.as_str() {- return Some(text.to_string());- }- let object = block.as_object()?;- if let Some(text) = object.get("text").and_then(Value::as_str) {- return Some(text.to_string());- }- if let Some(value) = object.get("json") {- return Some(value.to_string());- }- object.keys().next().map(|kind| format!("[{kind} content]"))- })- .collect::<Vec<_>>()- .join("\n")- })- .unwrap_or_default()-}--fn normalize_message(role: &str, payload: &Value) -> Value {- let mut message = json!({ "role": role, "content": message_content(payload) });- if role == "tool" {- if let Some(id) = payload.get("tool_call_id") {- message["tool_call_id"] = id.clone();- }- }- if role == "assistant" {- if let Some(calls) = payload.get("tool_calls").and_then(Value::as_array) {- if !calls.is_empty() {- message["tool_calls"] = Value::Array(- calls- .iter()- .map(|call| {- let arguments = call.get("arguments").cloned().unwrap_or(Value::Null);- json!({- "id": call.get("id").cloned().unwrap_or(Value::Null),- "type": "function",- "function": {- "name": call.get("name").cloned().unwrap_or(Value::Null),- "arguments": if let Some(raw) = arguments.as_str() {- raw.to_string()- } else {- arguments.to_string()- },- },- })- })- .collect(),- );- }- }- let reasoning = payload- .get("content")- .and_then(Value::as_array)- .map(|blocks| {- blocks- .iter()- .filter_map(|block| block.get("thinking")?.get("text")?.as_str())- .collect::<Vec<_>>()- .join("\n")- })- .unwrap_or_default();- if !reasoning.is_empty() {- message["reasoning"] = json!(reasoning);- }- }- message-}--fn normalize_generation_io(value: &Value, output: bool) -> Value {- if let Some(messages) = value.as_array() {- return Value::Array(- messages- .iter()- .filter_map(|message| {- let object = message.as_object()?;- if object.get("role").and_then(Value::as_str).is_some() {- return Some(message.clone());- }- for role in ["system", "user", "assistant", "tool"] {- if let Some(payload) = object.get(role) {- return Some(normalize_message(role, payload));- }- }- None- })- .collect(),- );- }- if output && value.get("content").is_some() {- return normalize_message("assistant", value);- }- value.clone()-}--/// Journal replay puts serialized model payloads on the child root. Replace-/// those with the delegated user task and last assistant answer for the trace-/// overview; the full per-call messages remain on generation observations.-pub(super) fn prepare_subagent_root(spans: &mut [TraceSpan]) {- let first_input = spans- .iter()- .find(|span| span.kind == SpanKind::Generation)- .and_then(|span| span.input.as_ref())- .map(|input| normalize_generation_io(input, false))- .and_then(|messages| {- messages.as_array().and_then(|messages| {- messages- .iter()- .rev()- .find(|message| message["role"] == "user")- .and_then(|message| message.get("content"))- .cloned()- })- });- let last_output = spans- .iter()- .rev()- .find(|span| span.kind == SpanKind::Generation)- .and_then(|span| span.output.as_ref())- .map(|output| normalize_generation_io(output, true))- .and_then(|message| message.get("content").cloned());- if let Some(root) = spans.iter_mut().find(|span| span.parent_span_id.is_none()) {- if first_input.is_some() {- root.input = first_input;- }- if last_output.is_some() {- root.output = last_output;- }- }-}--fn compact_internal_searches(spans: &[TraceSpan]) -> Vec<TraceSpan> {- let mut output = Vec::with_capacity(spans.len());- let mut groups: BTreeMap<String, Vec<&TraceSpan>> = BTreeMap::new();- for span in spans {- if span.name == "tool.tool_search" && span.status != SpanStatus::Error {- groups- .entry(span.parent_span_id.clone().unwrap_or_default())- .or_default()- .push(span);- } else {- output.push(span.clone());- }- }- for (parent, group) in groups {- if group.len() == 1 {- output.push((*group[0]).clone());- continue;- }- let mut summary = (*group[0]).clone();- summary.span_id = format!("{}:tool-search-summary", parent);- summary.name = "tool.search_catalog".to_string();- summary.start_unix_ms = group- .iter()- .map(|span| span.start_unix_ms)- .min()- .unwrap_or(0);- summary.end_unix_ms = group.iter().filter_map(|span| span.end_unix_ms).max();- summary.input = None;- summary.output = None;- summary.attributes.clear();- summary- .attributes- .insert("tool.call_count".to_string(), json!(group.len()));- output.push(summary);- }- output.sort_by_key(|span| span.start_unix_ms);- output-}--fn without_child_run_details(spans: &[TraceSpan]) -> Vec<TraceSpan> {- let by_id: HashMap<&str, &TraceSpan> = spans- .iter()- .map(|span| (span.span_id.as_str(), span))- .collect();- spans- .iter()- .filter(|span| {- let mut parent = span.parent_span_id.as_deref();- while let Some(id) = parent {- let Some(ancestor) = by_id.get(id) else {- break;- };- if ancestor.kind == SpanKind::Subagent {- return false;- }- parent = ancestor.parent_span_id.as_deref();- }- true- })- .cloned()- .collect()-}--fn span_to_otlp(span: &TraceSpan, root: &TraceSpan, environment: &str) -> Value {- let mut attrs = vec![- attribute(- "langfuse.observation.type",- match span.kind {- SpanKind::Turn | SpanKind::Subagent => "agent",- SpanKind::Tool => "tool",- SpanKind::Generation => "generation",- SpanKind::Iteration | SpanKind::SubagentIteration => "span",- },- ),- attribute("langfuse.trace.name", root.name.clone()),- attribute(- "langfuse.trace.metadata.openhuman_trace_id",- root.trace_id.clone(),- ),- attribute("langfuse.environment", environment),- attribute("langfuse.version", env!("CARGO_PKG_VERSION")),- attribute("langfuse.release", env!("CARGO_PKG_VERSION")),- attribute(- "langfuse.session.id",- string_attr(root, "thread.id")- .unwrap_or(root.trace_id.as_str())- .to_string(),- ),- ];- if let Some(run_type) = string_attr(root, "run.type") {- attrs.push(attribute("langfuse.trace.metadata.run_type", run_type));- let mut tags = vec![format!("run:{run_type}")];- if let Some(source) = string_attr(root, "channel.source") {- tags.push(format!("source:{source}"));- }- attrs.push(json!({ "key": "langfuse.trace.tags", "value": {- "arrayValue": { "values": tags.into_iter().map(|tag| json!({ "stringValue": tag })).collect::<Vec<_>>() }- } }));- }- for key in [- "agent.id",- "channel.source",- "run_id",- "parent_run_id",- "root_run_id",- ] {- if let Some(value) = string_attr(root, key) {- attrs.push(attribute(- &format!("langfuse.trace.metadata.{}", key.replace('.', "_")),- value,- ));- }- }- if let Some(input) = &span.input {- let input = if span.kind == SpanKind::Generation {- normalize_generation_io(input, false)- } else {- input.clone()- };- attrs.push(json_attribute("langfuse.observation.input", &input));- }- if let Some(output) = &span.output {- let output = if span.kind == SpanKind::Generation {- normalize_generation_io(output, true)- } else {- output.clone()- };- attrs.push(json_attribute("langfuse.observation.output", &output));- }- if span.status == SpanStatus::Error {- attrs.push(attribute("langfuse.observation.level", "ERROR"));- if let Some(message) = string_attr(span, "error.message") {- attrs.push(attribute("langfuse.observation.status_message", message));- }- }- for (key, value) in &span.attributes {- if key.starts_with("gen_ai.usage.") || key == "gen_ai.request.model" {- continue;- }- attrs.push(json_attribute(- &format!("langfuse.observation.metadata.{}", key.replace('.', "_")),- value,- ));- }- if span.kind == SpanKind::Generation {- if let Some(model) = string_attr(span, "gen_ai.request.model") {- attrs.push(attribute("langfuse.observation.model.name", model));- }- if let Some(provider) = string_attr(span, "gen_ai.provider") {- attrs.push(attribute(- "langfuse.observation.metadata.provider",- provider,- ));- }- if provider_is_openrouter(span) {- attrs.push(attribute(- "langfuse.observation.metadata.model_route",- "openrouter",- ));- }- if let Some(usage) = usage_details(span) {- attrs.push(json_attribute("langfuse.observation.usage_details", &usage));- }- // Langfuse derives time to first token from the completion start.- if let Some(completion_start) = span- .attributes- .get("gen_ai.response.first_token_unix_ms")- .and_then(Value::as_u64)- .and_then(|ms| chrono::DateTime::from_timestamp_millis(ms as i64))- {- attrs.push(attribute(- "langfuse.observation.completion_start_time",- completion_start.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),- ));- }- if let Some(cost) = span- .attributes- .get("gen_ai.usage.cost_usd")- .and_then(Value::as_f64)- .filter(|cost| *cost > 0.0)- {- attrs.push(json_attribute(- "langfuse.observation.cost_details",- &json!({ "total": cost }),- ));- }- } else if span.span_id == root.span_id {- for key in [- "gen_ai.usage.input_tokens",- "gen_ai.usage.output_tokens",- "gen_ai.usage.cost_usd",- ] {- if let Some(value) = span.attributes.get(key) {- attrs.push(json_attribute(- &format!(- "langfuse.observation.metadata.run_total_{}",- key.rsplit('.').next().unwrap_or(key)- ),- value,- ));- }- }- }- let mut body = json!({- "traceId": hex_id(&span.trace_id, 16),- "spanId": hex_id(&span.span_id, 8),- "name": span.name,- "startTimeUnixNano": span.start_unix_ms.saturating_mul(1_000_000).to_string(),- "endTimeUnixNano": span.end_unix_ms.unwrap_or(span.start_unix_ms).saturating_mul(1_000_000).to_string(),- "attributes": attrs,- });- if let Some(parent) = &span.parent_span_id {- body["parentSpanId"] = json!(hex_id(parent, 8));- }- body-}--fn provider_is_openrouter(span: &TraceSpan) -> bool {- string_attr(span, "gen_ai.provider") == Some("openrouter")- || string_attr(span, "gen_ai.request.model")- .is_some_and(|model| model.contains("openrouter/"))-}--pub(super) fn otlp_requests(spans: &[TraceSpan], environment: &str) -> Vec<Value> {- let Some(root) = spans.iter().find(|span| span.parent_span_id.is_none()) else {- return Vec::new();- };- // Child runs have their own journal-backed trace under the same session.- // Keep their parent placeholder here, but export each child model/tool call- // only once so Langfuse usage metrics do not count it twice.- let visible = without_child_run_details(spans);- let compacted = compact_internal_searches(&visible);- let make_request = |spans: Vec<Value>| {- json!({ "resourceSpans": [{- "resource": { "attributes": [attribute("service.name", "openhuman")] },- "scopeSpans": [{- "scope": { "name": "openhuman.agent" },- "spans": spans,- }],- }] })- };- let mut requests = Vec::new();- let mut batch = Vec::new();- let mut bytes = 256;- for span in &compacted {- let converted = span_to_otlp(span, root, environment);- let span_bytes = converted.to_string().len();- if !batch.is_empty()- && (batch.len() >= MAX_SPANS_PER_REQUEST || bytes + span_bytes > MAX_REQUEST_BYTES)- {- requests.push(make_request(std::mem::take(&mut batch)));- bytes = 256;- }- bytes += span_bytes;- batch.push(converted);- }- if !batch.is_empty() {- requests.push(make_request(batch));- }- requests-}-pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {if spans.is_empty() {return Ok(());@@ -485,7 +40,7 @@ pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(let client = crate::backend::resolve_backend_transport().map_err(|err| format!("Langfuse OTLP push has no backend transport: {err}"))?.http_client(crate::backend::TransportProfile::Api);- for payload in otlp_requests(spans, environment) {+ for payload in otlp_requests(spans, environment, &super::export_brand()) {let response = client.post(&url).header(diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rsindex ca2ce358e1..8429643aca 100644--- a/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs@@ -1,231 +1,23 @@use super::*;use std::collections::BTreeMap;+use tinyagents_harness::observability::trace_export::{SpanKind, SpanStatus};-fn span(id: &str, parent: Option<&str>, kind: SpanKind, name: &str) -> TraceSpan {- TraceSpan {+#[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: id.into(),- parent_span_id: parent.map(str::to_string),- name: name.into(),- kind,+ 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,- }-}--fn attr<'a>(span: &'a Value, key: &str) -> Option<&'a str> {- span["attributes"]- .as_array()?- .iter()- .find(|item| item["key"] == key)?["value"]["stringValue"]- .as_str()-}--#[test]-fn otlp_has_one_root_with_readable_io_and_call_only_usage() {- let mut root = span("root", None, SpanKind::Turn, "agent.turn:orchestrator");- root.attributes- .insert("thread.id".into(), json!("thread-one"));- root.attributes- .insert("run.type".into(), json!("interactive_chat"));- root.attributes- .insert("gen_ai.usage.input_tokens".into(), json!(20));- root.attributes- .insert("gen_ai.usage.output_tokens".into(), json!(5));- root.input = Some(json!("What is the weather?"));- root.output = Some(json!("Sunny."));- let mut generation = span("call", Some("root"), SpanKind::Generation, "llm.reply");- generation.attributes.insert(- "gen_ai.request.model".into(),- json!("managed.openrouter/test"),- );- generation- .attributes- .insert("gen_ai.usage.input_tokens".into(), json!(20));- generation- .attributes- .insert("gen_ai.usage.cached_input_tokens".into(), json!(8));- generation- .attributes- .insert("gen_ai.usage.output_tokens".into(), json!(5));- generation.input = Some(json!([{ "role": "user", "content": "What is the weather?" }]));- generation.output = Some(json!({ "content": "Sunny." }));- let payloads = otlp_requests(&[root, generation], "production");- assert_eq!(payloads.len(), 1);- let spans = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]- .as_array()- .unwrap();- assert_eq!(spans.len(), 2);- let root = spans- .iter()- .find(|item| item["name"] == "agent.turn:orchestrator")- .unwrap();- let call = spans- .iter()- .find(|item| item["name"] == "llm.reply")- .unwrap();- assert_eq!(attr(root, "langfuse.observation.type"), Some("agent"));- assert_eq!(attr(root, "langfuse.session.id"), Some("thread-one"));- assert_eq!(- attr(root, "langfuse.observation.input"),- Some("\"What is the weather?\"")- );- assert_eq!(- attr(root, "langfuse.observation.output"),- Some("\"Sunny.\"")- );- assert!(attr(root, "langfuse.observation.usage_details").is_none());- assert_eq!(call["parentSpanId"], root["spanId"]);- assert_eq!(attr(call, "langfuse.observation.type"), Some("generation"));- assert_eq!(- attr(call, "langfuse.observation.model.name"),- Some("managed.openrouter/test")- );- assert_eq!(- attr(call, "langfuse.observation.usage_details"),- Some("{\"cache_read_input_tokens\":8,\"input\":12,\"output\":5,\"total\":25}")- );-}--#[test]-fn repeated_internal_searches_become_one_summary() {- let root = span("root", None, SpanKind::Turn, "agent.turn");- let searches: Vec<_> = (0..240)- .map(|index| {- span(- &format!("search-{index}"),- Some("root"),- SpanKind::Tool,- "tool.tool_search",- )- })- .collect();- let mut all = vec![root];- all.extend(searches);- let payloads = otlp_requests(&all, "production");- let spans = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]- .as_array()- .unwrap();- assert_eq!(spans.len(), 2);- let summary = spans- .iter()- .find(|item| item["name"] == "tool.search_catalog")- .unwrap();- assert_eq!(- attr(summary, "langfuse.observation.metadata.tool_call_count"),- Some("240")- );-}--#[test]-fn tinyinference_messages_render_as_role_labeled_conversation() {- let input = json!([- { "system": { "content": [{ "text": "instructions" }] } },- { "user": { "content": [{ "text": "find weather" }] } },- { "assistant": { "content": [], "tool_calls": [{- "id": "call-1", "name": "weather", "arguments": { "city": "Paris" }- }] } },- { "tool": { "tool_call_id": "call-1", "content": [{ "text": "sunny" }] } },- { "custom": { "kind": "compaction" } },- ]);- let normalized = normalize_generation_io(&input, false);- let messages = normalized.as_array().unwrap();- assert_eq!(messages.len(), 4);- assert_eq!(- messages[0],- json!({ "role": "system", "content": "instructions" })- );- assert_eq!(- messages[1],- json!({ "role": "user", "content": "find weather" })- );- assert_eq!(- messages[2]["tool_calls"][0]["function"]["arguments"],- "{\"city\":\"Paris\"}"- );- assert_eq!(- messages[3],- json!({ "role": "tool", "tool_call_id": "call-1", "content": "sunny" })- );- let output = normalize_generation_io(&json!({ "content": [{ "text": "It is sunny" }] }), true);- assert_eq!(- output,- json!({ "role": "assistant", "content": "It is sunny" })- );-}--#[test]-fn subagent_root_shows_task_and_final_answer() {- let mut root = span("root", None, SpanKind::Turn, "agent.turn:researcher");- root.input = Some(json!("unreadable serialized model request"));- let mut first = span("first", Some("root"), SpanKind::Generation, "model");- first.input = Some(json!([- { "system": { "content": [{ "text": "instructions" }] } },- { "user": { "content": [{ "text": "research topic" }] } },- ]));- first.output = Some(json!({ "content": [{ "text": "working" }] }));- let mut last = span("last", Some("root"), SpanKind::Generation, "model");- last.output = Some(json!({ "content": [{ "text": "final result" }] }));- let mut spans = vec![root, first, last];- prepare_subagent_root(&mut spans);- assert_eq!(spans[0].input, Some(json!("research topic")));- assert_eq!(spans[0].output, Some(json!("final result")));-}--#[test]-fn child_model_usage_is_exported_only_in_child_trace() {- let root = span("root", None, SpanKind::Turn, "agent.turn");- let child = span(- "child",- Some("root"),- SpanKind::Subagent,- "subagent.researcher",- );- let mut generation = span("model", Some("child"), SpanKind::Generation, "model");- generation- .attributes- .insert("gen_ai.usage.input_tokens".into(), json!(100));- generation- .attributes- .insert("gen_ai.usage.output_tokens".into(), json!(10));- let payloads = otlp_requests(&[root, child, generation], "production");- let spans = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]- .as_array()- .unwrap();- assert_eq!(spans.len(), 2);- assert!(spans- .iter()- .all(|span| attr(span, "langfuse.observation.usage_details").is_none()));-}--#[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 = [span("root", None, SpanKind::Turn, "agent.turn")];+ }];assert!(push_spans(&config, &spans).await.is_ok());}--#[test]-fn large_trace_is_split_under_backend_request_limit() {- let mut spans = vec![span("root", None, SpanKind::Turn, "agent.turn")];- for index in 0..18 {- let mut tool = span(- &format!("tool-{index}"),- Some("root"),- SpanKind::Tool,- "tool.fetch",- );- tool.output = Some(json!("x".repeat(500_000)));- spans.push(tool);- }- let requests = otlp_requests(&spans, "production");- assert!(requests.len() >= 2);- assert!(requests- .iter()- .all(|request| request.to_string().len() < MAX_REQUEST_BYTES));-}diff --git a/crates/openhuman-core/src/agent/progress_tracing/serialize.rs b/crates/openhuman-core/src/agent/progress_tracing/serialize.rsdeleted file mode 100644index adecb827d3..0000000000--- a/crates/openhuman-core/src/agent/progress_tracing/serialize.rs+++ /dev/null@@ -1,167 +0,0 @@-//! Content truncation caps, small JSON-value builders, and NDJSON-//! serialization for finished spans.--use crate::config::schema::AgentTracingBackend;--use super::types::TraceSpan;--/// Cap on tool arguments / tool output recorded onto spans when content-/// capture is on. Keeps a single runaway tool result from bloating the trace-/// batch while still giving Langfuse an actionable preview.-pub(super) const MAX_TOOL_CONTENT_CHARS: usize = 4_000;--/// Cap on captured error text (Langfuse observation `statusMessage`).-pub(super) const MAX_ERROR_MESSAGE_CHARS: usize = 500;--/// Cap on captured model request/completion content and subagent-/// prompt/output. Larger than the tool cap because a generation's input is the-/// full message array (system prompt included) — but still bounded so a-/// 100k-token context can't push the ingestion batch past Langfuse's event-/// size limits.-pub(super) const MAX_MODEL_CONTENT_CHARS: usize = 200_000;--/// Keep large model requests as structured messages so Langfuse can render-/// roles and tool calls. Retain the most recent messages within the bound.-pub(super) fn capture_model_content(value: &serde_json::Value) -> serde_json::Value {- let serialized = value.to_string();- if serialized.chars().count() <= MAX_MODEL_CONTENT_CHARS {- return value.clone();- }- if let Some(messages) = value.as_array() {- let mut kept = Vec::new();- let mut used = 0;- for message in messages.iter().rev() {- let mut message = message.clone();- let size = message.to_string().chars().count();- if size > MAX_MODEL_CONTENT_CHARS / 2 {- if let Some(content) = message.get_mut("content") {- *content = serde_json::Value::String(format!(- "{}…[message content truncated]",- truncate_chars(- &content- .as_str()- .map(str::to_owned)- .unwrap_or_else(|| content.to_string()),- MAX_MODEL_CONTENT_CHARS / 2- )- ));- }- }- let size = message.to_string().chars().count();- if used + size > MAX_MODEL_CONTENT_CHARS.saturating_sub(128) {- break;- }- used += size;- kept.push(message);- }- kept.reverse();- let omitted = messages.len().saturating_sub(kept.len());- if omitted > 0 {- kept.insert(- 0,- serde_json::json!({- "role": "system",- "content": format!("[{omitted} earlier messages omitted from telemetry]"),- }),- );- }- return serde_json::Value::Array(kept);- }- if let Some(fields) = value.as_object() {- let mut kept = fields.clone();- if let Some(content) = kept.get_mut("content") {- *content = serde_json::Value::String(truncate_chars(- &content- .as_str()- .map(str::to_owned)- .unwrap_or_else(|| content.to_string()),- MAX_MODEL_CONTENT_CHARS / 2,- ));- if serde_json::Value::Object(kept.clone())- .to_string()- .chars()- .count()- <= MAX_MODEL_CONTENT_CHARS- {- return serde_json::Value::Object(kept);- }- }- }- serde_json::json!({- "truncated": true,- "preview": truncate_chars(&serialized, MAX_MODEL_CONTENT_CHARS / 2),- })-}--/// Truncate `text` to `max` characters, appending an explicit truncation-/// marker (with the omitted char count) when content was dropped. Returns the-/// input unchanged when it already fits. Slices on char boundaries, so it-/// never panics on multi-byte content.-pub(super) fn truncate_chars(text: &str, max: usize) -> String {- match text.char_indices().nth(max) {- None => text.to_string(),- Some((byte_end, _)) => {- let omitted = text.chars().count() - max;- format!("{}…[truncated {omitted} chars]", &text[..byte_end])- }- }-}--/// Truncate tool-content text to [`MAX_TOOL_CONTENT_CHARS`].-pub(super) fn truncate_capture_text(text: &str) -> String {- truncate_chars(text, MAX_TOOL_CONTENT_CHARS)-}--pub(super) fn status_of(success: bool) -> super::types::SpanStatus {- if success {- super::types::SpanStatus::Ok- } else {- super::types::SpanStatus::Error- }-}--pub(super) fn json_str(s: &str) -> serde_json::Value {- serde_json::Value::String(s.to_string())-}--pub(super) fn json_u32(n: u32) -> serde_json::Value {- serde_json::Value::Number(n.into())-}--pub(super) fn json_u64(n: u64) -> serde_json::Value {- serde_json::Value::Number(n.into())-}--pub(super) fn json_usize(n: usize) -> serde_json::Value {- serde_json::Value::Number((n as u64).into())-}--pub(super) fn json_f64(n: f64) -> serde_json::Value {- serde_json::Number::from_f64(n)- .map(serde_json::Value::Number)- // NaN/inf can't be JSON numbers — degrade to null rather than panic.- .unwrap_or(serde_json::Value::Null)-}--/// Serialize spans to NDJSON (one span object per line) in the requested-/// backend envelope. Both backends share the [`TraceSpan`] body; Langfuse-/// wraps each line with a `{"type":"span-create", ...}` observation envelope-/// so it can be POSTed to the Langfuse ingestion API, while OTel emits the-/// bare span. Returns an empty string for an empty slice.-pub(crate) fn spans_to_ndjson(backend: AgentTracingBackend, spans: &[TraceSpan]) -> String {- let mut out = String::new();- for span in spans {- let line = match backend {- AgentTracingBackend::Otel => serde_json::to_string(span),- AgentTracingBackend::Langfuse => serde_json::to_string(&serde_json::json!({- "type": "span-create",- "body": span,- })),- };- if let Ok(line) = line {- out.push_str(&line);- out.push('\n');- }- }- out-}diff --git a/crates/openhuman-core/src/agent/progress_tracing/types.rs b/crates/openhuman-core/src/agent/progress_tracing/types.rsdeleted file mode 100644index 3866fe850e..0000000000--- a/crates/openhuman-core/src/agent/progress_tracing/types.rs+++ /dev/null@@ -1,260 +0,0 @@-//! Trace/span data model: run classification, trace-level correlation-//! context, and the exported span shape itself.--use std::collections::BTreeMap;--use serde::Serialize;--/// Kind of run a trace belongs to, rendered as stable snake_case strings for-/// Langfuse trace tags (`run:<type>`) and metadata (`run_type`) so runs can be-/// filtered in the UI.-///-/// Covers web progress bridge turns and child turns exported from their own-/// durable journals. Other background paths without either export hook do not-/// produce an agent trace yet.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]-pub enum RunType {- /// Interactive user chat turn (desktop UI / socket / PTT / dictation).- #[default]- InteractiveChat,- /// Autonomous background run.- AutonomousTask,- /// Inbound message relayed from an external channel (Telegram, Discord,- /// Slack, …) through the channel bus.- ChannelInbound,- /// A delegated child turn, exported as a trace in the parent conversation.- Subagent,-}--impl RunType {- /// Stable snake_case identifier used in tags/metadata.- pub fn as_str(self) -> &'static str {- match self {- RunType::InteractiveChat => "interactive_chat",- RunType::AutonomousTask => "autonomous_task",- RunType::ChannelInbound => "channel_inbound",- RunType::Subagent => "subagent",- }- }-- /// Classify from the chat-request `source` tag. Known background sources- /// map to their kinds; everything else (`ptt`/`dictation`/`type`/absent)- /// is an interactive chat turn.- pub fn from_source(source: Option<&str>) -> Self {- match source {- Some("autonomous") => RunType::AutonomousTask,- Some("channel_inbound") => RunType::ChannelInbound,- _ => RunType::InteractiveChat,- }- }-}--/// Trace-level correlation context, stamped onto the root span.-#[derive(Debug, Clone)]-pub struct TraceContext {- /// Trace id — unique per turn. Every span of a single turn shares it, so- /// each turn becomes its own Langfuse trace.- pub session_id: String,- /// Real authenticated user attribution (the backend user id, or email as- /// fallback) — exported as the Langfuse `userId`. `None` when the caller- /// is anonymous. Transport identifiers (socket client id / "system")- /// belong in [`Self::client_id`], not here.- pub user_id: Option<String>,- /// Transport client id (the broadcast socket client, or `"system"` for- /// autonomous runs). Exported as the `client.id` metadata attribute so it- /// stays inspectable without polluting user attribution.- pub client_id: Option<String>,- /// Agent definition id driving the turn (e.g. `"orchestrator"`,- /// `"task_manager_agent"`). Stamped as the `agent.id` attribute and folded into- /// the root span/trace name (`agent.turn:<agent_id>`).- pub agent_id: Option<String>,- /// Where the run originated (`"chat"`, `"ptt"`, `"autonomous"`, …).- /// Exported as the `channel.source` metadata attribute.- pub channel_source: Option<String>,- /// Grouping key (the thread/conversation id) exported as the Langfuse- /// `sessionId` so per-turn traces still group under one session. When- /// `None`, the collector falls back to the trace id so every trace still- /// carries a session id.- pub session_group: Option<String>,- /// Whether content capture (`observability.agent_tracing.capture_content`)- /// is on. Gates recording tool arguments/results onto spans at collection- /// time — when off, tool I/O never even reaches the in-memory span.- pub capture_content: bool,- /// Kind of run — exported as Langfuse trace tags (`run:<type>`) and the- /// `run_type` metadata key. Defaults to interactive chat.- pub run_type: RunType,- /// This run's own id (the tinyagents `RunContext` run id), exported as the- /// `run_id` metadata key. `None` until the run's observations are known.- pub run_id: Option<String>,- /// The spawning run's id when this run is a sub-agent/graph node, exported- /// as the `parent_run_id` metadata key. `None` for top-level turns. This is- /// what links a spawned sub-agent's trace back to its parent turn (#4657).- pub parent_run_id: Option<String>,- /// The root ancestor run id (equal to [`Self::run_id`] for top-level runs),- /// exported as the `root_run_id` metadata key so Langfuse can thread a whole- /// spawn tree under one root.- pub root_run_id: Option<String>,-}--impl TraceContext {- pub fn new(session_id: impl Into<String>, user_id: Option<String>) -> Self {- Self {- session_id: session_id.into(),- user_id,- client_id: None,- agent_id: None,- channel_source: None,- session_group: None,- capture_content: false,- run_type: RunType::default(),- run_id: None,- parent_run_id: None,- root_run_id: None,- }- }-- /// Set the grouping key (thread/conversation id) for the Langfuse- /// `sessionId`, so a conversation's per-turn traces group together.- pub fn with_session_group(mut self, group: impl Into<String>) -> Self {- self.session_group = Some(group.into());- self- }-- /// Set the transport client id (`client.id` metadata attribute).- pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {- self.client_id = Some(client_id.into());- self- }-- /// Set the agent definition id (`agent.id` attribute + trace name suffix).- pub fn with_agent_id(mut self, agent_id: impl Into<String>) -> Self {- self.agent_id = Some(agent_id.into());- self- }-- /// Set the run origin (`channel.source` metadata attribute).- pub fn with_channel_source(mut self, source: impl Into<String>) -> Self {- self.channel_source = Some(source.into());- self- }-- /// Enable/disable content capture (tool arguments/results on spans).- pub fn with_capture_content(mut self, capture_content: bool) -> Self {- self.capture_content = capture_content;- self- }-- /// Set the run type (Langfuse `run:<type>` tag / `run_type` metadata).- pub fn with_run_type(mut self, run_type: RunType) -> Self {- self.run_type = run_type;- self- }-- /// Stamp the run lineage (`run_id` / `parent_run_id` / `root_run_id`) so a- /// spawned sub-agent's trace links back to its parent turn (#4657). The ids- /// come from the tinyagents `RunContext`, surfaced via the run's journalled- /// observations at export time.- pub fn with_run_lineage(- mut self,- run_id: Option<String>,- parent_run_id: Option<String>,- root_run_id: Option<String>,- ) -> Self {- self.run_id = run_id;- self.parent_run_id = parent_run_id;- self.root_run_id = root_run_id;- self- }-}--/// Derive the trace id (session id) for a run: prefer the UI session id when-/// present, otherwise fall back to the thread id so headless/autonomous runs-/// (which carry no UI session) still correlate their spans.-pub fn trace_session_id(ui_session_id: Option<u64>, thread_id: &str) -> String {- ui_session_id- .map(|id| id.to_string())- .unwrap_or_else(|| thread_id.to_string())-}--/// What a span represents. Mirrors the [`super::AgentProgress`] lifecycle.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]-#[serde(rename_all = "snake_case")]-pub enum SpanKind {- /// The whole turn (root span).- Turn,- /// One LLM iteration of the parent turn.- Iteration,- /// A tool call.- Tool,- /// A single LLM call (model invocation) with per-call usage/cost.- Generation,- /// A spawned subagent.- Subagent,- /// One LLM iteration inside a subagent.- SubagentIteration,-}--/// OTel-style span status.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]-#[serde(rename_all = "snake_case")]-pub enum SpanStatus {- /// Not yet completed, or completed without an explicit success signal.- Unset,- /// Completed successfully.- Ok,- /// Completed with an error.- Error,-}--/// A single finished (or in-flight) span. Field names follow OpenTelemetry-/// conventions (snake_case `trace_id`/`span_id`/`start_unix_ms`/…) so the raw-/// NDJSON file/log export is a self-describing OTel-style span dump for local-/// inspection.-///-/// #4469 item 13: this raw record is **not** directly Langfuse-ingestible — the-/// Langfuse `/api/public/ingestion` API needs each span wrapped in a-/// `{ type, id, timestamp, body }` event envelope. That envelope is produced-/// only on the remote-push path (`otlp::push_spans`); the local NDJSON exporter-/// intentionally emits the raw spans, not the batch format.-#[derive(Debug, Clone, Serialize)]-pub struct TraceSpan {- /// Trace id (the session id) — shared by every span in the run.- pub trace_id: String,- /// Unique id of this span within the trace.- pub span_id: String,- /// Parent span id, or `None` for the root turn span.- #[serde(skip_serializing_if = "Option::is_none")]- pub parent_span_id: Option<String>,- /// Human-readable span name, e.g. `agent.turn`, `tool.web_search`.- pub name: String,- /// Structured kind for programmatic filtering.- pub kind: SpanKind,- /// Wall-clock start (Unix epoch milliseconds).- pub start_unix_ms: u64,- /// Wall-clock end (Unix epoch milliseconds); `None` while in flight.- #[serde(skip_serializing_if = "Option::is_none")]- pub end_unix_ms: Option<u64>,- /// Completion status.- pub status: SpanStatus,- /// Metadata-only attributes (no secrets/PII).- pub attributes: BTreeMap<String, serde_json::Value>,- /// Optional prompt/input content. Populated (via `AgentProgress::TurnContent`)- /// **only** when `observability.agent_tracing.capture_content` is opted in —- /// the [`super::collector::SpanCollector`] drops content at storage time otherwise, so with the- /// default gate off this is always `None` and no exporter can serialize it.- #[serde(skip_serializing_if = "Option::is_none")]- pub input: Option<serde_json::Value>,- /// Optional model-reply/output content. Same storage-level gating as- /// [`Self::input`].- #[serde(skip_serializing_if = "Option::is_none")]- pub output: Option<serde_json::Value>,-}--impl TraceSpan {- /// Duration in milliseconds, or `None` while the span is still open.- #[cfg(test)]- pub fn duration_ms(&self) -> Option<u64> {- self.end_unix_ms- .map(|end| end.saturating_sub(self.start_unix_ms))- }-}