Skip to main content

lean_ctx/core/
telemetry_aggregate.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Privacy-safe daily telemetry aggregation.
4//!
5//! Every UTC day keeps cumulative totals. A send carries the full totals of
6//! today (and of any closed day with unsent activity) under that day's bucket.
7//! The server replaces per-day rows, so sending several times a day is
8//! idempotent: tool usage reaches the server within the day, and a one-day
9//! user is counted without having to come back.
10
11use sha2::Digest;
12use std::collections::{BTreeMap, BTreeSet, HashMap};
13use std::path::PathBuf;
14use std::sync::{Mutex, OnceLock};
15
16use fs2::FileExt;
17use serde::{Deserialize, Serialize};
18
19use super::installation_id;
20use super::telemetry_v2::{
21    Architecture, ClientFamily, DecisionMetrics, DistributionChannel, ErrorCategory, ErrorMetrics,
22    HeartbeatMetrics, Histogram, MAX_BATCH_EVENTS, MAX_COUNT, MAX_TOOL_ENTRIES, OccurrenceMetrics,
23    OperatingSystem, SCHEMA_VERSION, SessionMetrics, SyncMetrics, TelemetryBatchV2,
24    TelemetryEnvelopeV2, TelemetryEventV2, TokenMetrics, ToolCallCount, ToolCallMetrics,
25    ToolUsageMetrics, VersionUpgradeMetrics, valid_feature_code, valid_tool_name,
26};
27
28mod counters;
29mod environment;
30mod features;
31mod history;
32use super::telemetry_failure::{KindCounts, sub_kinds, wire_kinds, wire_messages};
33use counters::{add_counters, counter_delta};
34use environment::{client_family, distribution_channel, setup_profile};
35use features::{FeatureTally, add_feature, feature_metrics};
36
37/// Most send attempts per installation and UTC day: a snapshot every half hour
38/// of a day in use. The server admits sixty (from Oct 2026; ten before); the
39/// rest stays in reserve for retries and clock skew between client and server.
40pub const DAILY_SEND_CAP: u32 = 48;
41/// Backoff base while today's first send has not been acknowledged yet.
42const RETRY_BACKOFF_SECS: i64 = 60;
43/// Flat spacing after the first acknowledged send of a day: while LeanCTX is in
44/// use the latest totals are never more than half an hour old. (It used to
45/// double up to two hours, leaving evening activity unreported until morning.)
46const RESEND_INTERVAL_SECS: i64 = 30 * 60;
47/// Ceiling for the retry backoff of an unacknowledged send.
48const MAX_SEND_INTERVAL_SECS: i64 = 2 * 60 * 60;
49/// Flat spacing for the exit flush, so a session's final calls still arrive.
50const EXIT_RESEND_INTERVAL_SECS: i64 = 5 * 60;
51/// Closed days with unsent activity kept locally besides today.
52const RETAINED_CLOSED_DAYS: usize = 7;
53
54/// What prompted a send attempt.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum SendTrigger {
57    /// Background cadence while tools are being called.
58    Periodic,
59    /// Final flush as the MCP server exits; may use the last daily slot.
60    Exit,
61}
62
63#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65struct CounterCheckpoint {
66    tool_calls: u64,
67    tool_failures: u64,
68    tool_latency_buckets: [u64; crate::core::telemetry::TOOL_LATENCY_BUCKET_UPPER_MS.len()],
69    session_uptime_secs: u64,
70    /// Per-tool counters. Absent in state written before per-tool counting.
71    #[serde(default)]
72    tools: BTreeMap<String, ToolCounterCheckpoint>,
73    /// Tool-output tokens. Absent in state written before 3.11.1.
74    #[serde(default)]
75    tokens_input: u64,
76    #[serde(default)]
77    tokens_output: u64,
78    /// Scrubbed failure templates, keyed `tool\ttemplate` (3.11.1).
79    #[serde(default)]
80    failure_messages: BTreeMap<String, u64>,
81}
82
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(deny_unknown_fields)]
85struct ToolCounterCheckpoint {
86    calls: u64,
87    failures: u64,
88    #[serde(default)]
89    latency_us: u64,
90    #[serde(default)]
91    failure_kinds: KindCounts,
92}
93
94#[derive(Debug, Clone, Default, Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96struct AggregateState {
97    #[serde(default)]
98    installation_id: String,
99    /// Legacy in-process baseline, kept so older state files still load.
100    /// Unsent counters now live durably in [`QueuedOneShots::counters`].
101    process_nonce: String,
102    acknowledged: CounterCheckpoint,
103    pending: Option<PendingBatch>,
104    /// Bucket of the most recently acknowledged batch.
105    #[serde(default)]
106    last_sent_bucket: Option<String>,
107    /// Unix time of the most recent admitted send attempt.
108    #[serde(default)]
109    last_attempt_unix: Option<i64>,
110    /// UTC day that `attempts_in_bucket` counts for.
111    #[serde(default)]
112    attempt_bucket: Option<String>,
113    #[serde(default)]
114    attempts_in_bucket: u32,
115}
116
117#[derive(Debug, Clone, Default, Serialize, Deserialize)]
118#[serde(deny_unknown_fields)]
119struct OneShotState {
120    #[serde(default)]
121    installation_id: String,
122    setup_recorded: bool,
123    configured_integrations: BTreeSet<String>,
124    observed_major: Option<u16>,
125    #[serde(default)]
126    last_acknowledged_batch: Option<String>,
127    /// Pre-daily-totals queue. Loaded for compatibility and migrated into
128    /// today's totals; never written with content again.
129    #[serde(default, skip_serializing_if = "QueuedOneShots::is_empty")]
130    queued: QueuedOneShots,
131    /// Cumulative totals per UTC day, keyed `YYYY-MM-DD`.
132    #[serde(default)]
133    days: BTreeMap<String, DayTotals>,
134}
135
136#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(deny_unknown_fields)]
138struct DayTotals {
139    totals: QueuedOneShots,
140    /// The totals the server last acknowledged for this day.
141    #[serde(default)]
142    sent: QueuedOneShots,
143}
144
145impl DayTotals {
146    fn unsent(&self) -> bool {
147        self.totals != self.sent
148    }
149}
150
151#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(deny_unknown_fields)]
153struct QueuedOneShots {
154    setup_completed: bool,
155    integrations_detected: u64,
156    version_upgrade: Option<VersionTransition>,
157    #[serde(default)]
158    sync: SyncMetrics,
159    #[serde(default)]
160    autopilot: DecisionMetrics,
161    #[serde(default)]
162    autopilot_fallback: DecisionMetrics,
163    #[serde(default)]
164    checkout_started: u64,
165    #[serde(default)]
166    error_categories: [u64; 8],
167    /// Shell commands that exited non-zero (3.11.1); kept apart from the
168    /// fixed-size category array so older state still loads.
169    #[serde(default)]
170    command_errors: u64,
171    /// Tool counters folded in by every process, so short sessions reach the
172    /// server even when the process exits before the next send.
173    #[serde(default)]
174    counters: CounterCheckpoint,
175    /// CLI commands and background features by registry code (3.11.1).
176    #[serde(default)]
177    features: BTreeMap<String, FeatureTally>,
178}
179
180impl QueuedOneShots {
181    fn is_empty(&self) -> bool {
182        *self == Self::default()
183    }
184
185    /// Merge `extra` into these totals, saturating at the contract bounds.
186    fn absorb(&mut self, extra: &Self) {
187        self.setup_completed |= extra.setup_completed;
188        self.integrations_detected = self
189            .integrations_detected
190            .saturating_add(extra.integrations_detected)
191            .min(MAX_COUNT);
192        self.version_upgrade = match (self.version_upgrade, extra.version_upgrade) {
193            (Some(own), Some(other)) => Some(VersionTransition {
194                from_major: own.from_major.min(other.from_major),
195                to_major: own.to_major.max(other.to_major),
196            }),
197            (own, other) => own.or(other),
198        };
199        self.sync.attempts = self
200            .sync
201            .attempts
202            .saturating_add(extra.sync.attempts)
203            .min(MAX_COUNT);
204        self.sync.successes = self
205            .sync
206            .successes
207            .saturating_add(extra.sync.successes)
208            .min(self.sync.attempts);
209        self.sync.failures = self
210            .sync
211            .failures
212            .saturating_add(extra.sync.failures)
213            .min(self.sync.attempts - self.sync.successes);
214        add_decisions(&mut self.autopilot, &extra.autopilot);
215        add_decisions(&mut self.autopilot_fallback, &extra.autopilot_fallback);
216        self.checkout_started = self
217            .checkout_started
218            .saturating_add(extra.checkout_started)
219            .min(MAX_COUNT);
220        for (own, other) in self.error_categories.iter_mut().zip(extra.error_categories) {
221            *own = own.saturating_add(other).min(MAX_COUNT);
222        }
223        self.command_errors = self
224            .command_errors
225            .saturating_add(extra.command_errors)
226            .min(MAX_COUNT);
227        add_counters(&mut self.counters, &extra.counters);
228        for (code, tally) in &extra.features {
229            add_feature(&mut self.features, code, *tally);
230        }
231    }
232}
233
234fn add_decisions(total: &mut DecisionMetrics, extra: &DecisionMetrics) {
235    total.admitted = total.admitted.saturating_add(extra.admitted).min(MAX_COUNT);
236    total.denied = total.denied.saturating_add(extra.denied).min(MAX_COUNT);
237    total.fallback = total.fallback.saturating_add(extra.fallback).min(MAX_COUNT);
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(deny_unknown_fields)]
242struct VersionTransition {
243    from_major: u16,
244    to_major: u16,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize)]
248#[serde(deny_unknown_fields)]
249struct PendingBatch {
250    batch: TelemetryBatchV2,
251    #[serde(default)]
252    acknowledgement_id: String,
253    observed: CounterCheckpoint,
254    process_nonce: String,
255    /// Legacy subtract-on-acknowledge snapshot; new batches use `included_days`.
256    #[serde(default, skip_serializing_if = "QueuedOneShots::is_empty")]
257    included_one_shots: QueuedOneShots,
258    /// Exact per-day totals this batch carries, recorded as sent on success.
259    #[serde(default)]
260    included_days: BTreeMap<String, QueuedOneShots>,
261}
262
263pub struct DailySendLease {
264    batch: TelemetryBatchV2,
265    state_path: PathBuf,
266    one_shot_path: PathBuf,
267    _lock: super::file_lock::FlockGuard,
268}
269
270impl DailySendLease {
271    pub fn batch(&self) -> &TelemetryBatchV2 {
272        &self.batch
273    }
274
275    pub fn commit(self) -> Result<(), String> {
276        acknowledge_at(&self.state_path, &self.one_shot_path, &self.batch)
277    }
278}
279
280pub fn pending_daily_batch() -> Result<TelemetryBatchV2, String> {
281    preview_daily_batch()
282}
283
284/// Build the exact currently eligible payload without advancing durable state.
285pub fn preview_daily_batch() -> Result<TelemetryBatchV2, String> {
286    let path = state_path()?;
287    ensure_parent(&path)?;
288    let _lock = super::file_lock::FlockGuard::try_exclusive(open_state_lock(&path)?)
289        .map_err(|error| format!("cannot lock telemetry aggregate state for preview: {error}"))?
290        .ok_or_else(|| {
291            "exact telemetry preview unavailable while a send is in progress".to_string()
292        })?;
293    let state = state_for_current_identity(load_state_at(&path)?)?;
294    if let Some(pending) = state.pending {
295        return Ok(pending.batch);
296    }
297    let sidecar_path = one_shot_path()?;
298    ensure_parent(&sidecar_path)?;
299    // Tool calls hold this lock briefly to persist counters; wait out that
300    // window instead of failing a concurrent preview.
301    let _sidecar_lock = lock_telemetry_file(open_sidecar_lock(&sidecar_path)?, "one-shot")
302        .map_err(|error| {
303            format!("exact telemetry preview unavailable: cannot lock one-shot state: {error}")
304        })?;
305    let mut one_shots = one_shots_for_current_identity(load_one_shots_at(&sidecar_path)?)?;
306    // Fold in memory only: the preview must not advance durable state.
307    let today = current_send_bucket();
308    fold_process_counters(&sidecar_path, &mut one_shots, &today);
309    build_batch(&one_shots, &today).map(|(batch, _)| batch)
310}
311
312/// Freeze one payload until the sender explicitly acknowledges success,
313/// bypassing admission so tests can drive the two phases directly.
314#[cfg(test)]
315fn prepare_daily_batch() -> Result<TelemetryBatchV2, String> {
316    with_locked_state(|mut state| {
317        if let Some(pending) = &state.pending {
318            return Ok((state.clone(), pending.batch.clone()));
319        }
320        let (batch, _) = freeze_batch(&mut state, &current_send_bucket())?;
321        Ok((state, batch))
322    })
323}
324
325/// Hold the cross-process state lease until network, ledger, and
326/// acknowledgement finish. Refuses while the next send is not yet due.
327pub fn begin_daily_send() -> Result<DailySendLease, String> {
328    begin_send(SendTrigger::Periodic)
329}
330
331/// Admission and payload resolve one clock reading under the aggregate lock,
332/// so competing senders cannot both pass a stale caller-side precheck.
333pub fn begin_send(trigger: SendTrigger) -> Result<DailySendLease, String> {
334    let path = state_path()?;
335    let one_shot_path = one_shot_path()?;
336    ensure_parent(&path)?;
337    let _lock = lock_telemetry_file(open_state_lock(&path)?, "aggregate")?;
338    let mut state = state_for_current_identity(load_state()?)?;
339    let (bucket, now) = send_clock();
340    if state.attempt_bucket.as_deref() != Some(bucket.as_str()) {
341        state.attempt_bucket = Some(bucket.clone());
342        state.attempts_in_bucket = 0;
343    }
344    let sent_today = state.last_sent_bucket.as_deref() == Some(bucket.as_str());
345    admit(&state, now, trigger, sent_today)?;
346    let batch = if let Some(pending) = &state.pending {
347        // Retries remain at-least-once with the exact frozen bytes, including
348        // across UTC day boundaries.
349        pending.batch.clone()
350    } else {
351        let (batch, unsent) = freeze_batch(&mut state, &bucket)?;
352        if sent_today && !unsent {
353            // Nothing new since the last acknowledged send. The fold above
354            // already persisted this process's counters, which is harmless.
355            return Err(format!("telemetry for {bucket} is already up to date"));
356        }
357        batch
358    };
359    state.last_attempt_unix = Some(now);
360    state.attempts_in_bucket = state.attempts_in_bucket.saturating_add(1);
361    write_state(&path, &state)?;
362    Ok(DailySendLease {
363        batch,
364        state_path: path,
365        one_shot_path,
366        _lock,
367    })
368}
369
370/// Whether the next attempt is due. Attempts in a day are capped below the
371/// server's own limit. An acknowledged day is re-sent at a flat half-hour
372/// spacing while tools are in use; an unacknowledged send backs off, so an
373/// offline machine retries ever more rarely.
374fn admit(
375    state: &AggregateState,
376    now: i64,
377    trigger: SendTrigger,
378    sent_today: bool,
379) -> Result<(), String> {
380    let cap = match trigger {
381        SendTrigger::Periodic => DAILY_SEND_CAP - 1,
382        SendTrigger::Exit => DAILY_SEND_CAP,
383    };
384    let attempts = state.attempts_in_bucket;
385    if attempts >= cap {
386        return Err(format!(
387            "telemetry daily send limit reached ({attempts} of {cap} attempts)"
388        ));
389    }
390    let interval = if attempts == 0 {
391        0
392    } else if state.pending.is_some() || !sent_today {
393        backoff(RETRY_BACKOFF_SECS, attempts)
394    } else if trigger == SendTrigger::Exit {
395        EXIT_RESEND_INTERVAL_SECS
396    } else {
397        RESEND_INTERVAL_SECS
398    };
399    // A clock that moved backwards must not stall sending until it catches up.
400    let elapsed = state
401        .last_attempt_unix
402        .map_or(i64::MAX, |last| now.saturating_sub(last));
403    if elapsed >= 0 && elapsed < interval {
404        return Err(format!(
405            "telemetry send not due for another {}s",
406            interval - elapsed
407        ));
408    }
409    Ok(())
410}
411
412fn backoff(base: i64, attempts: u32) -> i64 {
413    base.saturating_mul(1_i64 << attempts.saturating_sub(1).min(16))
414        .min(MAX_SEND_INTERVAL_SECS)
415}
416
417/// Fold this process's counters, then freeze the batch for `bucket` as the
418/// pending payload. Also reports whether the batch carries any totals the
419/// server has not acknowledged yet. Holds the one-shot lock only for the fold.
420fn freeze_batch(
421    state: &mut AggregateState,
422    bucket: &str,
423) -> Result<(TelemetryBatchV2, bool), String> {
424    let one_shot_path = one_shot_path()?;
425    ensure_parent(&one_shot_path)?;
426    let _one_shot_lock = lock_telemetry_file(open_sidecar_lock(&one_shot_path)?, "one-shot")?;
427    let mut one_shots = one_shots_for_current_identity(load_one_shots_at(&one_shot_path)?)?;
428    let observed = fold_process_counters(&one_shot_path, &mut one_shots, bucket);
429    write_one_shots(&one_shot_path, &one_shots)?;
430    mark_folded(&one_shot_path, observed.clone());
431    let (batch, included_days) = build_batch(&one_shots, bucket)?;
432    // A day without an entry has no activity, so it has nothing unsent.
433    let unsent = included_days
434        .keys()
435        .any(|day| one_shots.days.get(day).is_some_and(DayTotals::unsent));
436    state.installation_id = batch_installation_id(&batch).to_string();
437    state.pending = Some(PendingBatch {
438        batch: batch.clone(),
439        acknowledgement_id: uuid::Uuid::new_v4().to_string(),
440        observed,
441        process_nonce: process_nonce().to_string(),
442        included_one_shots: QueuedOneShots::default(),
443        included_days,
444    });
445    Ok((batch, unsent))
446}
447
448/// Advance durable state only when the exact frozen payload was accepted.
449#[cfg(test)]
450fn acknowledge_daily_batch(batch: &TelemetryBatchV2) -> Result<(), String> {
451    let path = state_path()?;
452    ensure_parent(&path)?;
453    let _lock = super::file_lock::FlockGuard::exclusive(open_state_lock(&path)?)
454        .map_err(|error| format!("cannot lock telemetry aggregate state: {error}"))?;
455    acknowledge_at(&path, &one_shot_path()?, batch)
456}
457
458fn acknowledge_at(
459    state_path: &std::path::Path,
460    one_shot_path: &std::path::Path,
461    batch: &TelemetryBatchV2,
462) -> Result<(), String> {
463    let current_state = load_state_at(state_path)?;
464    let pending = current_state
465        .pending
466        .as_ref()
467        .ok_or_else(|| "no prepared telemetry batch to acknowledge".to_string())?;
468    let included = pending.included_days.clone();
469    let acknowledgement_id = pending_acknowledgement_id(pending)?;
470    let state = acknowledge_state(current_state, batch)?;
471    acknowledge_one_shots_at(one_shot_path, &included, &acknowledgement_id)?;
472    write_state(state_path, &state)
473}
474
475fn pending_acknowledgement_id(pending: &PendingBatch) -> Result<String, String> {
476    if !pending.acknowledgement_id.is_empty() {
477        return Ok(pending.acknowledgement_id.clone());
478    }
479    let encoded = serde_json::to_vec(&pending.batch)
480        .map_err(|error| format!("cannot encode telemetry acknowledgement: {error}"))?;
481    Ok(hex::encode(sha2::Sha256::digest(encoded)))
482}
483
484fn acknowledge_state(
485    mut state: AggregateState,
486    batch: &TelemetryBatchV2,
487) -> Result<AggregateState, String> {
488    let pending = state
489        .pending
490        .take()
491        .ok_or_else(|| "no prepared telemetry batch to acknowledge".to_string())?;
492    if pending.batch != *batch {
493        return Err("telemetry acknowledgement does not match pending batch".to_string());
494    }
495    state.process_nonce = pending.process_nonce;
496    state.acknowledged = pending.observed;
497    state.last_sent_bucket = batch
498        .events
499        .first()
500        .map(|event| event.timestamp_bucket.clone());
501    Ok(state)
502}
503
504pub fn last_sent_bucket() -> Option<String> {
505    load_state()
506        .and_then(state_for_current_identity)
507        .ok()
508        .and_then(|state| state.last_sent_bucket)
509}
510
511/// UTC bucket shared by payload generation and the background caller's precheck.
512pub(crate) fn current_send_bucket() -> String {
513    send_clock().0
514}
515
516/// UTC day bucket and unix time from one clock reading.
517fn send_clock() -> (String, i64) {
518    #[cfg(test)]
519    if let Some(clock) = TEST_CLOCK
520        .lock()
521        .unwrap_or_else(std::sync::PoisonError::into_inner)
522        .clone()
523    {
524        return clock;
525    }
526    let now = lean_ctx_time::UtcDateTime::now();
527    (now.format("%Y-%m-%d").to_string(), now.timestamp())
528}
529
530/// Fixed clock for tests; `None` uses the system clock.
531#[cfg(test)]
532static TEST_CLOCK: Mutex<Option<(String, i64)>> = Mutex::new(None);
533
534/// Pin the send clock until the guard drops.
535#[cfg(test)]
536struct TestClockGuard;
537
538#[cfg(test)]
539impl TestClockGuard {
540    fn set(bucket: &str, unix: i64) -> Self {
541        *TEST_CLOCK
542            .lock()
543            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((bucket.to_string(), unix));
544        Self
545    }
546}
547
548#[cfg(test)]
549impl Drop for TestClockGuard {
550    fn drop(&mut self) {
551        *TEST_CLOCK
552            .lock()
553            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
554    }
555}
556
557fn state_for_current_identity(mut state: AggregateState) -> Result<AggregateState, String> {
558    let (current, _) = installation_id::get_or_create_identity()
559        .map_err(|error| format!("installation ID unavailable: {error}"))?;
560    let pending_mismatch = state.pending.as_ref().is_some_and(|pending| {
561        let pending_id = batch_installation_id(&pending.batch);
562        pending_id.is_empty() || pending_id != current
563    });
564    if pending_mismatch || (!state.installation_id.is_empty() && state.installation_id != current) {
565        state = AggregateState {
566            installation_id: current,
567            ..AggregateState::default()
568        };
569    } else if state.installation_id.is_empty() {
570        state.installation_id = current;
571    }
572    Ok(state)
573}
574
575fn batch_installation_id(batch: &TelemetryBatchV2) -> &str {
576    batch
577        .events
578        .first()
579        .map_or("", |event| event.installation_id.as_str())
580}
581
582/// Build today's cumulative totals under `today`, followed by every closed day
583/// with unsent activity (oldest first) under its own bucket, as many as fit in
584/// one batch. Today leads so the first event names the send's bucket. Returns
585/// the exact totals included per day, to be recorded as sent on success.
586fn build_batch(
587    one_shots: &OneShotState,
588    today: &str,
589) -> Result<(TelemetryBatchV2, BTreeMap<String, QueuedOneShots>), String> {
590    let (installation_id, deletion_token) = installation_id::get_or_create_identity()
591        .map_err(|error| format!("installation ID unavailable: {error}"))?;
592    let deletion_token_hash = hex::encode(sha2::Sha256::digest(deletion_token.as_bytes()));
593    let distribution_channel = distribution_channel();
594    let client_family = client_family();
595    let build_day = |day: &str, totals: &QueuedOneShots| {
596        build_daily_aggregate(
597            installation_id.clone(),
598            deletion_token_hash.clone(),
599            day.to_string(),
600            distribution_channel,
601            client_family,
602            totals,
603        )
604    };
605    let today_totals = one_shots
606        .days
607        .get(today)
608        .map(|day| day.totals.clone())
609        .unwrap_or_default();
610    let mut batch = build_day(today, &today_totals)?;
611    if let Some(history) = lean_ctx_time::parse_date(today, "%Y-%m-%d")
612        .ok()
613        .and_then(history::usage_history)
614    {
615        let event = envelope_like(&batch.events[0], TelemetryEventV2::UsageHistory(history));
616        batch.events.push(event);
617    }
618    let mut included = BTreeMap::from([(today.to_string(), today_totals)]);
619    for (day, totals) in one_shots
620        .days
621        .range::<str, _>(before(today))
622        .filter(|(_, day)| day.unsent())
623    {
624        let closed = build_day(day, &totals.totals)?;
625        if batch.events.len() + closed.events.len() > MAX_BATCH_EVENTS {
626            break;
627        }
628        batch.events.extend(closed.events);
629        included.insert(day.clone(), totals.totals.clone());
630    }
631    batch
632        .validate()
633        .map_err(|error| format!("invalid telemetry batch: {error:?}"))?;
634    Ok((batch, included))
635}
636
637fn build_daily_aggregate(
638    installation_id: String,
639    deletion_token_hash: String,
640    timestamp_bucket: String,
641    distribution_channel: DistributionChannel,
642    client_family: ClientFamily,
643    queued: &QueuedOneShots,
644) -> Result<TelemetryBatchV2, String> {
645    let observed = &queued.counters;
646    let baseline = CounterCheckpoint::default();
647    let latency_counts = bounded_histogram_delta(
648        &observed.tool_latency_buckets,
649        &baseline.tool_latency_buckets,
650    );
651    let calls = latency_counts.iter().sum();
652    debug_assert_eq!(
653        calls,
654        observed
655            .tool_calls
656            .saturating_sub(baseline.tool_calls)
657            .min(MAX_COUNT)
658    );
659    let failures = observed
660        .tool_failures
661        .saturating_sub(baseline.tool_failures)
662        .min(calls);
663    let duration = observed
664        .session_uptime_secs
665        .saturating_sub(baseline.session_uptime_secs)
666        .min(MAX_COUNT);
667    let mut batch = build_daily_heartbeat(
668        installation_id,
669        deletion_token_hash,
670        timestamp_bucket,
671        distribution_channel,
672        client_family,
673    )?;
674    let common = batch.events[0].clone();
675    batch.events.push(envelope_like(
676        &common,
677        TelemetryEventV2::SetupProfile(setup_profile()),
678    ));
679    batch.events.push(envelope_like(
680        &common,
681        TelemetryEventV2::SessionAggregate(SessionMetrics {
682            sessions: 1,
683            duration_seconds: single_observation_histogram(
684                duration,
685                &[
686                    60,
687                    300,
688                    900,
689                    3_600,
690                    14_400,
691                    86_400,
692                    604_800,
693                    31_536_000,
694                    i64::MAX as u64,
695                ],
696                1,
697            ),
698        }),
699    ));
700    batch.events.push(envelope_like(
701        &common,
702        TelemetryEventV2::ToolUsageAggregate(ToolUsageMetrics {
703            calls,
704            failures,
705            latency_milliseconds: Histogram {
706                upper_bounds: crate::core::telemetry::TOOL_LATENCY_BUCKET_UPPER_MS.to_vec(),
707                counts: latency_counts.to_vec(),
708            },
709            tokens: Some(TokenMetrics {
710                original: observed.tokens_input.min(MAX_COUNT),
711                delivered: observed.tokens_output.min(MAX_COUNT),
712            }),
713        }),
714    ));
715    let tools = tool_call_deltas(&observed.tools, &baseline.tools, &observed.failure_messages);
716    if !tools.is_empty() {
717        batch.events.push(envelope_like(
718            &common,
719            TelemetryEventV2::ToolCallAggregate(ToolCallMetrics { tools }),
720        ));
721    }
722    if queued.setup_completed {
723        batch.events.push(envelope_like(
724            &common,
725            TelemetryEventV2::SetupCompleted(OccurrenceMetrics { count: 1 }),
726        ));
727    }
728    if queued.integrations_detected > 0 {
729        batch.events.push(envelope_like(
730            &common,
731            TelemetryEventV2::IntegrationDetected(OccurrenceMetrics {
732                count: queued.integrations_detected.min(MAX_COUNT),
733            }),
734        ));
735    }
736    if let Some(transition) = queued.version_upgrade {
737        batch.events.push(envelope_like(
738            &common,
739            TelemetryEventV2::VersionUpgrade(VersionUpgradeMetrics {
740                from_major: transition.from_major,
741                to_major: transition.to_major,
742            }),
743        ));
744    }
745    if queued.sync.attempts > 0 {
746        batch.events.push(envelope_like(
747            &common,
748            TelemetryEventV2::SyncAggregate(queued.sync.clone()),
749        ));
750    }
751    if queued.autopilot.admitted > 0 || queued.autopilot.denied > 0 || queued.autopilot.fallback > 0
752    {
753        batch.events.push(envelope_like(
754            &common,
755            TelemetryEventV2::AutopilotAggregate(queued.autopilot.clone()),
756        ));
757    }
758    if queued.autopilot_fallback.fallback > 0 {
759        batch.events.push(envelope_like(
760            &common,
761            TelemetryEventV2::AutopilotFallbackAggregate(queued.autopilot_fallback.clone()),
762        ));
763    }
764    if queued.checkout_started > 0 {
765        batch.events.push(envelope_like(
766            &common,
767            TelemetryEventV2::CheckoutStarted(OccurrenceMetrics {
768                count: queued.checkout_started,
769            }),
770        ));
771    }
772    for (category, count) in ERROR_CATEGORIES
773        .into_iter()
774        .zip(queued.error_categories)
775        .chain([(ErrorCategory::Command, queued.command_errors)])
776    {
777        let count = count.min(MAX_COUNT);
778        if count > 0 {
779            batch.events.push(envelope_like(
780                &common,
781                TelemetryEventV2::ErrorCategoryAggregate(ErrorMetrics { category, count }),
782            ));
783        }
784    }
785    if let Some(features) = feature_metrics(&queued.features) {
786        batch.events.push(envelope_like(
787            &common,
788            TelemetryEventV2::FeatureAggregate(features),
789        ));
790    }
791    batch
792        .validate()
793        .map_err(|error| format!("invalid telemetry batch: {error:?}"))?;
794    Ok(batch)
795}
796
797fn bounded_histogram_delta<const N: usize>(observed: &[u64; N], baseline: &[u64; N]) -> [u64; N] {
798    let mut remaining = MAX_COUNT;
799    std::array::from_fn(|index| {
800        let count = observed[index]
801            .saturating_sub(baseline[index])
802            .min(remaining);
803        remaining -= count;
804        count
805    })
806}
807
808/// Per-tool calls since the baseline. Names failing the contract format are
809/// dropped; past [`MAX_TOOL_ENTRIES`] the most-called tools are kept. The
810/// result is sorted by name, as the contract requires.
811fn tool_call_deltas(
812    observed: &BTreeMap<String, ToolCounterCheckpoint>,
813    baseline: &BTreeMap<String, ToolCounterCheckpoint>,
814    messages: &BTreeMap<String, u64>,
815) -> Vec<ToolCallCount> {
816    let mut tools: Vec<ToolCallCount> = observed
817        .iter()
818        .filter(|(tool, _)| valid_tool_name(tool))
819        .filter_map(|(tool, counter)| {
820            let base = baseline.get(tool).copied().unwrap_or_default();
821            let calls = counter.calls.saturating_sub(base.calls).min(MAX_COUNT);
822            let failures = counter.failures.saturating_sub(base.failures).min(calls);
823            (calls > 0).then(|| ToolCallCount {
824                tool: tool.clone(),
825                calls,
826                failures,
827                latency_milliseconds_total: Some(
828                    (counter.latency_us.saturating_sub(base.latency_us) / 1_000).min(MAX_COUNT),
829                ),
830                failure_kinds: wire_kinds(
831                    &sub_kinds(&counter.failure_kinds, &base.failure_kinds),
832                    failures,
833                ),
834                failure_messages: wire_messages(messages, tool, failures),
835            })
836        })
837        .collect();
838    if tools.len() > MAX_TOOL_ENTRIES {
839        tools.sort_by(|a, b| b.calls.cmp(&a.calls).then_with(|| a.tool.cmp(&b.tool)));
840        tools.truncate(MAX_TOOL_ENTRIES);
841        tools.sort_by(|a, b| a.tool.cmp(&b.tool));
842    }
843    tools
844}
845
846fn envelope_like(template: &TelemetryEnvelopeV2, event: TelemetryEventV2) -> TelemetryEnvelopeV2 {
847    TelemetryEnvelopeV2 {
848        schema_version: template.schema_version,
849        timestamp_bucket: template.timestamp_bucket.clone(),
850        installation_id: template.installation_id.clone(),
851        account_id: template.account_id.clone(),
852        organization_id: template.organization_id.clone(),
853        app_version: template.app_version.clone(),
854        event,
855    }
856}
857
858fn single_observation_histogram(value: u64, bounds: &[u64], count: u64) -> Histogram {
859    let mut counts = vec![0; bounds.len()];
860    let index = bounds
861        .iter()
862        .position(|bound| value <= *bound)
863        .unwrap_or(bounds.len() - 1);
864    counts[index] = count.min(MAX_COUNT);
865    Histogram {
866        upper_bounds: bounds.to_vec(),
867        counts,
868    }
869}
870
871fn current_checkpoint() -> CounterCheckpoint {
872    let snapshot = crate::core::telemetry::global_metrics().daily_telemetry_snapshot();
873    CounterCheckpoint {
874        tool_calls: snapshot.tool_calls,
875        tool_failures: snapshot.tool_failures,
876        tool_latency_buckets: snapshot.tool_latency_buckets,
877        session_uptime_secs: snapshot.session_uptime_secs,
878        tools: snapshot
879            .per_tool
880            .into_iter()
881            .map(|(tool, counter)| {
882                (
883                    tool.to_string(),
884                    ToolCounterCheckpoint {
885                        calls: counter.calls,
886                        failures: counter.failures,
887                        latency_us: counter.latency_us,
888                        failure_kinds: counter.failure_kinds,
889                    },
890                )
891            })
892            .collect(),
893        tokens_input: snapshot.tokens_input,
894        tokens_output: snapshot.tokens_output,
895        failure_messages: snapshot
896            .failure_templates
897            .into_iter()
898            .map(|((tool, template), count)| (format!("{tool}\t{template}"), count))
899            .collect(),
900    }
901}
902
903fn process_nonce() -> &'static str {
904    static NONCE: OnceLock<String> = OnceLock::new();
905    NONCE.get_or_init(|| uuid::Uuid::new_v4().to_string())
906}
907
908/// This process's counters already folded into each sidecar, keyed by path so
909/// an isolated state directory starts from zero.
910fn folded_baselines() -> &'static Mutex<HashMap<PathBuf, CounterCheckpoint>> {
911    static FOLDED: OnceLock<Mutex<HashMap<PathBuf, CounterCheckpoint>>> = OnceLock::new();
912    FOLDED.get_or_init(Mutex::default)
913}
914
915/// Add this process's not-yet-folded counters to the totals of `day` in memory
916/// and return the observed checkpoint. Callers that persist the result must
917/// then [`mark_folded`] it while still holding the sidecar lock.
918fn fold_process_counters(
919    path: &std::path::Path,
920    one_shots: &mut OneShotState,
921    day: &str,
922) -> CounterCheckpoint {
923    let observed = current_checkpoint();
924    let folded = folded_baselines()
925        .lock()
926        .unwrap_or_else(std::sync::PoisonError::into_inner)
927        .get(path)
928        .cloned()
929        .unwrap_or_default();
930    let delta = counter_delta(&observed, &folded);
931    if delta != CounterCheckpoint::default() {
932        add_counters(&mut day_totals(one_shots, day).counters, &delta);
933    }
934    observed
935}
936
937fn mark_folded(path: &std::path::Path, observed: CounterCheckpoint) {
938    folded_baselines()
939        .lock()
940        .unwrap_or_else(std::sync::PoisonError::into_inner)
941        .insert(path.to_path_buf(), observed);
942}
943
944/// Persist this process's unsent tool counters so they survive process exit
945/// and reach the next daily batch. While telemetry is disabled the counters
946/// are skipped instead, so re-enabling never back-fills opted-out activity.
947pub fn persist_process_counters() -> Result<(), String> {
948    let path = one_shot_path()?;
949    if !telemetry_collection_eligible() {
950        mark_folded(&path, current_checkpoint());
951        return Ok(());
952    }
953    ensure_parent(&path)?;
954    let _lock = lock_telemetry_file(open_sidecar_lock(&path)?, "one-shot")?;
955    let mut one_shots = one_shots_for_current_identity(load_one_shots_at(&path)?)?;
956    let before = one_shots.clone();
957    let observed = fold_process_counters(&path, &mut one_shots, &current_send_bucket());
958    if one_shots.days != before.days || one_shots.queued != before.queued {
959        write_one_shots(&path, &one_shots)?;
960    }
961    mark_folded(&path, observed);
962    Ok(())
963}
964
965fn state_path() -> Result<PathBuf, String> {
966    crate::core::paths::state_dir().map(|dir| dir.join("telemetry_v2_aggregate.json"))
967}
968
969fn one_shot_path() -> Result<PathBuf, String> {
970    crate::core::paths::state_dir().map(|dir| dir.join("telemetry_v2_one_shots.json"))
971}
972
973pub fn record_setup_completion(
974    integration_ids: impl IntoIterator<Item = String>,
975) -> Result<(), String> {
976    if !telemetry_collection_eligible() {
977        return Ok(());
978    }
979    with_locked_one_shots(|mut state| {
980        let mut setup_completed = false;
981        if !state.setup_recorded {
982            state.setup_recorded = true;
983            setup_completed = true;
984        }
985        let mut inserted = 0_u64;
986        for integration_id in integration_ids {
987            if state.configured_integrations.len() >= 64 {
988                break;
989            }
990            if integration_id.is_empty() || integration_id.len() > 128 {
991                continue;
992            }
993            let stable_id = hex::encode(sha2::Sha256::digest(integration_id.as_bytes()));
994            if state.configured_integrations.insert(stable_id) {
995                inserted += 1;
996            }
997        }
998        let today = today_totals(&mut state);
999        today.setup_completed |= setup_completed;
1000        today.integrations_detected = today
1001            .integrations_detected
1002            .saturating_add(inserted)
1003            .min(MAX_COUNT);
1004        Ok((state, ()))
1005    })
1006}
1007
1008pub fn record_sync_result(success: bool) -> Result<(), String> {
1009    if !telemetry_collection_eligible() {
1010        return Ok(());
1011    }
1012    with_locked_one_shots(|mut state| {
1013        let sync = &mut today_totals(&mut state).sync;
1014        if sync.attempts >= MAX_COUNT {
1015            return Ok((state, ()));
1016        }
1017        sync.attempts += 1;
1018        if success {
1019            sync.successes = sync.successes.saturating_add(1).min(sync.attempts);
1020        } else {
1021            sync.failures = sync
1022                .failures
1023                .saturating_add(1)
1024                .min(sync.attempts.saturating_sub(sync.successes));
1025        }
1026        Ok((state, ()))
1027    })
1028}
1029
1030pub fn record_autopilot_decisions(admitted: u64, denied: u64) -> Result<(), String> {
1031    if !telemetry_collection_eligible() {
1032        return Ok(());
1033    }
1034    with_locked_one_shots(|mut state| {
1035        add_decisions(
1036            &mut today_totals(&mut state).autopilot,
1037            &DecisionMetrics {
1038                admitted,
1039                denied,
1040                fallback: 0,
1041            },
1042        );
1043        Ok((state, ()))
1044    })
1045}
1046
1047pub fn record_autopilot_fallback() -> Result<(), String> {
1048    if !telemetry_collection_eligible() {
1049        return Ok(());
1050    }
1051    with_locked_one_shots(|mut state| {
1052        let today = today_totals(&mut state);
1053        let fallback = DecisionMetrics {
1054            admitted: 0,
1055            denied: 0,
1056            fallback: 1,
1057        };
1058        add_decisions(&mut today.autopilot, &fallback);
1059        add_decisions(&mut today.autopilot_fallback, &fallback);
1060        Ok((state, ()))
1061    })
1062}
1063
1064pub fn record_checkout_started() -> Result<(), String> {
1065    if !telemetry_collection_eligible() {
1066        return Ok(());
1067    }
1068    with_locked_one_shots(|mut state| {
1069        let today = today_totals(&mut state);
1070        today.checkout_started = today.checkout_started.saturating_add(1).min(MAX_COUNT);
1071        Ok((state, ()))
1072    })
1073}
1074
1075/// Counts one use of a registry feature (`core::telemetry_features`) for
1076/// today; `ok = false` also counts a failure. Invalid codes are ignored.
1077pub fn record_feature(code: &str, ok: bool) -> Result<(), String> {
1078    record_feature_counts(&[(code, 1, u64::from(!ok))])
1079}
1080
1081/// Adds `(code, count, failures)` tallies for today in one locked write.
1082/// Invalid codes and empty tallies are ignored.
1083pub fn record_feature_counts(entries: &[(&str, u64, u64)]) -> Result<(), String> {
1084    let entries: Vec<_> = entries
1085        .iter()
1086        .filter(|(code, count, _)| *count > 0 && valid_feature_code(code))
1087        .collect();
1088    if entries.is_empty() || !telemetry_collection_eligible() {
1089        return Ok(());
1090    }
1091    with_locked_one_shots(|mut state| {
1092        let features = &mut today_totals(&mut state).features;
1093        for (code, count, failures) in entries {
1094            let (count, failures) = (*count, *failures);
1095            add_feature(features, code, FeatureTally { count, failures });
1096        }
1097        Ok((state, ()))
1098    })
1099}
1100
1101const ERROR_CATEGORIES: [ErrorCategory; 8] = [
1102    ErrorCategory::Authentication,
1103    ErrorCategory::Authorization,
1104    ErrorCategory::Configuration,
1105    ErrorCategory::Network,
1106    ErrorCategory::Provider,
1107    ErrorCategory::Timeout,
1108    ErrorCategory::Validation,
1109    ErrorCategory::Internal,
1110];
1111
1112pub fn record_error_category(category: ErrorCategory) -> Result<(), String> {
1113    record_error_category_inner(category)
1114}
1115
1116fn record_error_category_inner(category: ErrorCategory) -> Result<(), String> {
1117    if !telemetry_collection_eligible() {
1118        return Ok(());
1119    }
1120    let index = ERROR_CATEGORIES
1121        .iter()
1122        .position(|candidate| *candidate == category);
1123    with_locked_one_shots(|mut state| {
1124        let totals = today_totals(&mut state);
1125        let count = match index {
1126            Some(index) => &mut totals.error_categories[index],
1127            None => &mut totals.command_errors,
1128        };
1129        *count = count.saturating_add(1).min(MAX_COUNT);
1130        Ok((state, ()))
1131    })
1132}
1133
1134/// Collection stays off whenever the opt-out cannot be read: an unreadable or
1135/// corrupt config must never be mistaken for consent.
1136pub(crate) fn telemetry_collection_eligible() -> bool {
1137    let Ok(config) = crate::core::config::Config::try_load_global() else {
1138        return false;
1139    };
1140    let do_not_track = crate::core::host_env::var("DO_NOT_TRACK");
1141    let telemetry_override = crate::core::host_env::var("LEAN_CTX_TELEMETRY");
1142    !config.telemetry.explicitly_disabled()
1143        && !crate::core::config::TelemetryConfig::environment_disables(
1144            do_not_track.as_deref(),
1145            telemetry_override.as_deref(),
1146        )
1147        && !crate::core::telemetry_consent::running_in_ci()
1148}
1149
1150pub fn record_current_version() -> Result<(), String> {
1151    record_current_version_value(env!("CARGO_PKG_VERSION"))
1152}
1153
1154fn record_current_version_value(version: &str) -> Result<(), String> {
1155    let current = parse_major(version)
1156        .ok_or_else(|| "current app version has no valid major component".to_string())?;
1157    with_locked_one_shots(|mut state| {
1158        let previous = match state.observed_major {
1159            Some(previous) => Some(previous),
1160            None => crate::core::telemetry_ledger::latest_valid_version()?
1161                .as_deref()
1162                .and_then(parse_major),
1163        };
1164        match previous {
1165            Some(previous) if current > previous => {
1166                // Several upgrades within one day collapse into one transition.
1167                let today = today_totals(&mut state);
1168                let from_major = today
1169                    .version_upgrade
1170                    .map_or(previous, |transition| transition.from_major);
1171                today.version_upgrade = Some(VersionTransition {
1172                    from_major,
1173                    to_major: current,
1174                });
1175                state.observed_major = Some(current);
1176            }
1177            Some(previous) => state.observed_major = Some(previous.max(current)),
1178            None => state.observed_major = Some(current),
1179        }
1180        Ok((state, ()))
1181    })
1182}
1183
1184fn parse_major(version: &str) -> Option<u16> {
1185    version.split('.').next()?.parse().ok()
1186}
1187
1188pub fn purge_local_state() -> Result<(), String> {
1189    purge_local_state_then(|| Ok(()))
1190}
1191
1192pub fn purge_local_state_then<T>(
1193    operation: impl FnOnce() -> Result<T, String>,
1194) -> Result<T, String> {
1195    let path = state_path()?;
1196    ensure_parent(&path)?;
1197    let _lock = lock_telemetry_file(open_state_lock(&path)?, "aggregate")?;
1198    let one_shot_path = one_shot_path()?;
1199    ensure_parent(&one_shot_path)?;
1200    let _one_shot_lock = lock_telemetry_file(open_sidecar_lock(&one_shot_path)?, "one-shot")?;
1201    remove_state_file(&path, "aggregate")?;
1202    remove_state_file(&one_shot_path, "one-shot")?;
1203    operation()
1204}
1205
1206pub fn rotate_identity_state_then<T>(
1207    operation: impl FnOnce() -> Result<T, String>,
1208) -> Result<T, String> {
1209    let path = state_path()?;
1210    let one_shot_path = one_shot_path()?;
1211    ensure_parent(&path)?;
1212    let _lock = lock_telemetry_file(open_state_lock(&path)?, "aggregate")?;
1213    let _one_shot_lock = lock_telemetry_file(open_sidecar_lock(&one_shot_path)?, "one-shot")?;
1214    let mut one_shots = one_shots_for_current_identity(load_one_shots_at(&one_shot_path)?)?;
1215    write_one_shots(&one_shot_path, &one_shots)?;
1216    let value = operation()?;
1217    one_shots.installation_id = installation_id::get_or_create()
1218        .map_err(|error| format!("installation ID unavailable after rotation: {error}"))?;
1219    requeue_for_new_identity(&mut one_shots);
1220    remove_state_file(&path, "aggregate")?;
1221    write_one_shots(&one_shot_path, &one_shots)?;
1222    Ok(value)
1223}
1224
1225/// A new identity starts with no history, so only setup facts carry over:
1226/// its first batch reports the existing setup as that identity's own.
1227fn requeue_for_new_identity(state: &mut OneShotState) {
1228    state.queued = QueuedOneShots::default();
1229    state.days.clear();
1230    state.last_acknowledged_batch = None;
1231    let setup_completed = state.setup_recorded;
1232    let integrations = state
1233        .configured_integrations
1234        .len()
1235        .try_into()
1236        .unwrap_or(MAX_COUNT)
1237        .min(MAX_COUNT);
1238    let today = today_totals(state);
1239    today.setup_completed = setup_completed;
1240    today.integrations_detected = integrations;
1241}
1242
1243/// Totals for the current UTC day, created on first use.
1244fn today_totals(state: &mut OneShotState) -> &mut QueuedOneShots {
1245    day_totals(state, &current_send_bucket())
1246}
1247
1248fn day_totals<'a>(state: &'a mut OneShotState, day: &str) -> &'a mut QueuedOneShots {
1249    &mut state.days.entry(day.to_string()).or_default().totals
1250}
1251
1252fn remove_state_file(path: &std::path::Path, kind: &str) -> Result<(), String> {
1253    match std::fs::remove_file(path) {
1254        Ok(()) => Ok(()),
1255        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1256        Err(error) => Err(format!("cannot purge telemetry {kind} state: {error}")),
1257    }
1258}
1259
1260fn load_state() -> Result<AggregateState, String> {
1261    let path = state_path()?;
1262    load_state_at(&path)
1263}
1264
1265fn load_state_at(path: &std::path::Path) -> Result<AggregateState, String> {
1266    match std::fs::read(path) {
1267        Ok(bytes) => serde_json::from_slice(&bytes)
1268            .map_err(|error| format!("invalid telemetry aggregate state: {error}")),
1269        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(AggregateState::default()),
1270        Err(error) => Err(format!("cannot read telemetry aggregate state: {error}")),
1271    }
1272}
1273
1274fn load_one_shots_at(path: &std::path::Path) -> Result<OneShotState, String> {
1275    match std::fs::read(path) {
1276        Ok(bytes) => serde_json::from_slice(&bytes)
1277            .map_err(|error| format!("invalid telemetry one-shot state: {error}")),
1278        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(OneShotState::default()),
1279        Err(error) => Err(format!("cannot read telemetry one-shot state: {error}")),
1280    }
1281}
1282
1283fn one_shots_for_current_identity(mut state: OneShotState) -> Result<OneShotState, String> {
1284    let current = installation_id::get_or_create()
1285        .map_err(|error| format!("installation ID unavailable: {error}"))?;
1286    if state.installation_id.is_empty() {
1287        state.installation_id = current;
1288    } else if state.installation_id != current {
1289        state.installation_id = current;
1290        requeue_for_new_identity(&mut state);
1291    }
1292    normalize_days(&mut state, &current_send_bucket());
1293    Ok(state)
1294}
1295
1296/// Range over the day keys strictly before `day` (closed days).
1297fn before(day: &str) -> (std::ops::Bound<&str>, std::ops::Bound<&str>) {
1298    (std::ops::Bound::Unbounded, std::ops::Bound::Excluded(day))
1299}
1300
1301/// Migrate the pre-daily-totals queue into today and drop closed days the
1302/// server already holds, keeping the most recent unsent ones.
1303fn normalize_days(state: &mut OneShotState, today: &str) {
1304    if !state.queued.is_empty() {
1305        let legacy = std::mem::take(&mut state.queued);
1306        day_totals(state, today).absorb(&legacy);
1307    }
1308    state
1309        .days
1310        .retain(|day, totals| day.as_str() >= today || totals.unsent());
1311    let closed = state.days.range::<str, _>(before(today)).count();
1312    let stale: Vec<String> = state
1313        .days
1314        .keys()
1315        .take(closed.saturating_sub(RETAINED_CLOSED_DAYS))
1316        .cloned()
1317        .collect();
1318    for day in stale {
1319        state.days.remove(&day);
1320    }
1321}
1322
1323fn with_locked_one_shots<T>(
1324    operation: impl FnOnce(OneShotState) -> Result<(OneShotState, T), String>,
1325) -> Result<T, String> {
1326    let path = one_shot_path()?;
1327    ensure_parent(&path)?;
1328    let _lock = lock_telemetry_file(open_sidecar_lock(&path)?, "one-shot")?;
1329    let state = one_shots_for_current_identity(load_one_shots_at(&path)?)?;
1330    let (state, value) = operation(state)?;
1331    write_one_shots(&path, &state)?;
1332    Ok(value)
1333}
1334
1335/// Record the exact per-day totals the server accepted. Totals that grew while
1336/// the batch was in flight stay unsent and go out with the next send.
1337fn acknowledge_one_shots_at(
1338    path: &std::path::Path,
1339    included: &BTreeMap<String, QueuedOneShots>,
1340    acknowledgement_id: &str,
1341) -> Result<(), String> {
1342    ensure_parent(path)?;
1343    let _lock = lock_telemetry_file(open_sidecar_lock(path)?, "one-shot")?;
1344    let mut state = one_shots_for_current_identity(load_one_shots_at(path)?)?;
1345    if state.last_acknowledged_batch.as_deref() == Some(acknowledgement_id) {
1346        return Ok(());
1347    }
1348    // A day pruned or reset by an identity change in the meantime stays gone.
1349    for (day, sent) in included {
1350        if let Some(totals) = state.days.get_mut(day) {
1351            totals.sent = sent.clone();
1352        }
1353    }
1354    state.last_acknowledged_batch = Some(acknowledgement_id.to_string());
1355    normalize_days(&mut state, &current_send_bucket());
1356    write_one_shots(path, &state)
1357}
1358
1359#[cfg(test)]
1360fn with_locked_state<T>(
1361    operation: impl FnOnce(AggregateState) -> Result<(AggregateState, T), String>,
1362) -> Result<T, String> {
1363    let path = state_path()?;
1364    ensure_parent(&path)?;
1365    let _lock = super::file_lock::FlockGuard::exclusive(open_state_lock(&path)?)
1366        .map_err(|error| format!("cannot lock telemetry aggregate state: {error}"))?;
1367    let (state, value) = operation(load_state_at(&path)?)?;
1368    write_state(&path, &state)?;
1369    Ok(value)
1370}
1371
1372fn ensure_parent(path: &std::path::Path) -> Result<(), String> {
1373    let parent = path
1374        .parent()
1375        .ok_or_else(|| "telemetry state path has no parent".to_string())?;
1376    std::fs::create_dir_all(parent)
1377        .map_err(|error| format!("cannot create telemetry state directory: {error}"))
1378}
1379
1380fn write_state(path: &std::path::Path, state: &AggregateState) -> Result<(), String> {
1381    let bytes = serde_json::to_vec(&state)
1382        .map_err(|error| format!("cannot serialize telemetry aggregate state: {error}"))?;
1383    #[cfg(unix)]
1384    let permissions = {
1385        use std::os::unix::fs::PermissionsExt;
1386        Some(std::fs::Permissions::from_mode(0o600))
1387    };
1388    #[cfg(not(unix))]
1389    let permissions: Option<std::fs::Permissions> = None;
1390    crate::core::atomic_fs::try_atomic_write(&path, &bytes, permissions.as_ref())
1391        .map_err(|error| format!("cannot persist telemetry aggregate state: {error}"))
1392}
1393
1394fn write_one_shots(path: &std::path::Path, state: &OneShotState) -> Result<(), String> {
1395    let bytes = serde_json::to_vec(state)
1396        .map_err(|error| format!("cannot serialize telemetry one-shot state: {error}"))?;
1397    #[cfg(unix)]
1398    let permissions = {
1399        use std::os::unix::fs::PermissionsExt;
1400        Some(std::fs::Permissions::from_mode(0o600))
1401    };
1402    #[cfg(not(unix))]
1403    let permissions: Option<std::fs::Permissions> = None;
1404    crate::core::atomic_fs::try_atomic_write(path, &bytes, permissions.as_ref())
1405        .map_err(|error| format!("cannot persist telemetry one-shot state: {error}"))
1406}
1407
1408fn open_state_lock(path: &std::path::Path) -> Result<std::fs::File, String> {
1409    std::fs::OpenOptions::new()
1410        .create(true)
1411        .truncate(false)
1412        .read(true)
1413        .write(true)
1414        .open(path.with_extension("lock"))
1415        .map_err(|error| format!("cannot open telemetry state lock: {error}"))
1416}
1417
1418fn open_sidecar_lock(path: &std::path::Path) -> Result<std::fs::File, String> {
1419    open_state_lock(path)
1420}
1421
1422/// Contention fails without mutating state; failed acknowledgements keep the
1423/// frozen batch retryable. This bounds acquisition, not filesystem I/O.
1424/// Tests use the production bound: a contender must outwait a lease holder
1425/// even under coverage instrumentation, where 150 ms timed out.
1426const SEND_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(750);
1427const SEND_LOCK_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_millis(25);
1428
1429/// Shared acquisition for aggregate, one-shot and ledger locks, in that order.
1430/// Held until the returned guard drops.
1431pub(super) fn lock_telemetry_file(
1432    file: std::fs::File,
1433    kind: &str,
1434) -> Result<super::file_lock::FlockGuard, String> {
1435    let deadline = std::time::Instant::now() + SEND_LOCK_TIMEOUT;
1436    loop {
1437        match file.try_lock_exclusive() {
1438            Ok(()) => return Ok(super::file_lock::FlockGuard::from_locked(file)),
1439            Err(error) if super::file_lock::is_contended(&error) => {
1440                if std::time::Instant::now() >= deadline {
1441                    return Err(format!(
1442                        "telemetry {kind} lock timed out after {}ms; another operation is active",
1443                        SEND_LOCK_TIMEOUT.as_millis()
1444                    ));
1445                }
1446                std::thread::sleep(SEND_LOCK_RETRY_INTERVAL);
1447            }
1448            Err(error) => return Err(format!("cannot lock telemetry {kind} state: {error}")),
1449        }
1450    }
1451}
1452
1453pub fn build_daily_heartbeat(
1454    installation_id: String,
1455    deletion_token_hash: String,
1456    timestamp_bucket: String,
1457    distribution_channel: DistributionChannel,
1458    client_family: ClientFamily,
1459) -> Result<TelemetryBatchV2, String> {
1460    let install_age = environment::install_age(std::time::SystemTime::now());
1461    let active_days = environment::active_days(&installation_id, &timestamp_bucket);
1462    let batch = TelemetryBatchV2 {
1463        schema_version: SCHEMA_VERSION,
1464        deletion_token_hash,
1465        events: vec![TelemetryEnvelopeV2 {
1466            schema_version: SCHEMA_VERSION,
1467            timestamp_bucket,
1468            installation_id,
1469            account_id: None,
1470            organization_id: None,
1471            app_version: env!("CARGO_PKG_VERSION").to_string(),
1472            event: TelemetryEventV2::Heartbeat(HeartbeatMetrics {
1473                distribution_channel,
1474                client_family,
1475                operating_system: OperatingSystem::current(),
1476                architecture: Architecture::current(),
1477                install_age,
1478                active_days: Some(active_days),
1479                runtime_environment: Some(environment::runtime_environment()),
1480            }),
1481        }],
1482    };
1483    batch
1484        .validate()
1485        .map_err(|error| format!("invalid telemetry batch: {error:?}"))?;
1486    Ok(batch)
1487}
1488
1489#[cfg(test)]
1490mod tests;