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