Skip to main content

lean_ctx_ext/core/
datadog_push.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Agentless Datadog export (GL #401, setup path B).
3//!
4//! Pushes the metrics-contract series straight to the Datadog Metrics API v2
5//! (`POST /api/v2/series`, `DD-API-KEY` header) — no local Agent, no OTel
6//! Collector. Strictly opt-in: **both** `LEAN_CTX_DATADOG_PUSH=1` and
7//! `DD_API_KEY` must be set; a stray `DD_API_KEY` from another tool never
8//! turns on egress by itself.
9//!
10//! Counter semantics: Datadog v2 `count` points are per-interval deltas, not
11//! cumulative totals. The pusher keeps the last pushed totals in-process and
12//! submits deltas; the first cycle only records the baseline (submitting a
13//! lifetime total as one interval would spike every graph). Gauges go out on
14//! every cycle, including the first.
15//!
16//! Tag policy is identical to the `lean_ctx_info` series: five bounded tags
17//! (`project`, `profile`, `agent_role`, `model`, `version`) attached to every
18//! series — bounded values, so Datadog custom-metric cardinality stays flat.
19
20use std::sync::Mutex;
21use std::time::Duration;
22
23const ENABLE_ENV: &str = "LEAN_CTX_DATADOG_PUSH";
24const API_KEY_ENV: &str = "DD_API_KEY";
25const SITE_ENV: &str = "DD_SITE";
26const INTERVAL_ENV: &str = "LEAN_CTX_DATADOG_INTERVAL_SECS";
27
28const DEFAULT_INTERVAL_SECS: u64 = 60;
29const MIN_INTERVAL_SECS: u64 = 10;
30
31/// Datadog v2 metric intake types.
32const TYPE_COUNT: u8 = 1;
33const TYPE_GAUGE: u8 = 3;
34
35/// Cumulative totals as of the previous push — source of the count deltas.
36#[derive(Default, Clone, Copy)]
37struct Baseline {
38    tokens_in: u64,
39    tokens_out: u64,
40    tokens_saved: u64,
41    ledger_tokens: u64,
42    ledger_usd: f64,
43    tool_calls: u64,
44    tool_errors: u64,
45}
46
47static BASELINE: Mutex<Option<Baseline>> = Mutex::new(None);
48
49/// True when the operator explicitly enabled the push exporter.
50pub(crate) fn enabled() -> bool {
51    std::env::var(ENABLE_ENV).is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
52        && std::env::var(API_KEY_ENV).is_ok_and(|v| !v.trim().is_empty())
53}
54
55fn interval() -> Duration {
56    let secs = std::env::var(INTERVAL_ENV)
57        .ok()
58        .and_then(|v| v.parse::<u64>().ok())
59        .unwrap_or(DEFAULT_INTERVAL_SECS)
60        .max(MIN_INTERVAL_SECS);
61    Duration::from_secs(secs)
62}
63
64fn intake_url() -> String {
65    let site = std::env::var(SITE_ENV).unwrap_or_else(|_| "datadoghq.com".to_string());
66    format!("https://api.{site}/api/v2/series")
67}
68
69/// Spawn the background push loop if (and only if) the operator opted in.
70/// Called from long-running entry points (dashboard server). Returns whether
71/// the loop was started.
72pub fn spawn_if_enabled() -> bool {
73    if !enabled() {
74        return false;
75    }
76    std::thread::Builder::new()
77        .name("dd-push".into())
78        .spawn(|| {
79            loop {
80                match push_once() {
81                    Ok(sent) => {
82                        tracing::debug!("datadog push: {sent} series sent");
83                    }
84                    Err(e) => {
85                        tracing::warn!("datadog push failed (will retry): {e}");
86                    }
87                }
88                std::thread::sleep(interval());
89            }
90        })
91        .is_ok()
92}
93
94/// Build and submit one batch. Returns the number of series sent.
95pub(crate) fn push_once() -> Result<usize, String> {
96    let api_key = std::env::var(API_KEY_ENV).map_err(|_| "DD_API_KEY not set".to_string())?;
97    let series = build_series(now_ts());
98    if series.is_empty() {
99        return Ok(0); // first cycle: baseline recorded, gauges follow next tick
100    }
101    let count = series.len();
102    let payload = serde_json::json!({ "series": series });
103    let body = serde_json::to_vec(&payload).map_err(|e| e.to_string())?;
104
105    let agent = crate::core::http_client::ureq_agent(
106        ureq::config::Config::builder()
107            .tls_config(crate::core::http_client::platform_tls_config())
108            .timeout_global(Some(Duration::from_secs(10)))
109            .http_status_as_error(false)
110            .build(),
111    );
112    let resp = agent
113        .post(&intake_url())
114        .header("Content-Type", "application/json")
115        .header("DD-API-KEY", api_key.trim())
116        .send(body.as_slice())
117        .map_err(|e| format!("datadog intake unreachable: {e}"))?;
118
119    let status = resp.status().as_u16();
120    if !(200..300).contains(&status) {
121        let body = resp.into_body().read_to_string().unwrap_or_default();
122        return Err(format!("datadog intake rejected ({status}): {body}"));
123    }
124    Ok(count)
125}
126
127fn now_ts() -> i64 {
128    std::time::SystemTime::now()
129        .duration_since(std::time::UNIX_EPOCH)
130        .map_or(0, |d| d.as_secs() as i64)
131}
132
133/// Extra static tags, e.g. `env:prod,team:platform` — the Datadog-side
134/// equivalent of OTel resource attributes like `deployment.environment`.
135const EXTRA_TAGS_ENV: &str = "LEAN_CTX_DD_TAGS";
136
137fn tags() -> Vec<String> {
138    let mut tags: Vec<String> = super::telemetry::info_tags()
139        .into_iter()
140        .map(|(k, v)| format!("{k}:{v}"))
141        .collect();
142    if let Ok(extra) = std::env::var(EXTRA_TAGS_ENV) {
143        tags.extend(
144            extra
145                .split(',')
146                .map(str::trim)
147                .filter(|t| !t.is_empty() && t.contains(':'))
148                .map(String::from),
149        );
150    }
151    tags
152}
153
154fn series_entry(metric: &str, ty: u8, value: f64, ts: i64, tags: &[String]) -> serde_json::Value {
155    serde_json::json!({
156        "metric": metric,
157        "type": ty,
158        "points": [{ "timestamp": ts, "value": value }],
159        "tags": tags,
160    })
161}
162
163/// Assemble the batch: gauges always, counts as deltas vs. the baseline.
164/// First call returns an empty batch (baseline only) by design.
165fn build_series(ts: i64) -> Vec<serde_json::Value> {
166    let snap = super::telemetry::global_metrics().snapshot();
167    let (ledger_tokens, ledger_usd) = super::telemetry::ledger_totals_cached();
168    let current = Baseline {
169        tokens_in: snap.tokens_input,
170        tokens_out: snap.tokens_output,
171        tokens_saved: snap.tokens_saved,
172        ledger_tokens,
173        ledger_usd,
174        tool_calls: snap.tool_calls_total,
175        tool_errors: snap.tool_calls_error,
176    };
177
178    let Ok(mut guard) = BASELINE.lock() else {
179        return Vec::new();
180    };
181    let Some(prev) = *guard else {
182        *guard = Some(current);
183        return Vec::new();
184    };
185    *guard = Some(current);
186    drop(guard);
187
188    let t = tags();
189    let d = |cur: u64, old: u64| cur.saturating_sub(old) as f64;
190    let mut series = vec![
191        series_entry(
192            "leanctx.tokens.in",
193            TYPE_COUNT,
194            d(current.tokens_in, prev.tokens_in),
195            ts,
196            &t,
197        ),
198        series_entry(
199            "leanctx.tokens.out",
200            TYPE_COUNT,
201            d(current.tokens_out, prev.tokens_out),
202            ts,
203            &t,
204        ),
205        series_entry(
206            "leanctx.tokens.saved",
207            TYPE_COUNT,
208            d(current.tokens_saved, prev.tokens_saved),
209            ts,
210            &t,
211        ),
212        series_entry(
213            "leanctx.tokens.saved_verified",
214            TYPE_COUNT,
215            d(current.ledger_tokens, prev.ledger_tokens),
216            ts,
217            &t,
218        ),
219        series_entry(
220            "leanctx.cost.saved_usd",
221            TYPE_COUNT,
222            (current.ledger_usd - prev.ledger_usd).max(0.0),
223            ts,
224            &t,
225        ),
226        series_entry(
227            "leanctx.tools.calls",
228            TYPE_COUNT,
229            d(current.tool_calls, prev.tool_calls),
230            ts,
231            &t,
232        ),
233        series_entry(
234            "leanctx.tools.errors",
235            TYPE_COUNT,
236            d(current.tool_errors, prev.tool_errors),
237            ts,
238            &t,
239        ),
240    ];
241
242    let verify = crate::core::output_verification::stats_snapshot();
243    series.extend([
244        series_entry(
245            "leanctx.cache.hit_ratio",
246            TYPE_GAUGE,
247            snap.cache_hit_rate,
248            ts,
249            &t,
250        ),
251        series_entry(
252            "leanctx.compression.ratio",
253            TYPE_GAUGE,
254            snap.compression_ratio,
255            ts,
256            &t,
257        ),
258        series_entry(
259            "leanctx.session.uptime_seconds",
260            TYPE_GAUGE,
261            snap.session_uptime_secs as f64,
262            ts,
263            &t,
264        ),
265        series_entry(
266            "leanctx.verification.pass_ratio",
267            TYPE_GAUGE,
268            verify.pass_rate,
269            ts,
270            &t,
271        ),
272    ]);
273    series
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    /// Single sequential test: `BASELINE` is process-global, so the
281    /// baseline → delta → tags assertions must not run as parallel tests.
282    #[test]
283    fn baseline_then_deltas_then_tags() {
284        *BASELINE
285            .lock()
286            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
287
288        // Cycle 1: baseline only, nothing submitted.
289        {
290            let found = &build_series(1000);
291            assert!(found.is_empty(), "{found:?}");
292        }
293
294        // Cycle 2: full batch with counts as deltas, not lifetime totals.
295        let m = super::super::telemetry::global_metrics();
296        m.record_tokens(100, 10, 500);
297        let batch = build_series(1060);
298        assert!(
299            batch.len() >= 11,
300            "expected full batch, got {}",
301            batch.len()
302        );
303        let saved = batch
304            .iter()
305            .find(|s| s["metric"] == "leanctx.tokens.saved")
306            .expect("tokens.saved present");
307        let v = saved["points"][0]["value"].as_f64().unwrap();
308        // Other lib tests may record tokens concurrently (global metrics), so
309        // ≥ the 500 just recorded — but never absent or typed as gauge.
310        assert!(
311            v >= 500.0,
312            "delta should include the 500 just recorded: {v}"
313        );
314        assert_eq!(saved["type"], TYPE_COUNT);
315
316        // Every series carries the five bounded info tags.
317        for s in &batch {
318            let tags: Vec<String> = s["tags"]
319                .as_array()
320                .unwrap()
321                .iter()
322                .map(|t| t.as_str().unwrap().to_string())
323                .collect();
324            for key in ["project:", "profile:", "agent_role:", "model:", "version:"] {
325                assert!(
326                    tags.iter().any(|t| t.starts_with(key)),
327                    "{} missing tag {key}",
328                    s["metric"]
329                );
330            }
331        }
332    }
333
334    #[test]
335    fn disabled_without_explicit_opt_in() {
336        // Neither env set in the test environment → off.
337        assert!(!enabled());
338    }
339
340    #[test]
341    fn site_routing_defaults_to_us() {
342        assert_eq!(intake_url(), "https://api.datadoghq.com/api/v2/series");
343    }
344}