Skip to main content

lean_ctx_ext/core/
metering.rs

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