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