Skip to main content

cmd_usage/ocuse/
window.rs

1// Aggregation: rows -> per-model totals -> the documented windows.
2//
3// Go's limits are per model and per period: 5-hour = 20% of the monthly limit,
4// weekly = 50%, monthly = 100%. The monthly *period* is a subscription
5// anniversary that nothing local records, so we infer it from the earliest Go
6// row we have ever seen (its day-of-month) and fall back to the calendar month
7// when there is no evidence. The inference is reported, never silent.
8use crate::ocuse::db::Row;
9use crate::ocuse::zen::Catalog;
10
11pub const FIVE_HOUR_SECS: i64 = 5 * 3600;
12pub const WEEKLY_SECS: i64 = 7 * 86_400;
13/// How far back to read when inferring the anniversary.
14pub const LOOKBACK_SECS: i64 = 120 * 86_400;
15
16#[derive(Debug, Clone, Default)]
17pub struct Totals {
18    pub cost: f64,
19    pub requests: u64,
20    pub input: u64,
21    pub output: u64,
22    pub cache_read: u64,
23}
24
25impl Totals {
26    pub fn add(&mut self, row: &Row) {
27        self.cost += row.cost_usd;
28        self.requests += 1;
29        self.input += row.input;
30        self.output += row.output;
31        self.cache_read += row.cache_read;
32    }
33
34    pub fn tokens(&self) -> u64 {
35        self.input + self.output + self.cache_read
36    }
37}
38
39#[derive(Debug, Clone)]
40pub struct ModelUsage {
41    pub id: String,
42    pub provider: String,
43    pub limit: Option<f64>,
44    pub month: Totals,
45    pub five_hour: Totals,
46    pub weekly: Totals,
47}
48
49impl ModelUsage {
50    /// Fraction of the monthly limit used, when the docs give one.
51    pub fn month_use(&self) -> Option<f64> {
52        self.limit.filter(|l| *l > 0.0).map(|l| self.month.cost / l)
53    }
54}
55
56/// Which of this model's windows is over its share of the monthly limit, if
57/// any — the verdict the sidebar's flag, the watch frame and the cap
58/// notification all read from. Go meters per model AND per window (5-hour =
59/// 20%, weekly = 50%, monthly = 100%), so any one of them counts; the shortest
60/// window wins, being the most actionable. `None` for a free/unlimited model.
61pub fn over_window(model: &ModelUsage) -> Option<&'static str> {
62    let limit = model.limit.filter(|l| *l > 0.0)?;
63    let shares = &crate::ocuse::zen::catalog().go.window_share;
64    if model.five_hour.cost > limit * shares.five_hour {
65        Some("5-hour")
66    } else if model.weekly.cost > limit * shares.weekly {
67        Some("weekly")
68    } else if model.month.cost > limit * shares.monthly {
69        Some("monthly")
70    } else {
71        None
72    }
73}
74
75#[derive(Debug, Clone)]
76pub struct Report {
77    /// What the caller called this period ("calendar month", "all", "30d") for display.
78    pub period_label: String,
79    pub now_ms: i64,
80    pub since_ms: i64,
81    /// End of the period (epoch ms), resolved by the caller from its own start
82    /// — see `next_month`. `None` when the period has no boundary (`--window
83    /// all`); the rolling 5h/weekly windows never carry one.
84    pub period_end_ms: Option<i64>,
85    pub month_inferred: bool,
86    pub five_hour: Totals,
87    pub weekly: Totals,
88    pub month: Totals,
89    /// Sorted by month cost, descending.
90    pub models: Vec<ModelUsage>,
91}
92
93/// Civil date from a Unix day number (Howard Hinnant's algorithm) — avoids a
94/// date dependency for the one thing we need: a day-of-month.
95fn day_of_month(epoch_secs: i64) -> u32 {
96    civil(epoch_secs).2 as u32
97}
98
99pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
100    let y = if m <= 2 { y - 1 } else { y };
101    let era = y.div_euclid(400);
102    let yoe = y - era * 400;
103    let mp = if m > 2 { m - 3 } else { m + 9 };
104    let doy = (153 * mp + 2) / 5 + d - 1;
105    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
106    era * 146_097 + doe - 719_468
107}
108
109fn civil(epoch_secs: i64) -> (i64, i64, i64) {
110    let days = epoch_secs.div_euclid(86_400);
111    let z = days + 719_468;
112    let era = z.div_euclid(146_097);
113    let doe = z.rem_euclid(146_097);
114    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
115    let y = yoe + era * 400;
116    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
117    let mp = (5 * doy + 2) / 153;
118    let d = doy - (153 * mp + 2) / 5 + 1;
119    let m = if mp < 10 { mp + 3 } else { mp - 9 };
120    (if m <= 2 { y + 1 } else { y }, m, d)
121}
122
123/// Wall-clock now in epoch ms.
124pub fn now_ms() -> i64 {
125    std::time::SystemTime::now()
126        .duration_since(std::time::UNIX_EPOCH)
127        .map(|d| d.as_millis() as i64)
128        .unwrap_or(0)
129}
130
131/// Start of the calendar month, 00:00 UTC — the predictable default, since
132/// nothing local records a subscription anniversary (the console holds it).
133pub fn calendar_month_start(now_ms: i64) -> i64 {
134    let (year, month, _) = civil(now_ms / 1000);
135    days_from_civil(year, month, 1) * 86_400_000
136}
137
138/// The same day-of-month one month later, 00:00 UTC, in epoch ms; the year
139/// wraps. The day is clamped to 28 so an anniversary on the 29th–31st cannot
140/// skip a month into the wrong one — the same clamp `month_start` applies, so a
141/// period start it produced always has a matching end.
142pub fn next_month(ms: i64) -> i64 {
143    let (year, month, day) = civil(ms / 1000);
144    let (ny, nm) = if month == 12 {
145        (year + 1, 1)
146    } else {
147        (year, month + 1)
148    };
149    days_from_civil(ny, nm, day.min(28)) * 86_400_000
150}
151
152/// Start of the billing month: the most recent occurrence of the inferred
153/// anniversary day, else the first of the calendar month. Returns (start, inferred).
154pub fn month_start(rows: &[Row], now_ms: i64) -> (i64, bool) {
155    let now_secs = now_ms / 1000;
156    // Anniversary evidence: the oldest Go row we know about (its day-of-month),
157    // else the oldest row of any kind.
158    let (year, month, _day) = civil(now_secs);
159    let earliest_go = rows
160        .iter()
161        .filter(|r| r.provider == "opencode-go")
162        .map(|r| r.at_ms)
163        .min();
164    let anniversary = earliest_go
165        .or_else(|| rows.iter().map(|r| r.at_ms).min())
166        .map(|ms| day_of_month(ms / 1000));
167    if let Some(day_wanted) = anniversary {
168        let candidate = days_from_civil(year, month, day_wanted.min(28) as i64) * 86_400;
169        if candidate <= now_secs {
170            return (candidate * 1000, true);
171        }
172        let (py, pm) = if month == 1 {
173            (year - 1, 12)
174        } else {
175            (year, month - 1)
176        };
177        return (
178            days_from_civil(py, pm, day_wanted.min(28) as i64) * 86_400 * 1000,
179            true,
180        );
181    }
182    // No evidence at all: calendar month.
183    let current = civil(now_secs);
184    let days = days_from_civil(current.0, current.1, 1);
185    (days * 86_400 * 1000, false)
186}
187
188/// Build the report: window totals plus a per-model breakdown for the period.
189///
190/// `plan_id` selects which Go plan's per-model allowances the figures are
191/// measured against (the store records no subscription, so the caller chooses);
192/// `since_override` pins the period start (from `--period-start`); otherwise the
193/// anniversary heuristic in [`month_start`] applies. Rows before the period are
194/// anniversary evidence only — never listed — so the table and the totals agree.
195pub fn build(
196    rows: &[Row],
197    catalog: &Catalog,
198    plan_id: &str,
199    now_ms: i64,
200    since_override: Option<i64>,
201) -> Report {
202    let (inferred_start, month_inferred) = month_start(rows, now_ms);
203    let since_ms = since_override.unwrap_or(inferred_start);
204    let five_cut = now_ms - FIVE_HOUR_SECS * 1000;
205    let week_cut = now_ms - WEEKLY_SECS * 1000;
206
207    let mut report = Report {
208        period_label: "calendar month".into(),
209        now_ms,
210        since_ms,
211        period_end_ms: None,
212        month_inferred: since_override.is_none() && month_inferred,
213        five_hour: Totals::default(),
214        weekly: Totals::default(),
215        month: Totals::default(),
216        models: Vec::new(),
217    };
218    let mut by_model: std::collections::BTreeMap<String, ModelUsage> = Default::default();
219
220    for row in rows {
221        if row.at_ms < since_ms {
222            continue; // before the period: evidence for the anniversary only
223        }
224        report.month.add(row);
225        if row.at_ms >= week_cut {
226            report.weekly.add(row);
227        }
228        if row.at_ms >= five_cut {
229            report.five_hour.add(row);
230        }
231        let entry = by_model
232            .entry(row.model.clone())
233            .or_insert_with(|| ModelUsage {
234                id: row.model.clone(),
235                provider: row.provider.clone(),
236                limit: catalog.go_limit(plan_id, &row.model),
237                month: Totals::default(),
238                five_hour: Totals::default(),
239                weekly: Totals::default(),
240            });
241        entry.month.add(row);
242        if row.at_ms >= week_cut {
243            entry.weekly.add(row);
244        }
245        if row.at_ms >= five_cut {
246            entry.five_hour.add(row);
247        }
248    }
249
250    report.models = by_model.into_values().collect();
251    report.models.sort_by(|a, b| {
252        b.month
253            .cost
254            .partial_cmp(&a.month.cost)
255            .unwrap_or(std::cmp::Ordering::Equal)
256            .then_with(|| a.id.cmp(&b.id))
257    });
258    report
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::ocuse::db::Row;
265
266    fn row(at_s: i64, model: &str, cost: f64) -> Row {
267        Row {
268            at_ms: at_s * 1000,
269            provider: "opencode-go".into(),
270            model: model.into(),
271            cost_usd: cost,
272            ..Default::default()
273        }
274    }
275
276    #[test]
277    fn civil_helpers_round_trip() {
278        // 2026-09-27T00:00:00Z
279        let secs = days_from_civil(2026, 9, 27) * 86_400;
280        assert_eq!(civil(secs), (2026, 9, 27));
281        assert_eq!(day_of_month(secs), 27);
282    }
283
284    #[test]
285    fn next_month_keeps_the_day_and_wraps_the_year() {
286        // Same day-of-month, one month later, across a year boundary.
287        let dec15 = days_from_civil(2026, 12, 15) * 86_400_000;
288        assert_eq!(civil(next_month(dec15) / 1000), (2027, 1, 15));
289        // A calendar-month start (day 1) lands on day 1 of the next month.
290        let jan1 = days_from_civil(2026, 1, 1) * 86_400_000;
291        assert_eq!(civil(next_month(jan1) / 1000), (2026, 2, 1));
292        // A 31st start is clamped to 28, so it cannot skip a short month.
293        let jan31 = days_from_civil(2026, 1, 31) * 86_400_000;
294        assert_eq!(civil(next_month(jan31) / 1000), (2026, 2, 28));
295    }
296
297    #[test]
298    fn windows_are_rolling_and_the_month_is_inferred() {
299        let now = days_from_civil(2026, 9, 27) * 86_400 + 12 * 3600;
300        let rows = vec![
301            row(now - 60, "glm-5.3-flash", 1.0),          // inside 5h
302            row(now - 2 * 3600, "glm-5.3-flash", 2.0),    // inside 5h + week
303            row(now - 3 * 86_400, "kimi-k3", 4.0),        // inside week only
304            row(now - 40 * 86_400, "glm-5.3-flash", 8.0), // previous cycle: anniversary evidence
305        ];
306        let catalog = crate::ocuse::zen::catalog();
307        let report = build(
308            &rows,
309            &catalog,
310            crate::ocuse::zen::DEFAULT_PLAN,
311            now * 1000,
312            None,
313        );
314        assert!(
315            report.month_inferred,
316            "anniversary inferred from the earliest row"
317        );
318        assert!((report.five_hour.cost - 3.0).abs() < 1e-9);
319        assert!((report.weekly.cost - 7.0).abs() < 1e-9);
320        // anniversary day = 18 (40 days before the 27th), so this cycle starts Sep 18
321        assert!(
322            (report.month.cost - 7.0).abs() < 1e-9,
323            "month cost {}",
324            report.month.cost
325        );
326        let flash = report
327            .models
328            .iter()
329            .find(|m| m.id == "glm-5.3-flash")
330            .unwrap();
331        assert_eq!(flash.limit, Some(60.0));
332        assert!((flash.five_hour.cost - 3.0).abs() < 1e-9);
333    }
334
335    #[test]
336    fn models_sort_by_month_spend() {
337        let now = days_from_civil(2026, 9, 27) * 86_400;
338        let rows = vec![row(now - 60, "cheap", 0.1), row(now - 60, "pricey", 5.0)];
339        let report = build(
340            &rows,
341            &crate::ocuse::zen::catalog(),
342            crate::ocuse::zen::DEFAULT_PLAN,
343            now * 1000,
344            None,
345        );
346        assert_eq!(report.models[0].id, "pricey");
347    }
348}