Skip to main content

lean_ctx/core/
metering.rs

1//! Local, append-only metering for the free product.
2//!
3//! Metering is deliberately observational: failures are logged and never affect
4//! an MCP tool response.  The JSONL file contains token counts only.
5
6use chrono::{DateTime, NaiveDate, Utc};
7use serde::{Deserialize, Serialize};
8use std::fs::{OpenOptions, create_dir_all};
9use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
10use std::path::{Path, PathBuf};
11
12use fs2::FileExt;
13
14const METERING_FILE: &str = "metering.jsonl";
15
16/// `tool_name` of a native shell call the hook left to the agent's own tool
17/// (#1285): observed, but not routed through lean-ctx and not tokenized.
18pub const NATIVE_PASSTHROUGH_TOOL: &str = "native_shell_passthrough";
19
20/// Block size for reading the metering file backwards.
21const TAIL_BLOCK_BYTES: usize = 64 * 1024;
22
23/// Totals for one UTC day.
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub struct DayTotals {
26    pub input_tokens: u64,
27    pub savings_tokens: u64,
28    /// Calls that went through lean-ctx (every metered `ctx_*` call).
29    pub routed_calls: u64,
30    pub native_passthrough_calls: u64,
31}
32
33/// One completed tool call, recorded locally as a JSONL line.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct MeterEntry {
36    pub timestamp: DateTime<Utc>,
37    pub tool_name: String,
38    pub input_tokens: u64,
39    pub output_tokens: u64,
40    pub savings_tokens: u64,
41}
42
43impl MeterEntry {
44    #[must_use]
45    pub fn new(
46        tool_name: impl Into<String>,
47        input_tokens: u64,
48        output_tokens: u64,
49        savings_tokens: u64,
50    ) -> Self {
51        Self {
52            timestamp: Utc::now(),
53            tool_name: tool_name.into(),
54            input_tokens,
55            output_tokens,
56            savings_tokens,
57        }
58    }
59}
60
61/// Aggregate used by local value displays such as "Pro would have saved you $X".
62#[derive(Debug, Clone, Copy, Default, PartialEq)]
63pub struct MeterAggregate {
64    pub total_savings_tokens: u64,
65    pub total_calls: u64,
66    /// Weighted output/input ratio. `0.0` means no metered input exists yet.
67    pub avg_compression_ratio: f64,
68}
69
70/// Append-only local JSONL store.
71#[derive(Debug, Clone)]
72pub struct MeterStore {
73    path: PathBuf,
74}
75
76impl MeterStore {
77    #[must_use]
78    pub fn new(data_dir: impl AsRef<Path>) -> Self {
79        Self {
80            path: data_dir.as_ref().join(METERING_FILE),
81        }
82    }
83
84    pub fn from_data_dir() -> Result<Self, String> {
85        Ok(Self::new(crate::core::data_dir::lean_ctx_data_dir()?))
86    }
87
88    #[must_use]
89    pub fn path(&self) -> &Path {
90        &self.path
91    }
92
93    /// Appends one complete JSON object and newline. Call this only off the hot path.
94    pub fn append(&self, entry: &MeterEntry) -> Result<(), String> {
95        let Some(parent) = self.path.parent() else {
96            return Err("metering path has no parent".to_string());
97        };
98        create_dir_all(parent).map_err(|error| error.to_string())?;
99        let line = serde_json::to_string(entry).map_err(|error| error.to_string())?;
100        let mut file = OpenOptions::new()
101            .create(true)
102            .read(true)
103            .append(true)
104            .open(&self.path)
105            .map_err(|error| error.to_string())?;
106        file.lock_exclusive().map_err(|error| error.to_string())?;
107        let write_result = writeln!(file, "{line}").map_err(|error| error.to_string());
108        let unlock_result = FileExt::unlock(&file).map_err(|error| error.to_string());
109        write_result.and(unlock_result)
110    }
111
112    /// Schedules persistence and returns immediately; metering cannot delay a tool call.
113    pub fn append_best_effort(entry: MeterEntry) {
114        tokio::task::spawn_blocking(move || {
115            let result = Self::from_data_dir().and_then(|store| store.append(&entry));
116            if let Err(error) = result {
117                tracing::warn!(%error, "lean-ctx: failed to append local metering entry");
118            }
119        });
120    }
121
122    #[must_use]
123    pub fn aggregate(&self) -> MeterAggregate {
124        let Ok(file) = std::fs::File::open(&self.path) else {
125            return MeterAggregate::default();
126        };
127        let mut aggregate = MeterAggregate::default();
128        let mut total_input = 0_u64;
129        let mut total_output = 0_u64;
130        for line in BufReader::new(file).lines().map_while(Result::ok) {
131            let Ok(entry) = serde_json::from_str::<MeterEntry>(&line) else {
132                continue;
133            };
134            aggregate.total_calls = aggregate.total_calls.saturating_add(1);
135            aggregate.total_savings_tokens = aggregate
136                .total_savings_tokens
137                .saturating_add(entry.savings_tokens);
138            total_input = total_input.saturating_add(entry.input_tokens);
139            total_output = total_output.saturating_add(entry.output_tokens);
140        }
141        if total_input > 0 {
142            aggregate.avg_compression_ratio = total_output as f64 / total_input as f64;
143        }
144        aggregate
145    }
146
147    /// Totals for the UTC day `day`. The file is append-only and chronological and
148    /// grows to tens of MB, so it is read backwards and parsing stops at the first
149    /// earlier entry: the cost follows the day's volume, not the history.
150    #[must_use]
151    pub fn day_totals(&self, day: NaiveDate) -> DayTotals {
152        self.day_totals_in_blocks(day, TAIL_BLOCK_BYTES)
153    }
154
155    fn day_totals_in_blocks(&self, day: NaiveDate, block: usize) -> DayTotals {
156        let mut totals = DayTotals::default();
157        let Ok(mut file) = std::fs::File::open(&self.path) else {
158            return totals;
159        };
160        let Ok(mut pos) = file.seek(SeekFrom::End(0)) else {
161            return totals;
162        };
163        // Bytes of a line that started in an earlier block, carried forward.
164        let mut carry = Vec::new();
165        while pos > 0 {
166            let len = usize::try_from(pos).map_or(block, |p| p.min(block));
167            pos -= len as u64;
168            let mut buf = vec![0; len];
169            if file.seek(SeekFrom::Start(pos)).is_err() || file.read_exact(&mut buf).is_err() {
170                return totals;
171            }
172            buf.extend_from_slice(&carry);
173            let mut lines: Vec<&[u8]> = buf.split(|b| *b == b'\n').collect();
174            // The first segment may be cut off unless the block starts the file.
175            carry = if pos > 0 {
176                lines.remove(0).to_vec()
177            } else {
178                Vec::new()
179            };
180            for line in lines.into_iter().rev() {
181                let Ok(entry) = serde_json::from_slice::<MeterEntry>(line) else {
182                    continue;
183                };
184                let date = entry.timestamp.date_naive();
185                if date < day {
186                    return totals;
187                }
188                if date > day {
189                    continue;
190                }
191                totals.input_tokens = totals.input_tokens.saturating_add(entry.input_tokens);
192                totals.savings_tokens = totals.savings_tokens.saturating_add(entry.savings_tokens);
193                if entry.tool_name == NATIVE_PASSTHROUGH_TOOL {
194                    totals.native_passthrough_calls += 1;
195                } else {
196                    totals.routed_calls += 1;
197                }
198            }
199        }
200        totals
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn aggregates_jsonl_entries() {
210        let dir = tempfile::tempdir().unwrap();
211        let store = MeterStore::new(dir.path());
212        store
213            .append(&MeterEntry::new("ctx_read", 100, 20, 80))
214            .unwrap();
215        store
216            .append(&MeterEntry::new("ctx_search", 200, 100, 100))
217            .unwrap();
218
219        let aggregate = store.aggregate();
220        assert_eq!(aggregate.total_calls, 2);
221        assert_eq!(aggregate.total_savings_tokens, 180);
222        assert!((aggregate.avg_compression_ratio - 0.4).abs() < f64::EPSILON);
223    }
224
225    #[test]
226    fn day_totals_reads_only_the_requested_day_across_block_boundaries() {
227        let dir = tempfile::tempdir().unwrap();
228        let store = MeterStore::new(dir.path());
229        let at = |ts: &str, tool: &str, input, saved| MeterEntry {
230            timestamp: ts.parse().unwrap(),
231            tool_name: tool.into(),
232            input_tokens: input,
233            output_tokens: input - saved,
234            savings_tokens: saved,
235        };
236        store
237            .append(&at("2026-10-01T23:59:59Z", "ctx_read", 1_000, 900))
238            .unwrap();
239        store
240            .append(&at("2026-10-02T00:00:01Z", "ctx_read", 100, 80))
241            .unwrap();
242        std::fs::OpenOptions::new()
243            .append(true)
244            .open(store.path())
245            .unwrap()
246            .write_all(b"{not json\n")
247            .unwrap();
248        store
249            .append(&at("2026-10-02T09:00:00Z", NATIVE_PASSTHROUGH_TOOL, 0, 0))
250            .unwrap();
251        store
252            .append(&at("2026-10-02T10:00:00Z", "ctx_search", 50, 10))
253            .unwrap();
254
255        let day = NaiveDate::from_ymd_opt(2026, 10, 2).unwrap();
256        let expected = DayTotals {
257            input_tokens: 150,
258            savings_tokens: 90,
259            routed_calls: 2,
260            native_passthrough_calls: 1,
261        };
262        assert_eq!(store.day_totals(day), expected);
263        // Blocks smaller than a line: every line is split across reads.
264        assert_eq!(store.day_totals_in_blocks(day, 7), expected);
265        assert_eq!(
266            MeterStore::new(dir.path().join("missing")).day_totals(day),
267            DayTotals::default()
268        );
269    }
270
271    #[tokio::test]
272    async fn best_effort_append_does_not_block_calling_task() {
273        let entry = MeterEntry::new("ctx_read", 10, 2, 8);
274        let task = tokio::spawn(async move {
275            MeterStore::append_best_effort(entry);
276            42_u8
277        });
278        assert_eq!(task.await.unwrap(), 42);
279    }
280}