Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): delta temporality, one export retry, and bounded telemetry series
thinhlpg133dfa691070
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 300921c86..39e129516 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -2723,6 +2723,23 @@ fn latest_user_text(messages: &[serde_json::Value]) -> Option<String> {}}+/// The prompt a run was started with: [`latest_user_text`], but only when that+/// user message is still the conversation's last word, reminders aside. A run+/// that continues or resumes a conversation ending in an assistant or tool+/// message was handed no new prompt, so telemetry must not count one.+fn new_user_prompt(messages: &[serde_json::Value]) -> Option<String> {+ let last = messages.iter().rev().find(|m| {+ !(m.get("role").and_then(|v| v.as_str()) == Some("user")+ && crate::core::agent::reminder::is_reminder_only(+ m.get("content").unwrap_or(&serde_json::Value::Null),+ ))+ })?;+ if last.get("role").and_then(|v| v.as_str()) != Some("user") {+ return None;+ }+ latest_user_text(messages)+}+/// Assembles the run's system prompt: `override_prompt` (a subagent's/// definition prompt) replaces the assistant identity when set, but the/// project-context and tool-use guidance from `compose_system_prompt` is still@@ -3155,6 +3172,9 @@ async fn orchestrate_inner(// is the whole prompt -- still placed below the history, so the arrangement// does not depend on which half happens to be empty.let submitted_prompt = latest_user_text(&conversation_messages);+ // What telemetry counts as a prompt: narrower than `submitted_prompt`,+ // which `UserPromptSubmit` below still fires with.+ let new_prompt = new_user_prompt(&conversation_messages);let mut transcript =crate::core::agent::transcript::Transcript::from_history(conversation_messages);if let Some(composed) = stable_system.as_ref().filter(|c| !c.prefix.is_empty()) {@@ -3447,7 +3467,7 @@ async fn orchestrate_inner(let _telemetry_run = crate::core::agent::otel::RunScope::begin(session_id.as_deref(),run_id.as_deref(),- submitted_prompt.as_deref(),+ new_prompt.as_deref(),);tools.fire_hooks(@@ -4773,6 +4793,37 @@ mod tests {use std::collections::VecDeque;use std::sync::Mutex as StdMutex;+ /// Telemetry's `user_prompt` count: a run continuing or resuming a+ /// conversation that ends in the model's or a tool's turn was handed no+ /// new prompt, even though an earlier user message is still in history.+ #[test]+ fn only_a_trailing_user_message_is_a_new_prompt() {+ let reminder =+ json!({"role": "user", "content": crate::core::agent::reminder::wrap("note")});+ let asked = json!({"role": "user", "content": "fix the bug"});+ let answered = json!({"role": "assistant", "content": "done"});+ let tool = json!({"role": "tool", "tool_call_id": "c1", "content": "ok"});+ let text = |messages: &[serde_json::Value]| new_user_prompt(messages);+ assert_eq!(text(std::slice::from_ref(&asked)).as_deref(), Some("fix the bug"));+ assert_eq!(+ text(&[asked.clone(), reminder.clone()]).as_deref(),+ Some("fix the bug"),+ "a trailing reminder is not a turn"+ );+ assert_eq!(+ text(&[asked.clone(), answered.clone()]),+ None,+ "continue after an answer"+ );+ assert_eq!(+ text(&[asked.clone(), answered, tool.clone()]),+ None,+ "resume with a tool result"+ );+ assert_eq!(text(&[asked, tool, reminder]), None);+ assert_eq!(text(&[]), None);+ }+/// The cache-prefix contract from #340: across turns the system prompt at/// message 0 and the tool schema must be byte-identical, so a provider can/// cache them; changing guidance is appended after the conversation.diff --git a/src-tauri/src/core/agent/otel/config.rs b/src-tauri/src/core/agent/otel/config.rsindex 12dab3c60..73a6725de 100644--- a/src-tauri/src/core/agent/otel/config.rs+++ b/src-tauri/src/core/agent/otel/config.rs@@ -12,6 +12,8 @@use std::time::Duration;+use super::encode::Temporality;+/// Wire encoding for an OTLP/HTTP export.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Protocol {@@ -68,6 +70,9 @@ pub struct Config {/// `OTEL_METRICS_INCLUDE_SESSION_ID` (default on): tag metric points with/// `session.id`. Off keeps a backend's series count bounded.pub metrics_session_id: bool,+ /// `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE`: cumulative (the+ /// spec's default) or delta, which a backend that sums points needs.+ pub temporality: Temporality,/// Human-readable problems with the configuration, for the caller to log.pub warnings: Vec<String>,}@@ -198,6 +203,22 @@ pub fn resolve(.unwrap_or(default),)};+ // Every metric here is a monotonic counter, so `lowmemory` -- delta for+ // synchronous counters, per the spec -- is delta too.+ let temporality = match get("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE")+ .map(|v| v.to_ascii_lowercase())+ .as_deref()+ {+ None | Some("cumulative") => Temporality::Cumulative,+ Some("delta" | "lowmemory") => Temporality::Delta,+ Some(other) => {+ warnings.push(format!(+ "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE={other} is not supported \+ (only cumulative, delta and lowmemory); using cumulative"+ ));+ Temporality::Cumulative+ }+ };let gate = |key: &str| get(key).as_deref().and_then(parse_flag).unwrap_or(false);Some(Config {metrics,@@ -215,6 +236,7 @@ pub fn resolve(.as_deref().and_then(parse_flag).unwrap_or(true),+ temporality,warnings,})}@@ -309,6 +331,7 @@ mod tests {assert_eq!(c.metric_interval, Duration::from_secs(60));assert!(!c.log_user_prompts && !c.log_tool_details);assert!(c.metrics_session_id);+ assert_eq!(c.temporality, Temporality::Cumulative);assert!(c.warnings.is_empty());}@@ -357,6 +380,39 @@ mod tests {assert!(!c.metrics_session_id);}+ #[test]+ fn the_temporality_preference_picks_delta_or_cumulative() {+ let pick = |value: &str| {+ let c = resolve(+ &env(&[+ (ENABLE_ENV, "1"),+ ("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE", value),+ ]),+ None,+ None,+ )+ .unwrap();+ (c.temporality, c.warnings.len())+ };+ assert_eq!(pick("delta"), (Temporality::Delta, 0));+ assert_eq!(+ pick("DELTA"),+ (Temporality::Delta, 0),+ "case-insensitive, as the spec says"+ );+ assert_eq!(+ pick("lowmemory"),+ (Temporality::Delta, 0),+ "delta for counters"+ );+ assert_eq!(pick("cumulative"), (Temporality::Cumulative, 0));+ assert_eq!(+ pick("sometimes"),+ (Temporality::Cumulative, 1),+ "unknown warns and keeps the default"+ );+ }+#[test]fn grpc_falls_back_and_console_disables_the_signal() {let c = resolve(diff --git a/src-tauri/src/core/agent/otel/encode.rs b/src-tauri/src/core/agent/otel/encode.rsindex 87dea70e4..f2d700fec 100644--- a/src-tauri/src/core/agent/otel/encode.rs+++ b/src-tauri/src/core/agent/otel/encode.rs@@ -1,5 +1,6 @@-//! OTLP wire encoding for the three signals this exporter sends: cumulative-//! monotonic sums (metrics), event log records (logs) and spans (traces).+//! OTLP wire encoding for the three signals this exporter sends: monotonic+//! sums, delta or cumulative (metrics), event log records (logs) and spans+//! (traces).//!//! Hand-rolled rather than generated: the subset is small and stable (OTLP v1//! is frozen for these messages), and carrying `prost` + the generated proto@@ -24,7 +25,7 @@ pub enum AnyValue {pub type Attrs = Vec<(String, AnyValue)>;-/// One point of a cumulative, monotonic sum.+/// One point of a monotonic sum: the total over `start..time`.#[derive(Debug, Clone, PartialEq)]pub struct Point {pub attrs: Attrs,@@ -39,12 +40,22 @@ pub enum PointValue {Double(f64),}-/// A counter, exported as an OTLP `Sum` (cumulative, monotonic).+/// OTLP `AggregationTemporality`. The values are the wire enum's.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Temporality {+ /// Each point is what accrued since the previous export.+ Delta = 1,+ /// Each point is the running total since the exporter started.+ Cumulative = 2,+}++/// A counter, exported as an OTLP monotonic `Sum`.#[derive(Debug, Clone, PartialEq)]pub struct Metric {pub name: String,pub description: String,pub unit: String,+ pub temporality: Temporality,pub points: Vec<Point>,}@@ -138,8 +149,11 @@ pub fn metrics_json(origin: &Origin, metrics: &[Metric]) -> Vec<u8> {"name": m.name,"description": m.description,"unit": m.unit,- // 2 = AGGREGATION_TEMPORALITY_CUMULATIVE- "sum": { "dataPoints": points, "aggregationTemporality": 2, "isMonotonic": true },+ "sum": {+ "dataPoints": points,+ "aggregationTemporality": m.temporality as u8,+ "isMonotonic": true,+ },})}).collect();@@ -307,7 +321,7 @@ pub fn metrics_proto(origin: &Origin, metrics: &[Metric]) -> Vec<u8> {attrs_pb(&mut point, 7, &p.attrs);pb_bytes(&mut sum, 1, &point);}- pb_varint(&mut sum, 2, 2);+ pb_varint(&mut sum, 2, m.temporality as u64);pb_varint(&mut sum, 3, 1);let mut metric = Vec::new();pb_str(&mut metric, 1, &m.name);@@ -402,11 +416,12 @@ mod tests {}}- fn counter() -> Metric {+ fn counter(temporality: Temporality) -> Metric {Metric {name: "jan_agent.token.usage".into(),description: "tokens".into(),unit: "tokens".into(),+ temporality,points: vec![Point {attrs: vec![("type".into(), AnyValue::Str("input".into()))],start_unix_nano: 1,@@ -470,8 +485,8 @@ mod tests {}#[test]- fn metrics_protobuf_nests_a_cumulative_sum_under_its_resource() {- let bytes = metrics_proto(&origin(), &[counter()]);+ fn metrics_protobuf_nests_a_monotonic_sum_under_its_resource() {+ let bytes = metrics_proto(&origin(), &[counter(Temporality::Cumulative)]);let resource_metrics = only(&bytes, 1);let scope_metrics = only(&resource_metrics, 2);let metric = only(&scope_metrics, 2);@@ -479,6 +494,9 @@ mod tests {let sum = only(&metric, 7);assert_eq!(only(&sum, 2)[0], 2, "cumulative");assert_eq!(only(&sum, 3)[0], 1, "monotonic");+ let delta = metrics_proto(&origin(), &[counter(Temporality::Delta)]);+ let delta_sum = only(&only(&only(&only(&delta, 1), 2), 2), 7);+ assert_eq!(only(&delta_sum, 2)[0], 1, "delta");let point = only(&sum, 1);assert_eq!(i64::from_le_bytes(only(&point, 6).try_into().unwrap()), 42);let resource = only(&resource_metrics, 1);@@ -504,7 +522,11 @@ mod tests {#[test]fn json_follows_the_otlp_json_mapping() {- let v: Value = serde_json::from_slice(&metrics_json(&origin(), &[counter()])).unwrap();+ let v: Value = serde_json::from_slice(&metrics_json(+ &origin(),+ &[counter(Temporality::Cumulative)],+ ))+ .unwrap();let metric = &v["resourceMetrics"][0]["scopeMetrics"][0]["metrics"][0];assert_eq!(metric["name"], "jan_agent.token.usage");assert_eq!(metric["sum"]["aggregationTemporality"], 2);diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rsindex db778b55e..06f0cd301 100644--- a/src-tauri/src/core/agent/otel/mod.rs+++ b/src-tauri/src/core/agent/otel/mod.rs@@ -40,7 +40,7 @@ use tokio::sync::{mpsc, oneshot};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::session::TokenRates;use config::{Config, Target};-use encode::{AnyValue, Attrs, LogRecord, Metric, Origin, Point, PointValue, Span};+use encode::{AnyValue, Attrs, LogRecord, Metric, Origin, Point, PointValue, Span, Temporality};/// Signals that can wait for the worker. Generous: a busy turn emits a few/// dozen, and the worker drains continuously.@@ -55,6 +55,11 @@ const SPAN_BATCH: usize = 512;const CONTENT_CAP: usize = 4096;/// Cap on an error message carried by `api_error`.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.+const MAX_RETRY_DELAY: Duration = Duration::from_secs(10);/// Per-token prices for `(provider, model)`, when the catalog knows them.pub type Pricer = Box<dyn Fn(Option<&str>, &str) -> Option<TokenRates> + Send + Sync>;@@ -91,6 +96,11 @@ pub enum Signal {child: Option<Child>,event: EventSignal,},+ /// A session is gone for good (an RPC `session/archive`): nothing more+ /// will be reported under its id.+ SessionClosed {+ session: String,+ },Flush,}@@ -414,6 +424,16 @@ pub fn compaction(message_count: usize) {}}+/// A session will report nothing more (an RPC `session/archive`), so its+/// metric series can stop being exported once their last values are out.+pub fn session_closed(session: &str) {+ if let Some(t) = global() {+ t.send(Signal::SessionClosed {+ session: session.to_string(),+ });+ }+}+/// Export whatever is buffered and stop, bounded by [`SHUTDOWN_TIMEOUT`].pub async fn shutdown() {if let Some(t) = global() {@@ -421,6 +441,70 @@ pub async fn shutdown() {}}+/// Run `work`, but if the process is told to stop first (SIGINT or SIGTERM;+/// Ctrl-C on Windows), drop it and export what telemetry has buffered before+/// dying of that signal. Dropping the work is what reports an interrupted+/// run: its [`RunScope`] sends the run's end and active time on drop. With+/// telemetry off the process dies at once, as it would without this.+pub async fn flush_on_termination<F: std::future::Future>(work: F) -> F::Output {+ // Boxed so the work can be dropped before the flush, not after it.+ let mut work = Box::pin(work);+ tokio::select! {+ output = &mut work => output,+ signal = termination() => {+ if global().is_some() {+ drop(work);+ shutdown().await;+ }+ die_of(signal)+ }+ }+}++/// The stop signal that arrived: its number.+#[cfg(unix)]+async fn termination() -> i32 {+ use tokio::signal::unix::{signal, SignalKind};+ let (Ok(mut interrupt), Ok(mut terminate)) = (+ signal(SignalKind::interrupt()),+ signal(SignalKind::terminate()),+ ) else {+ // No handler could be installed: the default action still applies.+ return std::future::pending().await;+ };+ tokio::select! {+ _ = interrupt.recv() => libc::SIGINT,+ _ = terminate.recv() => libc::SIGTERM,+ }+}++#[cfg(windows)]+async fn termination() -> i32 {+ if tokio::signal::ctrl_c().await.is_err() {+ return std::future::pending().await;+ }+ 0+}++/// Exit the way the signal's default action would have: re-raised with the+/// default disposition, so a parent still sees a death by that signal.+#[cfg(unix)]+fn die_of(signal: i32) -> ! {+ // SAFETY: restoring the default disposition installs no handler code, and+ // the raise that follows ends the process.+ unsafe {+ libc::signal(signal, libc::SIG_DFL);+ libc::raise(signal);+ }+ std::process::exit(128 + signal)+}++/// `STATUS_CONTROL_C_EXIT`, what a console process ended by Ctrl-C exits with.+#[cfg(windows)]+fn die_of(_: i32) -> ! {+ std::process::exit(0xC000_013A_u32 as i32)+}+/// Brackets one orchestration run: reports its start (and the prompt that/// started it) now, and its end and active time when dropped -- so a cancelled/// run, whose future is dropped mid-await, is still accounted for.@@ -538,7 +622,17 @@ pub struct State {cfg: Arc<Config>,pricer: Option<Pricer>,start_nanos: u64,+ /// Cumulative: the running totals since `start_nanos`. Delta: what accrued+ /// since the last export, which [`State::exported`] clears.counters: BTreeMap<SeriesKey, f64>,+ /// When the last metrics export was taken: a delta point's start.+ last_export_nanos: u64,+ /// The dropped-signal total the last export reported, so a delta point+ /// carries only what was dropped since.+ dropped_reported: u64,+ /// Sessions closed since the last export, whose cumulative series are+ /// evicted once that export carried their final values.+ closed_sessions: HashSet<String>,logs: Vec<LogRecord>,sessions_seen: HashSet<String>,/// The session each run (`None` = the main run) last reported, from its@@ -590,11 +684,15 @@ fn metric_attr(key: &str, value: impl Into<String>) -> (String, String) {impl State {pub fn new(cfg: Arc<Config>, pricer: Option<Pricer>) -> Self {+ let now = wall_nanos();Self {cfg,pricer,- start_nanos: wall_nanos(),+ start_nanos: now,counters: BTreeMap::new(),+ last_export_nanos: now,+ dropped_reported: 0,+ closed_sessions: HashSet::new(),logs: Vec::new(),sessions_seen: HashSet::new(),run_session: HashMap::new(),@@ -825,10 +923,27 @@ impl State {);}Signal::Event { child, event } => self.apply_event(at, wall, child, event),+ Signal::SessionClosed { session } => self.close_session(session),Signal::Flush => {}}}+ /// Forget a closed session. Its per-session bookkeeping goes now; its+ /// cumulative series go after the next export, which carries their final+ /// values. Delta needs no eviction: an export already clears every series.+ fn close_session(&mut self, session: String) {+ self.sessions_seen.remove(&session);+ self.prompt_ids.remove(&session);+ self.interaction_seq.remove(&session);+ self.run_session.retain(|_, s| *s != session);+ if self.main_session.as_ref() == Some(&session) {+ self.main_session = None;+ }+ if self.cfg.temporality == Temporality::Cumulative {+ self.closed_sessions.insert(session);+ }+ }+fn apply_event(&mut self, at: Instant, wall: u64, child: Option<Child>, event: EventSignal) {let run = child.as_ref().map(|c| c.run_id.clone());match event {@@ -1068,8 +1183,19 @@ impl State {self.logs.len()}- /// Every series so far, cumulative since the exporter started.+ /// The series to export at `now`: every running total since the exporter+ /// started (cumulative), or only what changed since the last export+ /// (delta). `dropped` is the process's running total of dropped signals.+ /// Pure: [`State::exported`] records that this snapshot went out.pub fn metrics(&self, now: u64, dropped: u64) -> Vec<Metric> {+ let temporality = self.cfg.temporality;+ let (start, dropped) = match temporality {+ Temporality::Cumulative => (self.start_nanos, dropped),+ Temporality::Delta => (+ self.last_export_nanos,+ dropped.saturating_sub(self.dropped_reported),+ ),+ };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));@@ -1085,7 +1211,7 @@ impl State {.iter().map(|(k, v)| (k.clone(), AnyValue::Str(v.clone()))).collect(),- start_unix_nano: self.start_nanos,+ start_unix_nano: start,time_unix_nano: now,value: if is_double {PointValue::Double(value)@@ -1103,11 +1229,37 @@ impl State {name: name.to_string(),description: description.to_string(),unit: unit.to_string(),+ temporality,points,}}).collect()}++ /// 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) {+ match self.cfg.temporality {+ Temporality::Delta => {+ self.counters.clear();+ self.last_export_nanos = now;+ 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))+ });+ }+ }+ }+ }}// ── Export ───────────────────────────────────────────────────────────────────@@ -1209,15 +1361,21 @@ impl Worker {}async fn export_metrics(&mut self) {- let Some(target) = self.cfg.metrics.clone() else { return };+ let Some(target) = self.cfg.metrics.clone() else {+ // Nothing will read these series, so keep them bounded all the same.+ self.state.exported(wall_nanos(), 0);+ return;+ };if !self.metrics_dirty {return;}- let metrics = self.state.metrics(wall_nanos(), self.dropped.load(Ordering::Relaxed));+ let (now, dropped) = (wall_nanos(), self.dropped.load(Ordering::Relaxed));+ let metrics = self.state.metrics(now, dropped);if metrics.is_empty() {return;}self.metrics_dirty = false;+ self.state.exported(now, dropped);let body = target.protocol.encode(|| encode::metrics_json(&self.origin, &metrics),|| encode::metrics_proto(&self.origin, &metrics),@@ -1254,8 +1412,11 @@ impl Worker {self.post(&target, body, "traces").await;}- /// One POST. Failures are the collector's problem, not the run's: logged- /// at debug (never the URL's headers) and otherwise ignored.+ /// One export, retried once when the collector answers with one of OTLP's+ /// retryable statuses (429/502/503/504). A refused connection is not+ /// 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) {let mut request = self.client@@ -1265,15 +1426,49 @@ impl Worker {for (k, v) in &target.headers {request = request.header(k.as_str(), v.as_str());}- match request.send().await {+ // 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) => {+ let status = response.status();+ let retry_after =+ response.headers().get(reqwest::header::RETRY_AFTER).and_then(|v| v.to_str().ok());+ let delay = retry_delay(status.as_u16(), retry_after);+ log::debug!("telemetry: {signal} export rejected: HTTP {status}");+ delay+ }+ Err(e) => {+ log::debug!("telemetry: {signal} export failed: {}", e.without_url());+ None+ }+ };+ let (Some(delay), Some(retry)) = (delay, retry) else { return };+ tokio::time::sleep(delay).await;+ match retry.send().await {Ok(response) if response.status().is_success() => {}Ok(response) => {- log::debug!("telemetry: {signal} export rejected: HTTP {}", response.status())+ log::debug!("telemetry: {signal} export rejected on retry, dropped: HTTP {}", response.status())}- Err(e) => log::debug!("telemetry: {signal} export failed: {}", e.without_url()),+ Err(e) => log::debug!("telemetry: {signal} export failed on retry, dropped: {}", e.without_url()),}}}+/// How long to wait before the one retry of a rejected export, or `None` for+/// no retry: the status is not one OTLP calls retryable, or the collector+/// asked for a longer wait than [`MAX_RETRY_DELAY`] -- retrying sooner than it+/// asked would only be refused again, and a longer wait would stall every+/// other export behind this one.+fn retry_delay(status: u16, retry_after: Option<&str>) -> Option<Duration> {+ if !matches!(status, 429 | 502 | 503 | 504) {+ return None;+ }+ // Seconds, the form collectors send. An HTTP-date is rare enough here to+ // fall back to the default wait rather than parse.+ let delay = retry_after.and_then(|v| v.trim().parse::<u64>().ok()).map(Duration::from_secs).unwrap_or(RETRY_DELAY);+ (delay <= MAX_RETRY_DELAY).then_some(delay)+}+#[cfg(test)]mod tests;diff --git a/src-tauri/src/core/agent/otel/tests.rs b/src-tauri/src/core/agent/otel/tests.rsindex 03974624e..5e7b8e181 100644--- a/src-tauri/src/core/agent/otel/tests.rs+++ b/src-tauri/src/core/agent/otel/tests.rs@@ -331,14 +331,26 @@ fn session_id_can_be_kept_off_metric_points() {/// A tokio listener standing in for a collector: records `(path, body)` of/// every POST, answers 200 or, when `stall`, never answers at all.async fn collector(stall: bool) -> (String, Arc<Mutex<Vec<(String, Vec<u8>)>>>) {+ collector_refusing(stall, 0).await+}++/// [`collector`] whose first `refuse` POSTs are answered `503` with+/// `Retry-After: 0`, the way a collector that cannot persist a batch answers.+async fn collector_refusing(+ stall: bool,+ refuse: usize,+) -> (String, Arc<Mutex<Vec<(String, Vec<u8>)>>>) {+ use std::sync::atomic::AtomicUsize;use tokio::io::{AsyncReadExt, AsyncWriteExt};let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let url = format!("http://{}", listener.local_addr().unwrap());let seen = Arc::new(Mutex::new(Vec::new()));let sink = Arc::clone(&seen);+ let refused = Arc::new(AtomicUsize::new(0));tokio::spawn(async move {while let Ok((mut stream, _)) = listener.accept().await {let sink = Arc::clone(&sink);+ let refused = Arc::clone(&refused);tokio::spawn(async move {if stall {tokio::time::sleep(Duration::from_secs(3600)).await;@@ -365,9 +377,12 @@ async fn collector(stall: bool) -> (String, Arc<Mutex<Vec<(String, Vec<u8>)>>>)}let path = head.split_whitespace().nth(1).unwrap_or("").to_string();sink.lock().unwrap().push((path, buf[end + 4..end + 4 + length].to_vec()));- let _ = stream- .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")- .await;+ let answer: &[u8] = if refused.fetch_add(1, Ordering::SeqCst) < refuse {+ b"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"+ } else {+ b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"+ };+ let _ = stream.write_all(answer).await;return;}});@@ -478,7 +493,236 @@ async fn a_dead_collector_is_not_the_runs_problem() {};let t = Telemetry::start(cfg_for(&format!("http://127.0.0.1:{port}"), "http/json"), None, "0");scripted_run(&t);+ let started = std::time::Instant::now();t.shutdown(Duration::from_secs(2)).await;+ // No collector is listening, so the exit must not wait on one: no retry,+ // no sleep. Not timed on Windows, where a connect to a closed port is+ // itself retried before it fails, so the exports alone took ~1s in CI.+ if cfg!(not(windows)) {+ assert!(started.elapsed() < RETRY_DELAY, "{:?}", started.elapsed());+ }+}++#[tokio::test]+async fn a_batch_the_collector_asks_to_retry_is_sent_again_once() {+ let posts = |seen: &[(String, Vec<u8>)], path: &str| {+ seen.iter()+ .filter(|(p, _)| p == path)+ .map(|(_, b)| b.clone())+ .collect::<Vec<_>>()+ };+ // The run's end exports logs, then metrics. One 503 + Retry-After: 0+ // hits the logs batch, and its retry lands.+ let (url, seen) = collector_refusing(false, 1).await;+ let t = Telemetry::start(cfg_for(&url, "http/json"), None, "0.0.0-test");+ scripted_run(&t);+ t.shutdown(Duration::from_secs(5)).await;+ let seen = seen.lock().unwrap().clone();+ let logs = posts(&seen, "/v1/logs");+ assert_eq!(logs.len(), 2, "{seen:?}");+ assert_eq!(logs[0], logs[1], "the retry resends the same batch");+ assert_eq!(posts(&seen, "/v1/metrics").len(), 1, "{seen:?}");++ // Refused again on the retry, the batch is dropped: there is no third try.+ let (url, seen) = collector_refusing(false, 2).await;+ let t = Telemetry::start(cfg_for(&url, "http/json"), None, "0.0.0-test");+ scripted_run(&t);+ t.shutdown(Duration::from_secs(5)).await;+ let seen = seen.lock().unwrap().clone();+ assert_eq!(posts(&seen, "/v1/logs").len(), 2, "{seen:?}");+ assert_eq!(posts(&seen, "/v1/metrics").len(), 1, "{seen:?}");+}++#[test]+fn only_otlps_retryable_statuses_are_retried_and_within_the_cap() {+ assert_eq!(retry_delay(503, Some("5")), Some(Duration::from_secs(5)));+ assert_eq!(retry_delay(429, None), Some(RETRY_DELAY));+ assert_eq!(+ retry_delay(502, Some("Wed, 21 Oct 2015 07:28:00 GMT")),+ Some(RETRY_DELAY)+ );+ assert_eq!(retry_delay(504, Some("0")), Some(Duration::ZERO));+ assert_eq!(+ retry_delay(503, Some("3600")),+ None,+ "longer than the cap: dropped, not retried early"+ );+ for status in [400, 401, 404, 413, 500] {+ assert_eq!(retry_delay(status, Some("1")), None, "{status}");+ }+}++fn cfg_temporality(value: &'static str) -> Config {+ let env = move |key: &str| match key {+ config::ENABLE_ENV => Some("1".to_string()),+ "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE" => Some(value.to_string()),+ _ => None,+ };+ config::resolve(&env, None, None).unwrap()+}++fn feed(state: &mut State, cfg: &Config, events: &[StreamEvent]) {+ for event in events {+ if let Some(signal) = classify(cfg, event, None) {+ state.apply(Instant::now(), 2, signal);+ }+ }+}++fn start_run(state: &mut State, session: &str) {+ state.apply(+ Instant::now(),+ 1,+ Signal::RunStart {+ session: Some(session.into()),+ run_id: None,+ prompt: Some((1, None)),+ },+ );+}++/// `(value, start, time)` of the point of `name` whose attributes include `want`.+fn point_in(+ metrics: &[Metric],+ name: &str,+ want: &[(&str, &str)],+) -> Option<(PointValue, u64, u64)> {+ metrics+ .iter()+ .find(|m| m.name == name)?+ .points+ .iter()+ .find_map(|p| {+ want.iter()+ .all(|(k, v)| {+ p.attrs+ .iter()+ .any(|(pk, pv)| pk == k && *pv == AnyValue::Str(v.to_string()))+ })+ .then_some((p.value, p.start_unix_nano, p.time_unix_nano))+ })+}++#[test]+fn delta_exports_only_what_accrued_since_the_last_export() {+ let cfg = Arc::new(cfg_temporality("delta"));+ let mut state = State::new(Arc::clone(&cfg), None);+ start_run(&mut state, "sess-1");+ feed(+ &mut state,+ &cfg,+ &[provenance(None, "sess-1"), usage(10, 1, 0, 0)],+ );+ let first = state.metrics(100, 2);+ assert!(first.iter().all(|m| m.temporality == Temporality::Delta));+ let input = [("type", "input"), ("session.id", "sess-1")];+ assert_eq!(+ point_in(&first, "jan_agent.token.usage", &input).map(|p| p.0),+ Some(PointValue::Int(10))+ );+ assert_eq!(+ point_in(&first, "jan_agent.telemetry.dropped", &[]).map(|p| p.0),+ Some(PointValue::Int(2))+ );+ state.exported(100, 2);++ // Nothing accrued and nothing more was dropped: nothing to send.+ assert!(state.metrics(150, 2).is_empty());++ feed(+ &mut state,+ &cfg,+ &[provenance(None, "sess-1"), usage(5, 0, 0, 0)],+ );+ let second = state.metrics(200, 3);+ // Only this window's tokens, over this window, and no re-send of the+ // series that did not move (output, the session and prompt counts).+ assert_eq!(+ point_in(&second, "jan_agent.token.usage", &input),+ Some((PointValue::Int(5), 100, 200))+ );+ assert_eq!(+ point_in(&second, "jan_agent.token.usage", &[("type", "output")]),+ None+ );+ assert!(second+ .iter()+ .all(|m| m.name != "jan_agent.session.count" && m.name != "jan_agent.prompt.count"));+ assert_eq!(+ point_in(&second, "jan_agent.telemetry.dropped", &[]).map(|p| p.0),+ Some(PointValue::Int(1))+ );+}++#[test]+fn cumulative_stays_the_running_total() {+ let cfg = Arc::new(cfg_temporality("cumulative"));+ let mut state = State::new(Arc::clone(&cfg), None);+ start_run(&mut state, "sess-1");+ feed(+ &mut state,+ &cfg,+ &[provenance(None, "sess-1"), usage(10, 1, 0, 0)],+ );+ state.exported(100, 0);+ feed(+ &mut state,+ &cfg,+ &[provenance(None, "sess-1"), usage(5, 0, 0, 0)],+ );+ let metrics = state.metrics(200, 0);+ assert!(metrics+ .iter()+ .all(|m| m.temporality == Temporality::Cumulative));+ let (value, start, _) =+ point_in(&metrics, "jan_agent.token.usage", &[("type", "input")]).unwrap();+ assert_eq!(value, PointValue::Int(15));+ assert_eq!(+ start, state.start_nanos,+ "a cumulative point starts when the exporter did"+ );+ assert!(+ point_in(&metrics, "jan_agent.token.usage", &[("type", "output")]).is_some(),+ "unchanged series are re-sent"+ );+}++#[test]+fn a_closed_sessions_cumulative_series_go_once_their_final_values_are_out() {+ let cfg = Arc::new(cfg_temporality("cumulative"));+ let mut state = State::new(Arc::clone(&cfg), None);+ for session in ["sess-a", "sess-b"] {+ start_run(&mut state, session);+ feed(+ &mut state,+ &cfg,+ &[provenance(None, session), usage(10, 1, 0, 0)],+ );+ }+ state.apply(+ Instant::now(),+ 3,+ Signal::SessionClosed {+ session: "sess-a".into(),+ },+ );+ let has = |metrics: &[Metric], s: &str| {+ point_in(+ metrics,+ "jan_agent.token.usage",+ &[("type", "input"), ("session.id", s)],+ )+ .is_some()+ };+ let last = state.metrics(100, 0);+ assert!(+ has(&last, "sess-a"),+ "the export after the close still carries its final totals"+ );+ state.exported(100, 0);+ let after = state.metrics(200, 0);+ assert!(!has(&after, "sess-a"));+ assert!(has(&after, "sess-b"), "a live session's series stay");}#[test]