Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): session.id on every metric point; keep a metrics window whose export failed (#9099)
Loc Nguyenb7f4f641efdc
diff --git a/docs/src/pages/docs/agent/telemetry.mdx b/docs/src/pages/docs/agent/telemetry.mdxindex 510dd79fd..c406baedc 100644--- a/docs/src/pages/docs/agent/telemetry.mdx+++ b/docs/src/pages/docs/agent/telemetry.mdx@@ -112,14 +112,18 @@ export what is buffered, then exit as that signal would.All metrics are monotonic sums. They are cumulative (running totals since the process started)unless `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` asks for delta, where each point holdsonly what changed since the last export. Every point carries `session.id` unless-`OTEL_METRICS_INCLUDE_SESSION_ID=false`. When an RPC host archives a session, its series are sent-one last time and then dropped, so a long-lived host doesn't keep exporting finished sessions.+`OTEL_METRICS_INCLUDE_SESSION_ID=false`, so a backend that sums points per session can fold all of+them. Under delta, `jan_agent.telemetry.dropped` carries the session it happened in; drops before+any session started are held and sent with the first one. `jan cli agent status` lists+`otlp-delta` in `capabilities` for builds that behave this way. When an RPC host archives a+session, its series are sent one last time and then dropped, so a long-lived host doesn't keep+exporting finished sessions.| Metric | Unit | Attributes || --- | --- | --- || `jan_agent.session.count` | 1 | || `jan_agent.prompt.count` | 1 | Counts new user prompts. A run that continues or resumes a conversation without a new user message doesn't count. |-| `jan_agent.turn.count` | 1 | `agent` (`main` / `subagent`) |+| `jan_agent.turn.count` | 1 | `agent` (`main` / `subagent`), and the run's `session.id` || `jan_agent.token.usage` | tokens | `type` (`input` / `output` / `cache_read` / `cache_write`), `model`, `provider` || `jan_agent.cost.usage` | USD | `model`, `provider`. Only for models whose price is in the model catalog. An unpriced model reports nothing, not zero. || `jan_agent.api_request.count` | 1 | `model`, `provider`, `success` |@@ -216,7 +220,10 @@ LANGFUSE_PUBLIC_KEY=... LANGFUSE_SECRET_KEY=... LANGFUSE_BASE_URL=https://cloud.Recording a signal never waits: it goes into a bounded in-memory queue. If a collector is slow ordown, new records are dropped and counted in `jan_agent.telemetry.dropped`, and the turn doesn'tslow down. A collector that answers 429, 502, 503 or 504 gets one retry, after its `Retry-After`-(up to 10 seconds; a longer wait drops the batch) or 1 second.+(up to 10 seconds; a longer wait counts as a failure) or 1 second. A log or trace batch that still+fails is dropped. A metrics export that still fails keeps its window: the next export carries it+again, over the combined span, so a delta backend loses nothing. If the failed export had in fact+landed and only its answer was lost, that window is counted twice.Export failures are logged at debug level (`RUST_LOG=debug`) on stderr and never printed tostdout.diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rsindex f3779e0ac..eb6bafd0e 100644--- a/src-tauri/src/core/agent/otel/mod.rs+++ b/src-tauri/src/core/agent/otel/mod.rs@@ -58,11 +58,14 @@ const ERROR_CAP: usize = 512;/// The wait before retrying an export the collector asked to be retried,/// when it did not say how long.const RETRY_DELAY: Duration = Duration::from_secs(1);-/// The longest `Retry-After` honoured; a longer one drops the batch instead.+/// The longest `Retry-After` honoured; a longer one counts as a failed export.const MAX_RETRY_DELAY: Duration = Duration::from_secs(10);/// Telemetry capabilities this build reports in `jan cli agent status`.-pub const CAPABILITIES: &[&str] = &[];+/// `otlp-delta`: `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta` is+/// honoured and every metric point carries `session.id`, so a backend that+/// sums delta points per session can fold them.+pub const CAPABILITIES: &[&str] = &["otlp-delta"];/// Per-token prices for `(provider, model)`, when the catalog knows them.pub type Pricer = Box<dyn Fn(Option<&str>, &str) -> Option<TokenRates> + Send + Sync>;@@ -626,6 +629,16 @@ fn random_ids() -> ([u8; 16], [u8; 8]) {}}+/// What one metrics export took out of [`State`]: the series it cleared or+/// evicted and the window it closed. Handed back to [`State::export_failed`]+/// when the export never reached the collector, so nothing is lost with it.+pub struct Exported {+ counters: BTreeMap<SeriesKey, f64>,+ closed_sessions: HashSet<String>,+ last_export_nanos: u64,+ dropped_reported: u64,+}+/// Everything the worker folds signals into. Pure: no I/O, so the mapping from/// events to metrics and logs is testable without a collector.pub struct State {@@ -1043,7 +1056,11 @@ impl State {self.log(wall, "jan_agent.api_request", false, session.as_deref(), child.as_ref(), fields);}EventSignal::Step => {- let mut attrs = Vec::new();+ // Carries the run's session like every other point, so a+ // backend that groups by `session.id` never sees a turn with+ // no session to put it in.+ let session = self.session_of(&run);+ let mut attrs = self.session_attr(session.as_deref());attrs.push(metric_attr("agent", if child.is_some() { "subagent" } else { "main" }));self.add("jan_agent.turn.count", attrs, 1.0);}@@ -1207,8 +1224,16 @@ impl State {),};let mut by_name: BTreeMap<&'static str, Vec<Point>> = BTreeMap::new();- let dropped_key = ("jan_agent.telemetry.dropped", Vec::new());- let dropped_entry = (dropped > 0).then_some((&dropped_key, dropped as f64));+ // A delta window's drops go under the session it happened in, like+ // every other point. A cumulative total stays process-wide: moving a+ // running total between sessions' series would count it twice.+ let dropped_attrs = match temporality {+ Temporality::Delta => self.session_attr(self.main_session.as_deref()),+ Temporality::Cumulative => Vec::new(),+ };+ let dropped_key = ("jan_agent.telemetry.dropped", dropped_attrs);+ let dropped_entry =+ (dropped > 0 && self.dropped_reportable()).then_some((&dropped_key, dropped as f64));for ((name, attrs), value) in self.counters.iter()@@ -1246,29 +1271,68 @@ impl State {.collect()}+ /// Whether a delta window's drops can be exported now. With session ids+ /// on, they wait for a session to carry them rather than go out as the+ /// only point with none, which a backend grouping by `session.id` would+ /// file as a session of its own; the count is kept until then.+ fn dropped_reportable(&self) -> bool {+ self.cfg.temporality == Temporality::Cumulative+ || !self.cfg.metrics_session_id+ || self.main_session.is_some()+ }+/// The snapshot [`State::metrics`] took at `now` was handed to the/// exporter. Delta starts the next window here, empty; cumulative drops/// the series of sessions closed since the last export, whose final/// values that snapshot carried, so a long-lived host's series stay- /// bounded by its live sessions.- pub fn exported(&mut self, now: u64, dropped: u64) {+ /// bounded by its live sessions. What it took comes back as an+ /// [`Exported`], for [`State::export_failed`] if the export never landed.+ pub fn exported(&mut self, now: u64, dropped: u64) -> Exported {+ let mut taken = Exported {+ counters: BTreeMap::new(),+ closed_sessions: HashSet::new(),+ last_export_nanos: self.last_export_nanos,+ dropped_reported: self.dropped_reported,+ };match self.cfg.temporality {Temporality::Delta => {- self.counters.clear();+ taken.counters = std::mem::take(&mut self.counters);self.last_export_nanos = now;- self.dropped_reported = dropped;+ if self.dropped_reportable() {+ self.dropped_reported = dropped;+ }}Temporality::Cumulative => {let closed = std::mem::take(&mut self.closed_sessions);if !closed.is_empty() {- self.counters.retain(|(_, attrs), _| {- !attrs- .iter()- .any(|(k, v)| k == "session.id" && closed.contains(v))- });+ let (gone, kept): (BTreeMap<_, _>, BTreeMap<_, _>) = std::mem::take(&mut self.counters)+ .into_iter()+ .partition(|((_, attrs), _)| {+ attrs.iter().any(|(k, v)| k == "session.id" && closed.contains(v))+ });+ self.counters = kept;+ taken.counters = gone;}+ taken.closed_sessions = closed;}}+ taken+ }++ /// The export [`State::exported`] was handed to never reached the+ /// collector: put back what it took, so the next export carries it. A+ /// delta window resumes from where the failed one started, with what+ /// accrued meanwhile added on; a closed session's cumulative series wait+ /// for the next export to carry their final values.+ pub fn export_failed(&mut self, taken: Exported) {+ for (key, value) in taken.counters {+ *self.counters.entry(key).or_insert(0.0) += value;+ }+ self.closed_sessions.extend(taken.closed_sessions);+ if self.cfg.temporality == Temporality::Delta {+ self.last_export_nanos = taken.last_export_nanos;+ self.dropped_reported = taken.dropped_reported;+ }}}@@ -1385,12 +1449,20 @@ impl Worker {return;}self.metrics_dirty = false;- self.state.exported(now, dropped);+ let taken = self.state.exported(now, dropped);let body = target.protocol.encode(|| encode::metrics_json(&self.origin, &metrics),|| encode::metrics_proto(&self.origin, &metrics),);- self.post(&target, body, "metrics").await;+ if !self.post(&target, body, "metrics").await {+ // No 2xx: a delta window that was cleared would otherwise be lost+ // for good, so the next export carries it again. An export that+ // did land but whose answer never came back is then counted twice;+ // that is rarer, and smaller, than losing every failed window.+ self.state.export_failed(taken);+ self.metrics_dirty = true;+ log::debug!("telemetry: metrics kept for the next export");+ }}async fn export_logs(&mut self) {@@ -1427,7 +1499,9 @@ impl Worker {/// retried: no collector is listening, and waiting on one would only hold/// up the process's exit. Failures are the collector's problem, not the/// run's: logged at debug (never the URL's headers) and otherwise ignored.- async fn post(&self, target: &Target, body: Vec<u8>, signal: &str) {+ /// Returns whether the collector accepted the batch, so metrics can keep+ /// a window whose export failed.+ async fn post(&self, target: &Target, body: Vec<u8>, signal: &str) -> bool {let mut request = self.client.post(&target.url)@@ -1439,7 +1513,7 @@ impl Worker {// A byte body clones by reference count, so the retry copies nothing.let retry = request.try_clone();let delay = match request.send().await {- Ok(response) if response.status().is_success() => return,+ Ok(response) if response.status().is_success() => return true,Ok(response) => {let status = response.status();let retry_after =@@ -1453,14 +1527,18 @@ impl Worker {None}};- let (Some(delay), Some(retry)) = (delay, retry) else { return };+ let (Some(delay), Some(retry)) = (delay, retry) else { return false };tokio::time::sleep(delay).await;match retry.send().await {- Ok(response) if response.status().is_success() => {}+ Ok(response) if response.status().is_success() => true,Ok(response) => {- log::debug!("telemetry: {signal} export rejected on retry, dropped: HTTP {}", response.status())+ log::debug!("telemetry: {signal} export rejected on retry: HTTP {}", response.status());+ false+ }+ Err(e) => {+ log::debug!("telemetry: {signal} export failed on retry: {}", e.without_url());+ false}- Err(e) => log::debug!("telemetry: {signal} export failed on retry, dropped: {}", e.without_url()),}}}diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rsindex 5e7b8e181..153b04618 100644--- a/src-tauri/src/core/agent/otel/tests.rs+++ b/src-tauri/src/core/agent/otel/tests.rs@@ -1153,3 +1153,128 @@ fn every_claude_code_signal_has_a_jan_equivalent_or_a_reason() {}}}++#[test]+fn a_turn_carries_its_runs_session() {+ let state = fold(+ cfg_with(false, false),+ None,+ &[provenance(None, "sess-1"), StreamEvent::Step { index: 1, max: 0 }],+ );+ assert_eq!(+ point(&state, "jan_agent.turn.count", &[("agent", "main"), ("session.id", "sess-1")]),+ Some(PointValue::Int(1))+ );+}++#[test]+fn delta_drops_wait_for_a_session_to_carry_them() {+ let cfg = Arc::new(cfg_temporality("delta"));+ let mut state = State::new(Arc::clone(&cfg), None);+ // Dropped before any run started: no session to put them in, so they+ // are held rather than sent as the one point without a session.+ assert!(state.metrics(100, 4).is_empty());+ let _ = state.exported(100, 4);+ start_run(&mut state, "sess-1");+ let metrics = state.metrics(200, 4);+ assert_eq!(+ point_in(&metrics, "jan_agent.telemetry.dropped", &[("session.id", "sess-1")]).map(|p| p.0),+ Some(PointValue::Int(4)),+ "the held drops go out with the first session"+ );+ let _ = state.exported(200, 4);+ assert!(state.metrics(300, 4).iter().all(|m| m.name != "jan_agent.telemetry.dropped"));+}++#[test]+fn a_failed_delta_export_puts_its_window_back() {+ let cfg = Arc::new(cfg_temporality("delta"));+ let mut state = State::new(Arc::clone(&cfg), None);+ let started = state.last_export_nanos;+ start_run(&mut state, "sess-1");+ feed(&mut state, &cfg, &[provenance(None, "sess-1"), usage(10, 1, 0, 0)]);+ let input = [("type", "input"), ("session.id", "sess-1")];+ assert_eq!(point_in(&state.metrics(100, 2), "jan_agent.token.usage", &input).map(|p| p.0), Some(PointValue::Int(10)));+ let taken = state.exported(100, 2);+ // More accrues while the export is in flight, then the export fails.+ feed(&mut state, &cfg, &[provenance(None, "sess-1"), usage(5, 0, 0, 0)]);+ state.export_failed(taken);+ let retry = state.metrics(200, 2);+ assert_eq!(+ point_in(&retry, "jan_agent.token.usage", &input),+ Some((PointValue::Int(15), started, 200)),+ "the failed window and what accrued since, over the whole span"+ );+ assert_eq!(+ point_in(&retry, "jan_agent.telemetry.dropped", &[]).map(|p| p.0),+ Some(PointValue::Int(2)),+ "drops the failed export carried are reported again"+ );+ assert!(retry.iter().any(|m| m.name == "jan_agent.session.count"), "nothing the failed window held is lost");+}++#[test]+fn a_failed_cumulative_export_keeps_a_closed_sessions_final_values() {+ let cfg = Arc::new(cfg_temporality("cumulative"));+ let mut state = State::new(Arc::clone(&cfg), None);+ start_run(&mut state, "sess-a");+ feed(&mut state, &cfg, &[provenance(None, "sess-a"), usage(10, 1, 0, 0)]);+ state.apply(Instant::now(), 3, Signal::SessionClosed { session: "sess-a".into() });+ let has_a = |metrics: &[Metric]| {+ point_in(metrics, "jan_agent.token.usage", &[("type", "input"), ("session.id", "sess-a")]).is_some()+ };+ let taken = state.exported(100, 0);+ assert!(!has_a(&state.metrics(150, 0)), "evicted once handed to an export");+ state.export_failed(taken);+ assert!(has_a(&state.metrics(200, 0)), "back until an export actually carries it");+ let _ = state.exported(200, 0);+ assert!(!has_a(&state.metrics(300, 0)));+}++fn cfg_delta_for(url: &str) -> Config {+ let url = url.to_string();+ let env = move |key: &str| match key {+ config::ENABLE_ENV => Some("1".to_string()),+ "OTEL_EXPORTER_OTLP_ENDPOINT" => Some(url.clone()),+ "OTEL_EXPORTER_OTLP_PROTOCOL" => Some("http/json".to_string()),+ "OTEL_EXPORTER_OTLP_TIMEOUT" => Some("500".to_string()),+ "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE" => Some("delta".to_string()),+ _ => None,+ };+ config::resolve(&env, None, None).unwrap()+}++#[tokio::test]+async fn a_delta_window_whose_export_failed_goes_out_with_the_next() {+ // The first run's logs and metrics are both refused, retry included+ // (four 503s); the second run's exports land.+ let (url, seen) = collector_refusing(false, 4).await;+ let t = Telemetry::start(cfg_delta_for(&url), None, "0.0.0-test");+ scripted_run(&t);+ scripted_run(&t);+ t.shutdown(Duration::from_secs(5)).await;+ let seen = seen.lock().unwrap().clone();+ let metrics: Vec<Value> = seen+ .iter()+ .filter(|(p, _)| p == "/v1/metrics")+ .map(|(_, b)| serde_json::from_slice(b).unwrap())+ .collect();+ let input_tokens = |body: &Value| -> Option<i64> {+ body["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]+ .as_array()?+ .iter()+ .find(|m| m["name"] == "jan_agent.token.usage")?["sum"]["dataPoints"]+ .as_array()?+ .iter()+ .find(|p| p["attributes"].to_string().contains("\"input\""))?["asInt"]+ .as_str()?+ .parse()+ .ok()+ };+ let landed = metrics.last().expect("a metrics POST landed");+ assert_eq!(+ input_tokens(landed),+ Some(18),+ "the refused window (9) and the next (9) arrive together: {metrics:?}"+ );+}