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