lean_ctx/core/
metering.rs1use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use std::fs::{OpenOptions, create_dir_all};
9use std::io::{BufRead, BufReader, Write};
10use std::path::{Path, PathBuf};
11
12use fs2::FileExt;
13
14const METERING_FILE: &str = "metering.jsonl";
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct MeterEntry {
19 pub timestamp: DateTime<Utc>,
20 pub tool_name: String,
21 pub input_tokens: u64,
22 pub output_tokens: u64,
23 pub savings_tokens: u64,
24}
25
26impl MeterEntry {
27 #[must_use]
28 pub fn new(
29 tool_name: impl Into<String>,
30 input_tokens: u64,
31 output_tokens: u64,
32 savings_tokens: u64,
33 ) -> Self {
34 Self {
35 timestamp: Utc::now(),
36 tool_name: tool_name.into(),
37 input_tokens,
38 output_tokens,
39 savings_tokens,
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, Default, PartialEq)]
46pub struct MeterAggregate {
47 pub total_savings_tokens: u64,
48 pub total_calls: u64,
49 pub avg_compression_ratio: f64,
51}
52
53#[derive(Debug, Clone)]
55pub struct MeterStore {
56 path: PathBuf,
57}
58
59impl MeterStore {
60 #[must_use]
61 pub fn new(data_dir: impl AsRef<Path>) -> Self {
62 Self {
63 path: data_dir.as_ref().join(METERING_FILE),
64 }
65 }
66
67 pub fn from_data_dir() -> Result<Self, String> {
68 Ok(Self::new(crate::core::data_dir::lean_ctx_data_dir()?))
69 }
70
71 #[must_use]
72 pub fn path(&self) -> &Path {
73 &self.path
74 }
75
76 pub fn append(&self, entry: &MeterEntry) -> Result<(), String> {
78 let Some(parent) = self.path.parent() else {
79 return Err("metering path has no parent".to_string());
80 };
81 create_dir_all(parent).map_err(|error| error.to_string())?;
82 let line = serde_json::to_string(entry).map_err(|error| error.to_string())?;
83 let mut file = OpenOptions::new()
84 .create(true)
85 .read(true)
86 .append(true)
87 .open(&self.path)
88 .map_err(|error| error.to_string())?;
89 file.lock_exclusive().map_err(|error| error.to_string())?;
90 let write_result = writeln!(file, "{line}").map_err(|error| error.to_string());
91 let unlock_result = FileExt::unlock(&file).map_err(|error| error.to_string());
92 write_result.and(unlock_result)
93 }
94
95 pub fn append_best_effort(entry: MeterEntry) {
97 tokio::task::spawn_blocking(move || {
98 let result = Self::from_data_dir().and_then(|store| store.append(&entry));
99 if let Err(error) = result {
100 tracing::warn!(%error, "lean-ctx: failed to append local metering entry");
101 }
102 });
103 }
104
105 #[must_use]
106 pub fn aggregate(&self) -> MeterAggregate {
107 let Ok(file) = std::fs::File::open(&self.path) else {
108 return MeterAggregate::default();
109 };
110 let mut aggregate = MeterAggregate::default();
111 let mut total_input = 0_u64;
112 let mut total_output = 0_u64;
113 for line in BufReader::new(file).lines().map_while(Result::ok) {
114 let Ok(entry) = serde_json::from_str::<MeterEntry>(&line) else {
115 continue;
116 };
117 aggregate.total_calls = aggregate.total_calls.saturating_add(1);
118 aggregate.total_savings_tokens = aggregate
119 .total_savings_tokens
120 .saturating_add(entry.savings_tokens);
121 total_input = total_input.saturating_add(entry.input_tokens);
122 total_output = total_output.saturating_add(entry.output_tokens);
123 }
124 if total_input > 0 {
125 aggregate.avg_compression_ratio = total_output as f64 / total_input as f64;
126 }
127 aggregate
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 #[test]
136 fn aggregates_jsonl_entries() {
137 let dir = tempfile::tempdir().unwrap();
138 let store = MeterStore::new(dir.path());
139 store
140 .append(&MeterEntry::new("ctx_read", 100, 20, 80))
141 .unwrap();
142 store
143 .append(&MeterEntry::new("ctx_search", 200, 100, 100))
144 .unwrap();
145
146 let aggregate = store.aggregate();
147 assert_eq!(aggregate.total_calls, 2);
148 assert_eq!(aggregate.total_savings_tokens, 180);
149 assert!((aggregate.avg_compression_ratio - 0.4).abs() < f64::EPSILON);
150 }
151
152 #[tokio::test]
153 async fn best_effort_append_does_not_block_calling_task() {
154 let entry = MeterEntry::new("ctx_read", 10, 2, 8);
155 let task = tokio::spawn(async move {
156 MeterStore::append_best_effort(entry);
157 42_u8
158 });
159 assert_eq!(task.await.unwrap(), 42);
160 }
161}