Skip to main content

cmd_usage/arkuse/
window.rs

1// Aggregation: rows -> per-model totals -> the plan's own windows.
2//
3// Two independent sources, and they answer different questions:
4//
5// * the **meters** (`arkcli usage plan`) are authoritative — the control plane's
6//   own used/quota/reset for 5h, weekly and monthly (and daily, on media), and
7//   the only view that can see traffic from another machine;
8// * the **store** (opencode.db) is this machine's rows, which give per-model
9//   attribution and a reconciliation against the coefficients.
10//
11// Window bounds come from the meters when they answered: ARK's 5h is a block
12// that starts at the cycle's first request, the week is Monday 00:00, and the
13// month is the subscription anniversary — a rolling `now - length` cut
14// reproduces none of them. Without an answer the rolling cuts remain, labelled
15// as the local estimate they are.
16use crate::arkuse::api::Usage;
17use crate::arkuse::ark::Catalog;
18use crate::arkuse::db::Row;
19
20pub const FIVE_HOUR_SECS: i64 = 5 * 3600;
21pub const DAY_SECS: i64 = 86_400;
22pub const WEEKLY_SECS: i64 = 7 * 86_400;
23/// How far back to read when inferring the anniversary.
24pub const LOOKBACK_SECS: i64 = 120 * 86_400;
25
26#[derive(Debug, Clone, Default)]
27pub struct Totals {
28    /// AFP — the plan's own currency. Never dollars, and never the store's
29    /// `cost`: opencode records no AFP at all.
30    pub afp: f64,
31    pub requests: u64,
32    pub input: u64,
33    pub output: u64,
34    pub cache_read: u64,
35    pub cache_write: u64,
36    /// The earliest row folded in — what a rolling window's next reset derives
37    /// from (oldest request + window length). Never a fabricated `now + length`.
38    pub oldest_ms: Option<i64>,
39}
40
41impl Totals {
42    /// Add one turn at the AFP the catalogue computed for it. `None` (an
43    /// unknown model) counts the request and its tokens but no AFP, rather than
44    /// inventing a coefficient.
45    pub fn add(&mut self, row: &Row, afp: Option<f64>) {
46        self.afp += afp.unwrap_or(0.0);
47        self.requests += 1;
48        self.input += row.input;
49        self.output += row.output;
50        self.cache_read += row.cache_read;
51        self.cache_write += row.cache_write;
52        self.oldest_ms = Some(self.oldest_ms.map_or(row.at_ms, |at| at.min(row.at_ms)));
53    }
54
55    pub fn tokens(&self) -> u64 {
56        self.input + self.output + self.cache_read
57    }
58}
59
60#[derive(Debug, Clone)]
61pub struct ModelUsage {
62    pub id: String,
63    pub provider: String,
64    /// The coefficient in force for the period (promo applied).
65    pub coef: f64,
66    pub month: Totals,
67    pub five_hour: Totals,
68    pub weekly: Totals,
69}
70
71#[derive(Debug, Clone)]
72pub struct Report {
73    pub period_label: String,
74    pub now_ms: i64,
75    pub since_ms: i64,
76    pub period_end_ms: Option<i64>,
77    pub month_inferred: bool,
78    /// The control plane's meters, when `arkcli` answered.
79    pub account: Option<Usage>,
80    /// Why the meters are absent, when that is worth saying (`--no-api` is a
81    /// deliberate choice, not a fault).
82    pub account_error: Option<String>,
83    /// The tier the figures are measured against (explicit `--plan`, else the
84    /// profile's own `plan_tier`, else the catalogue default).
85    pub tier: String,
86    /// `arkcli` profile the meters came from, for the header.
87    pub profile: Option<String>,
88    /// The server offset the account's windows are cut in (seconds east of UTC).
89    /// Period bounds print in that offset, never in a guessed local zone.
90    pub offset_secs: i64,
91    pub five_hour: Totals,
92    pub weekly: Totals,
93    pub month: Totals,
94    /// Present only when the endpoint returned a daily window (media workloads;
95    /// a text-only plan exposes 5h/weekly/monthly).
96    pub daily: Option<Totals>,
97    /// Sorted by month AFP, descending.
98    pub models: Vec<ModelUsage>,
99}
100
101impl Report {
102    /// AFP per request over the 5-hour window — the meter's figure divided by
103    /// this store's request count. Fresh enough to be meaningful, and the
104    /// number the capacity questions are built on.
105    pub fn afp_per_request(&self) -> Option<f64> {
106        let account = self.account.as_ref()?;
107        let requests = self.five_hour.requests;
108        (requests > 0).then(|| account.five_hour.used / requests as f64)
109    }
110
111    /// Meter vs computed AFP over the 5-hour window, as a signed percentage of
112    /// the meter. A few percent is normal (a request still in flight, another
113    /// machine on the same key); a large gap means an unmodelled item (media or
114    /// Harness) or traffic this store cannot see.
115    pub fn reconcile(&self) -> Option<f64> {
116        let account = self.account.as_ref()?;
117        if account.five_hour.used <= 0.0 || self.five_hour.afp <= 0.0 {
118            return None;
119        }
120        Some((self.five_hour.afp - account.five_hour.used) / account.five_hour.used * 100.0)
121    }
122
123    /// Burn implied by the 5h window, in AFP/day: what the cycle's current pace
124    /// would consume over a day. `None` before the block has any use.
125    pub fn burn_per_day(&self) -> Option<f64> {
126        let account = self.account.as_ref()?;
127        (account.five_hour.used > 0.0).then(|| account.five_hour.used / 5.0 * 24.0)
128    }
129
130    /// The plan's own quota for a window: its monthly AFP times the catalogue's
131    /// share of it. ARK publishes both, so the local estimate can print the same
132    /// pair the console does — medium's 10,000 / 35,000 / 100,000 AFP are exactly
133    /// what its meters reported on 2026-10-20.
134    pub fn window_quota(&self, catalog: &Catalog, share: f64) -> Option<f64> {
135        catalog.plan(&self.tier).map(|plan| plan.afp * share)
136    }
137
138    /// When a locally cut window turns over: its oldest in-window row plus the
139    /// window's length, the same derivation the Go side uses. `None` before the
140    /// window has rows — `now + length` is not a reset the data supports.
141    pub fn rolling_reset(&self, totals: &Totals, dur_secs: i64) -> Option<i64> {
142        totals.oldest_ms.map(|at| at + dur_secs * 1000)
143    }
144}
145
146/// Civil date from a Unix day number (Howard Hinnant's algorithm) — no date
147/// dependency for the day-of-month the anniversary needs.
148fn day_of_month(epoch_secs: i64) -> u32 {
149    civil(epoch_secs).2 as u32
150}
151
152pub fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
153    let y = if m <= 2 { y - 1 } else { y };
154    let era = y.div_euclid(400);
155    let yoe = y - era * 400;
156    let mp = if m > 2 { m - 3 } else { m + 9 };
157    let doy = (153 * mp + 2) / 5 + d - 1;
158    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
159    era * 146_097 + doe - 719_468
160}
161
162fn civil(epoch_secs: i64) -> (i64, i64, i64) {
163    let days = epoch_secs.div_euclid(DAY_SECS);
164    let z = days + 719_468;
165    let era = z.div_euclid(146_097);
166    let doe = z.rem_euclid(146_097);
167    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
168    let y = yoe + era * 400;
169    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
170    let mp = (5 * doy + 2) / 153;
171    let d = doy - (153 * mp + 2) / 5 + 1;
172    let m = if mp < 10 { mp + 3 } else { mp - 9 };
173    (if m <= 2 { y + 1 } else { y }, m, d)
174}
175
176/// Wall-clock now in epoch ms.
177pub fn now_ms() -> i64 {
178    std::time::SystemTime::now()
179        .duration_since(std::time::UNIX_EPOCH)
180        .map(|d| d.as_millis() as i64)
181        .unwrap_or(0)
182}
183
184/// Start of the calendar month, 00:00 UTC — the predictable default when no
185/// meter names the anniversary.
186pub fn calendar_month_start(now_ms: i64) -> i64 {
187    let (year, month, _) = civil(now_ms / 1000);
188    days_from_civil(year, month, 1) * 86_400_000
189}
190
191/// The same day-of-month one month later, 00:00 UTC, in epoch ms; the year
192/// wraps and the day is clamped to 28 so an anniversary on the 29th–31st cannot
193/// skip a month.
194pub fn next_month(ms: i64) -> i64 {
195    let (year, month, day) = civil(ms / 1000);
196    let (ny, nm) = if month == 12 {
197        (year + 1, 1)
198    } else {
199        (year, month + 1)
200    };
201    days_from_civil(ny, nm, day.min(28)) * 86_400_000
202}
203
204/// The subscription month's start from the meter's own reset instant.
205///
206/// ARK's monthly reset is the last second of the anniversary day
207/// (`2026-11-19T23:59:59+08:00`), so the cycle starts at 00:00 on that
208/// day-of-month in the previous month, **in the reset's own offset** — the
209/// server speaks +08:00, and bucketing its instant as UTC would put the boundary
210/// eight hours off.
211pub fn month_start_before(reset_ms: i64, offset_secs: i64) -> i64 {
212    let local = reset_ms + offset_secs * 1000;
213    let (year, month, day) = civil(local.div_euclid(1000));
214    let (py, pm) = if month == 1 {
215        (year - 1, 12)
216    } else {
217        (year, month - 1)
218    };
219    days_from_civil(py, pm, day.min(28)) * 86_400_000 - offset_secs * 1000
220}
221
222/// Is `at_ms` on or before the end of the `YYYY-MM-DD` day? Used for promo
223/// coefficients, which the docs publish as dates.
224pub fn before_day_end(at_ms: i64, day: &str) -> bool {
225    let mut parts = day.split('-');
226    let (Some(y), Some(m), Some(d)) = (parts.next(), parts.next(), parts.next()) else {
227        return false;
228    };
229    let (Ok(y), Ok(m), Ok(d)) = (y.parse::<i64>(), m.parse::<i64>(), d.parse::<i64>()) else {
230        return false;
231    };
232    let end = (days_from_civil(y, m, d) + 1) * 86_400_000;
233    at_ms < end
234}
235
236/// Start of the billing month from the first plan request, else the calendar
237/// month. Returns `(start, inferred)`.
238pub fn month_start(rows: &[Row], now_ms: i64) -> (i64, bool) {
239    let now_secs = now_ms / 1000;
240    let (year, month, _) = civil(now_secs);
241    if let Some(ms) = rows.iter().map(|r| r.at_ms).min() {
242        let wanted = day_of_month(ms / 1000).min(28) as i64;
243        let candidate = days_from_civil(year, month, wanted) * DAY_SECS;
244        if candidate <= now_secs {
245            return (candidate * 1000, true);
246        }
247        let (py, pm) = if month == 1 {
248            (year - 1, 12)
249        } else {
250            (year, month - 1)
251        };
252        return (days_from_civil(py, pm, wanted) * DAY_SECS * 1000, true);
253    }
254    (days_from_civil(year, month, 1) * DAY_SECS * 1000, false)
255}
256
257/// Build the report: window totals plus a per-model breakdown for the period.
258pub fn build(
259    rows: &[Row],
260    catalog: &Catalog,
261    plan_id: &str,
262    now_ms: i64,
263    since_override: Option<i64>,
264    account: Option<&Usage>,
265) -> Report {
266    let (inferred_start, month_inferred) = month_start(rows, now_ms);
267    let since_ms = since_override.unwrap_or(inferred_start);
268    // Cut at the meter's own bounds when it answered. ARK's 5-hour window is a
269    // block that begins at the cycle's first request, the week starts Monday
270    // 00:00 in the server's offset, and the month is the anniversary — none of
271    // which a rolling cut reproduces.
272    let (five_start, five_end) = match account.and_then(|a| a.five_hour.reset_ms()) {
273        Some(reset) => (reset - FIVE_HOUR_SECS * 1000, reset),
274        None => (now_ms - FIVE_HOUR_SECS * 1000, i64::MAX),
275    };
276    let (week_start, week_end) = match account.and_then(|a| a.weekly.reset_ms()) {
277        Some(reset) => (reset - WEEKLY_SECS * 1000, reset),
278        None => (now_ms - WEEKLY_SECS * 1000, i64::MAX),
279    };
280    // Only media and Harness plans expose a daily window; text-only plans answer
281    // no `daily` period at all, so the row stays absent rather than reading zero.
282    let day_bounds = account
283        .and_then(|a| a.daily.as_ref())
284        .and_then(|m| m.reset_ms())
285        .map(|reset| (reset - DAY_SECS * 1000, reset));
286
287    let mut report = Report {
288        period_label: "calendar month".into(),
289        now_ms,
290        since_ms,
291        period_end_ms: None,
292        month_inferred: since_override.is_none() && month_inferred,
293        account: None,
294        account_error: None,
295        tier: plan_id.to_string(),
296        profile: account.map(|a| a.profile.clone()),
297        offset_secs: account.map_or(0, |a| a.monthly.offset_secs()),
298        five_hour: Totals::default(),
299        weekly: Totals::default(),
300        month: Totals::default(),
301        daily: day_bounds.map(|_| Totals::default()),
302        models: Vec::new(),
303    };
304    let mut by_model: std::collections::BTreeMap<String, ModelUsage> = Default::default();
305
306    for row in rows {
307        let in_month = row.at_ms >= since_ms;
308        let in_week = row.at_ms >= week_start && row.at_ms < week_end;
309        let in_five = row.at_ms >= five_start && row.at_ms < five_end;
310        let in_day = day_bounds.is_some_and(|(start, end)| row.at_ms >= start && row.at_ms < end);
311        if !in_month && !in_week && !in_five && !in_day {
312            continue;
313        }
314        let afp = catalog.afp(&row.model, row.at_ms, row.input, row.cache_read, row.output);
315        if in_month {
316            report.month.add(row, afp);
317        }
318        if in_day {
319            report
320                .daily
321                .get_or_insert_with(Totals::default)
322                .add(row, afp);
323        }
324        if in_week {
325            report.weekly.add(row, afp);
326        }
327        if in_five {
328            report.five_hour.add(row, afp);
329        }
330        let coef = catalog
331            .models
332            .iter()
333            .find(|m| m.id == row.model)
334            .map(|m| crate::arkuse::ark::effective_coef(m, row.at_ms))
335            .unwrap_or(0.0);
336        let entry = by_model
337            .entry(row.model.clone())
338            .or_insert_with(|| ModelUsage {
339                id: row.model.clone(),
340                provider: row.provider.clone(),
341                coef,
342                month: Totals::default(),
343                five_hour: Totals::default(),
344                weekly: Totals::default(),
345            });
346        if in_month {
347            entry.month.add(row, afp);
348        }
349        if in_week {
350            entry.weekly.add(row, afp);
351        }
352        if in_five {
353            entry.five_hour.add(row, afp);
354        }
355    }
356
357    report.models = by_model.into_values().collect();
358    report.models.sort_by(|a, b| {
359        b.month
360            .afp
361            .partial_cmp(&a.month.afp)
362            .unwrap_or(std::cmp::Ordering::Equal)
363            .then_with(|| a.id.cmp(&b.id))
364    });
365    report
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use crate::arkuse::db::Row;
372
373    fn row(at_s: i64, model: &str) -> Row {
374        Row {
375            at_ms: at_s * 1000,
376            provider: "agent-plan".into(),
377            model: model.into(),
378            input: 10_000,
379            ..Default::default()
380        }
381    }
382
383    fn meter(percent: f64, used: f64, resets_at: &str) -> crate::arkuse::api::Meter {
384        crate::arkuse::api::Meter::from_parts("ok", percent, used, 0.0, Some(resets_at), None)
385    }
386
387    #[test]
388    fn civil_helpers_round_trip() {
389        let secs = days_from_civil(2026, 9, 27) * 86_400;
390        assert_eq!(civil(secs), (2026, 9, 27));
391        assert_eq!(day_of_month(secs), 27);
392    }
393
394    /// The server's monthly reset is the last second of the anniversary day in
395    /// +08:00, so the cycle starts at 00:00 on that day-of-month one month
396    /// earlier *in that offset* — not eight hours off, and not 23:59:59.
397    #[test]
398    fn month_start_follows_the_servers_anniversary_and_offset() {
399        // 2026-11-19T23:59:59+08:00
400        let reset = (days_from_civil(2026, 11, 19) * 86_400 + 23 * 3600 + 59 * 60 + 59) * 1000
401            - 8 * 3600 * 1000;
402        let start = month_start_before(reset, 8 * 3600);
403        let local = (start + 8 * 3600 * 1000) / 1000;
404        assert_eq!(civil(local), (2026, 10, 19), "00:00 on the 19th, +08:00");
405        assert_eq!(local.rem_euclid(DAY_SECS), 0);
406    }
407
408    #[test]
409    fn promo_dates_end_at_the_days_close() {
410        let day = days_from_civil(2026, 12, 30) * 86_400_000;
411        assert!(before_day_end(day + 3_600_000, "2026-12-30"));
412        assert!(!before_day_end(day + 86_400_000, "2026-12-30"));
413    }
414
415    #[test]
416    fn the_meters_bounds_cut_the_windows_when_they_answered() {
417        // Mon 2026-10-19 12:00 UTC = 20:00 +08:00.
418        let now = days_from_civil(2026, 10, 19) * 86_400 + 12 * 3600;
419        let account = crate::arkuse::api::Usage {
420            // Reset at 23:00 +08:00 the same evening: the block is now-2h..+3h.
421            five_hour: meter(6.0, 600.0, "2026-10-19T23:00:00+08:00"),
422            daily: None,
423            // Monday 00:00 +08:00 = Sunday 16:00 UTC.
424            weekly: meter(3.0, 1_050.0, "2026-10-26T00:00:00+08:00"),
425            monthly: meter(51.0, 51_000.0, "2026-11-19T23:59:59+08:00"),
426            tier: Some("medium".into()),
427            profile: "agent-plan_cn-beijing_medium".into(),
428        };
429        let rows = vec![
430            // Eight days back: before the server's week, inside a rolling 7d.
431            row(now - 8 * 86_400, "deepseek-v4.1-flash"),
432            // Six hours back: inside the Monday week, before the 5-hour block.
433            row(now - 6 * 3600, "deepseek-v4.1-flash"),
434            // One minute back: inside the block.
435            row(now - 60, "deepseek-v4.1-flash"),
436        ];
437        let catalog = crate::arkuse::ark::catalog();
438        let month_start = days_from_civil(2026, 10, 1) * 86_400;
439        let report = build(
440            &rows,
441            &catalog,
442            "medium",
443            now * 1000,
444            Some(month_start * 1000),
445            Some(&account),
446        );
447        assert_eq!(report.five_hour.requests, 1, "only the in-block row");
448        assert_eq!(report.weekly.requests, 2, "the block plus six hours back");
449        assert_eq!(report.month.requests, 3, "all of them inside October");
450        assert!(report.five_hour.afp > 0.0);
451    }
452
453    #[test]
454    fn a_rolling_window_borrows_its_boundary_from_its_oldest_row() {
455        // Without a meter the cut is `now - length`, so the next turnover is the
456        // oldest row inside it plus the length — the same derivation the Go side
457        // uses. `now + length` would be a fabricated countdown.
458        let now = days_from_civil(2026, 10, 19) * 86_400;
459        let rows = vec![
460            row(now - 4 * 3600, "deepseek-v4.1-flash"),
461            row(now - 60, "deepseek-v4.1-flash"),
462        ];
463        let catalog = crate::arkuse::ark::catalog();
464        let report = build(&rows, &catalog, "medium", now * 1000, None, None);
465        assert_eq!(report.five_hour.requests, 2);
466        assert_eq!(report.five_hour.oldest_ms, Some((now - 4 * 3600) * 1000));
467        assert_eq!(
468            report.rolling_reset(&report.five_hour, FIVE_HOUR_SECS),
469            Some((now + 3600) * 1000),
470            "four hours of the block already spent"
471        );
472        assert_eq!(
473            report.window_quota(&catalog, catalog.windows.five_hour),
474            Some(10_000.0),
475            "medium's published 5-hour split"
476        );
477        assert_eq!(
478            report.rolling_reset(&Totals::default(), FIVE_HOUR_SECS),
479            None
480        );
481    }
482
483    #[test]
484    fn a_daily_meter_gets_its_own_cut_and_a_text_plan_has_none() {
485        // Mon 2026-10-19 12:00 UTC.
486        let now = days_from_civil(2026, 10, 19) * 86_400 + 12 * 3600;
487        let account = crate::arkuse::api::Usage {
488            five_hour: meter(6.0, 600.0, "2026-10-19T23:00:00+08:00"),
489            // 07:00 UTC: the day block is 07:00 yesterday .. 07:00 today.
490            daily: Some(meter(1.0, 100.0, "2026-10-19T15:00:00+08:00")),
491            weekly: meter(3.0, 1_050.0, "2026-10-26T00:00:00+08:00"),
492            monthly: meter(51.0, 51_000.0, "2026-11-19T23:59:59+08:00"),
493            tier: Some("medium".into()),
494            profile: "agent-plan_cn-beijing_medium".into(),
495        };
496        let rows = vec![
497            row(now - 10 * 3600, "deepseek-v4.1-flash"), // 02:00 UTC, inside
498            row(now - 3600, "deepseek-v4.1-flash"),      // 11:00 UTC, after the cut
499        ];
500        let catalog = crate::arkuse::ark::catalog();
501        let report = build(&rows, &catalog, "medium", now * 1000, None, Some(&account));
502        assert_eq!(report.daily.expect("media plan exposes a day").requests, 1);
503        // The same rows without a daily meter: the row stays absent, never zero.
504        let mut text_only = account;
505        text_only.daily = None;
506        let report = build(
507            &rows,
508            &catalog,
509            "medium",
510            now * 1000,
511            None,
512            Some(&text_only),
513        );
514        assert!(report.daily.is_none());
515    }
516
517    #[test]
518    fn models_sort_by_month_afp() {
519        let now = days_from_civil(2026, 9, 27) * 86_400;
520        let rows = vec![
521            row(now - 60, "glm-5.3-flash"),
522            row(now - 60, "deepseek-v4.1-flash"),
523        ];
524        let catalog = crate::arkuse::ark::catalog();
525        let report = build(&rows, &catalog, "medium", now * 1000, None, None);
526        assert_eq!(report.models[0].id, "deepseek-v4.1-flash", "2.5 > 0.5");
527    }
528
529    #[test]
530    fn an_unknown_model_counts_a_request_but_no_afp() {
531        let now = days_from_civil(2026, 9, 27) * 86_400;
532        let rows = vec![row(now - 60, "not-a-model")];
533        let catalog = crate::arkuse::ark::catalog();
534        let report = build(&rows, &catalog, "medium", now * 1000, None, None);
535        assert_eq!(report.month.requests, 1);
536        assert_eq!(report.month.afp, 0.0);
537    }
538}