cortexkit_provider_usage/lib.rs
1//! Shared wire types for the `ai-provider-quota` module's `usage.get` payload.
2//!
3//! The quota module serves an array of [`ProviderUsage`] per request; ALF's
4//! router (`codexbar-window-extractors.ts`), astrocyte's capacity axis, and the
5//! `ck quota` renderer all consume that shape. This crate is the single
6//! definition those consumers compile against, so the wire shape cannot drift
7//! without a shared-crate PR every side reviews.
8//!
9//! # Shape, not policy
10//!
11//! These are pure data types. Read-time transform semantics are PRODUCER
12//! behavior documented on the relevant fields but NOT enforced here:
13//! - **Banked-reset relaxation:** the quota module may zero
14//! [`RateWindow::used_percent`] (the EFFECTIVE number consumers pace on) and
15//! carry the provider-reported truth in [`RateWindow::raw_used_percent`].
16//! A consumer renders whatever the wire says; a sudden `0 → high` transition
17//! is an honest disarm (credits spent / auth broke), not a glitch.
18//! - **Cache-only partial arrays:** the quota module never blocks on a fetch,
19//! so a result may omit providers not yet swept. Missing ≠ zero.
20//! - **Degraded entries ride in-band:** a provider fetch failure is a normal
21//! [`ProviderUsage`] carrying `error`, not a request-level failure.
22//!
23//! # Serialization contract consumers depend on
24//! - camelCase keys (`usedPercent`, `resetsAt`, `windowMinutes`, `windowKind`,
25//! `extraRateWindows`, `rawUsedPercent`, `accountInfo`, `savedResets`,
26//! `usedCount`, `totalCount`).
27//! - A healthy entry MUST NOT carry `error` (consumers skip truthy-`error`
28//! entries), so it is omitted when absent.
29//! - A window is emitted when it has a `usedPercent`; `resetsAt` is OPTIONAL and
30//! omitted when the provider reports no reset (never fabricated).
31
32use serde::{Deserialize, Serialize};
33
34/// One rate-limit window: how much of a quota pool is spent and when it resets.
35#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
36#[serde(rename_all = "camelCase")]
37pub struct RateWindow {
38 /// 0..100 percent of the window's quota consumed. This is the EFFECTIVE
39 /// number consumers pace on: when banked-reset relaxation applies it is
40 /// zeroed, and the provider-reported percent moves to `raw_used_percent`.
41 pub used_percent: f64,
42 /// The provider-reported percent when `used_percent` has been relaxed to
43 /// an effective value (banked resets guarantee the window resets before
44 /// the wall).
45 ///
46 /// **Pace on `used_percent`, not on this.** The effective number is the real
47 /// headroom: a reset that is going to happen has already been accounted for.
48 /// Treating this as the truer figure routes work away from an account whose
49 /// credit is about to be spent — and the credit expires whether or not it is
50 /// used, so the cautious-looking reading is the lossy one. Display it beside
51 /// the effective number in a human-facing view, where a zero next to real
52 /// consumption would otherwise look like a fault.
53 ///
54 /// Emitted **only where the two diverge**, so its absence means they agree
55 /// and falling back to `used_percent` is exact rather than approximate.
56 /// Rendering a placeholder for absence would be wrong on every unrelaxed
57 /// window, which is nearly all of them.
58 #[serde(skip_serializing_if = "Option::is_none", default)]
59 pub raw_used_percent: Option<f64>,
60 /// ISO 8601 / RFC 3339 timestamp when the window resets. Omitted when the
61 /// provider reports no reset (e.g. an idle session window with nothing
62 /// pending) — never fabricated.
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub resets_at: Option<String>,
65 /// Window length in minutes. Omitted when the provider does not report one;
66 /// the consumer then paces on utilization alone rather than a burn rate.
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub window_minutes: Option<i64>,
69 /// The period this window covers, when the upstream names it: one of the
70 /// values in [`window_kind`], or a value a consumer has not seen yet.
71 ///
72 /// It exists for windows whose length cannot be stated in minutes. A month
73 /// varies, so a monthly window carries no `window_minutes`, and without a
74 /// name a consumer cannot tell it from any other window with no stated
75 /// length, or from whatever a provider's other page shape puts in the same
76 /// slot. The first reader matches a refusal that names its limit ("monthly
77 /// usage limit reached") to the window it refers to.
78 ///
79 /// **Absence means the upstream did not name the period, never "some other
80 /// kind".** A producer sets it only from the upstream's own label or field (a
81 /// page's "Monthly usage" heading, an API key such as `seven_day`), mapped
82 /// onto this vocabulary. A consumer that needs the period of an unnamed
83 /// window falls back to `window_minutes`.
84 ///
85 /// An open string, not an enum: an unknown kind must reach the consumer
86 /// intact, not fail the decode of the whole response.
87 #[serde(skip_serializing_if = "Option::is_none", default)]
88 pub window_kind: Option<String>,
89 /// Absolute consumed count in the window (e.g. tokens, requests). A count
90 /// of things, so integral by contract, and only ever the upstream's own
91 /// figure — never recovered from a percentage and a cap (a derived figure
92 /// can carry a disagreement between two provider endpoints while wearing
93 /// a type that claims exactness). Omitted when the upstream reports only
94 /// a percentage. Human-facing UIs can show "10,336 / 40,000" alongside
95 /// the percentage for richer context.
96 #[serde(skip_serializing_if = "Option::is_none", default)]
97 pub used_count: Option<f64>,
98 /// Absolute total cap for the window, when the upstream states one. May
99 /// appear without `used_count`: the cap can be known while the consumed
100 /// figure is only a percentage.
101 #[serde(skip_serializing_if = "Option::is_none", default)]
102 pub total_count: Option<f64>,
103 /// How the window's quota comes back, when the upstream STATES a mechanic.
104 ///
105 /// **Absence licenses nothing.** It means the upstream said nothing about
106 /// replenishment — never "this is a fixed window". Most providers state
107 /// nothing, so absence is the common case and carries no information.
108 #[serde(skip_serializing_if = "Option::is_none", default)]
109 pub regeneration: Option<Regeneration>,
110 /// How the window's consumption divides among the upstream's own
111 /// categories, when the upstream states that split.
112 ///
113 /// **Absence means not fetched or not published, never "all zero".** Most
114 /// providers state no split, so absence is the common case.
115 #[serde(skip_serializing_if = "Option::is_none", default)]
116 pub breakdown: Option<UsageBreakdown>,
117}
118
119/// The values [`RateWindow::window_kind`] carries today.
120///
121/// Named by PERIOD, not by each upstream's own term, so a consumer branches on
122/// one vocabulary across providers. A producer maps the upstream's name onto it:
123/// Anthropic's `five_hour` and Ollama's "Session usage" are both
124/// [`FIVE_HOUR`]; Anthropic's `seven_day` and Ollama's "Weekly usage" are both
125/// [`WEEKLY`].
126///
127/// The list is open. A consumer must handle a value it does not know, and a
128/// new period is a new constant here, never a reuse of an existing one.
129pub mod window_kind {
130 /// A window that rolls over hourly, as the upstream names it. Its length can
131 /// still be unstated: Ollama's "Hourly usage" block gives none.
132 pub const HOURLY: &str = "hourly";
133 /// A five-hour window, which several upstreams call a session.
134 pub const FIVE_HOUR: &str = "five_hour";
135 /// A one-day window.
136 pub const DAILY: &str = "daily";
137 /// A seven-day window.
138 pub const WEEKLY: &str = "weekly";
139 /// A month-long window. Its length changes with the month, so it carries no
140 /// `window_minutes`, and it resets on the upstream's billing anchor, which
141 /// need not be the first of a calendar month.
142 pub const MONTHLY: &str = "monthly";
143}
144
145/// A window's consumption split by category, as the upstream reports it.
146///
147/// First observed on Anthropic's weekly window, which splits consumption across
148/// `claude_code`, `chat`, `cowork` and `other`. A consumer that sees only some
149/// of an account's traffic uses the split to tell which share of a movement in
150/// `used_percent` it can account for.
151#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
152#[serde(rename_all = "camelCase")]
153pub struct UsageBreakdown {
154 /// When the upstream computed the split, RFC 3339. Omitted when unstated.
155 #[serde(skip_serializing_if = "Option::is_none", default)]
156 pub as_of: Option<String>,
157 /// When the window this split describes began, RFC 3339, as the upstream
158 /// states it. Lets a consumer tell which window a split belongs to across a
159 /// reset. Omitted when unstated.
160 #[serde(skip_serializing_if = "Option::is_none", default)]
161 pub window_started_at: Option<String>,
162 /// One row per category, in the upstream's order.
163 pub rows: Vec<BreakdownRow>,
164}
165
166/// One category's part of a window's consumption.
167#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
168#[serde(rename_all = "camelCase")]
169pub struct BreakdownRow {
170 /// The upstream's own category key, verbatim: never mapped or renamed.
171 ///
172 /// A `String` rather than an enum, because this is an observability wire: a
173 /// category added upstream must arrive as itself, not fail the record.
174 pub key: String,
175 /// This category's share of what the window has CONSUMED, 0..=100.
176 ///
177 /// **A share, not a used-percent.** Across rows it sums to about 100 whatever
178 /// the window's `used_percent`: a window 85% used whose consumption was all
179 /// one category reads 100 on that row, not 85. The part of `used_percent` a
180 /// category accounts for is `used_percent * share_percent / 100`.
181 ///
182 /// Omitted, never zero, when the upstream's row carries no figure.
183 #[serde(skip_serializing_if = "Option::is_none", default)]
184 pub share_percent: Option<f64>,
185}
186
187/// A stated replenishment mechanic for a window.
188///
189/// Present only where an upstream describes how the quota returns. It exists
190/// because the alternative — projecting a replenishment onto `resets_at` — makes
191/// a continuously refilling pool indistinguishable from a hard cutoff, and the
192/// projection is unrecoverable once published.
193#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
194#[serde(rename_all = "camelCase")]
195pub struct Regeneration {
196 /// Which mechanic the upstream describes: `cliff`, `drip`, or `unstated`.
197 ///
198 /// **PACING DEPENDS ON THIS AND THE THREE ANSWERS DIFFER SHARPLY.** A rate
199 /// alone cannot separate them: "1,000,000 units per 720h" describes both a
200 /// lump arriving on one instant and a steady accrual every hour, and the two
201 /// give opposite answers about headroom on day 14.
202 ///
203 /// - `cliff` — the whole amount lands at `resets_at`, and **accrual before
204 /// that instant is exactly zero**. A consumer treating this as gradual
205 /// believes it has partial headroom when it has none.
206 /// - `drip` — the quota accrues continuously at `rate`, so headroom grows
207 /// between reads and an exhausted pool becomes usable again without any
208 /// reset event.
209 /// - `unstated` — the upstream states that quota replenishes but nothing
210 /// establishes which mechanic. **No pacing claim exists: display the rate,
211 /// never derive headroom from it.** Same contract as `PoolFunding::Unknown`
212 /// and `PoolBasis::Unstated`, for the same reason — an honest arm keeps a
213 /// producer from guessing to satisfy the type.
214 ///
215 /// A plain `String` rather than an enum, and REQUIRED rather than optional.
216 /// String because this is an observability wire: a variant added later must
217 /// not make an old consumer drop the record that reports a state it has never
218 /// seen. Required because an optional discriminator invites exactly the
219 /// inference this field exists to prevent — with no value present, a consumer
220 /// picks one, and the picker has less evidence than the producer.
221 ///
222 /// Treat an unrecognised value as `unstated`: render it, pace on nothing.
223 pub mechanic: String,
224 /// The stated replenishment rate, when the upstream gives one.
225 ///
226 /// Absent means the mechanic is described without a quantity — a real and
227 /// common shape ("credits refresh monthly" with no amount). Absence here says
228 /// nothing about `mechanic`, which stays authoritative.
229 #[serde(skip_serializing_if = "Option::is_none", default)]
230 pub rate: Option<RegenerationRate>,
231}
232
233/// How much quota returns, and over what period.
234#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
235#[serde(rename_all = "camelCase")]
236pub struct RegenerationRate {
237 /// Amount replenished per period, in the SAME units as `used_count` and
238 /// `total_count` on the window. Not integral by contract: unlike a count, a
239 /// rate is legitimately fractional (a monthly grant read per hour).
240 pub amount: f64,
241 /// Length of the replenishment period in minutes.
242 ///
243 /// Distinct from the window's own `window_minutes`, which they need not
244 /// match: an observed payload states a 720h refill period on a balance whose
245 /// percentage is measured against a larger total that includes a purchased
246 /// pool that never refills.
247 pub per_minutes: i64,
248}
249
250/// A per-model window bundled under one account (e.g. Antigravity's Geminis).
251#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
252#[serde(rename_all = "camelCase")]
253pub struct ExtraWindow {
254 /// Human-facing label. Absent when the producer has no display text for this
255 /// window; render `id` instead rather than dropping the entry.
256 #[serde(skip_serializing_if = "Option::is_none")]
257 pub title: Option<String>,
258 /// Stable identifier to match on. Absent when the producer cannot name the
259 /// window stably. **Not unique across providers** — one provider's ids are
260 /// model names, another's its own scope labels — so key on
261 /// `(provider, id)`, never on `id` alone.
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub id: Option<String>,
264 /// The figures for this window. Absent means the provider **named a limit it
265 /// could not read a figure for**, which is not the same as no limit: the
266 /// entry is still evidence the limit exists.
267 #[serde(skip_serializing_if = "Option::is_none")]
268 pub window: Option<RateWindow>,
269}
270
271/// The window topology for one account: up to three account-wide pools plus an
272/// optional list of per-model pools.
273#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
274#[serde(rename_all = "camelCase")]
275pub struct Usage {
276 /// The provider's **shortest** window, not its most constrained one. Absent
277 /// when the provider reported no window of that cadence.
278 ///
279 /// The three slots are positions, not a ranking, and **they can have holes**:
280 /// each is filled from its own optional upstream field, so `secondary` may be
281 /// absent while `tertiary` is present. Walk all three plus
282 /// `extra_rate_windows` rather than stopping at the first gap, and take the
283 /// maximum when asking how much headroom an account has.
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub primary: Option<RateWindow>,
286 /// The next cadence up, typically weekly. Absent means not reported — never
287 /// that the window exists at zero. See [`Usage::primary`] on slot holes.
288 #[serde(skip_serializing_if = "Option::is_none")]
289 pub secondary: Option<RateWindow>,
290 /// A third account-wide window where a provider has one. Absent means not
291 /// reported. See [`Usage::primary`] on slot holes.
292 #[serde(skip_serializing_if = "Option::is_none")]
293 pub tertiary: Option<RateWindow>,
294 /// Windows whose meaning has no slot — per-model pools, scoped weeklies.
295 /// Absent means the provider published none.
296 ///
297 /// These are **real limits**, not extras in the dispensable sense: a consumer
298 /// ignoring this list silently ignores whichever limits did not fit three
299 /// slots.
300 #[serde(skip_serializing_if = "Option::is_none")]
301 pub extra_rate_windows: Option<Vec<ExtraWindow>>,
302}
303
304/// An amount of money or credit, in integer minor units.
305///
306/// Not a float, and the reason is not stylistic. A balance is compared against
307/// zero on every routing decision that reads it, and binary floating point
308/// cannot hold ordinary decimal amounts exactly — the nearest `f64` to `0.1` is
309/// not `0.1`, so sums drift and a comparison near zero can fall either way. The
310/// providers agree: DeepSeek and MiniMax both send decimal strings, and
311/// Anthropic sends integer minor units with an exponent.
312///
313/// Parse a provider's own representation once, where its precision is still
314/// known, rather than passing a float along and re-rendering it.
315#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
316#[serde(rename_all = "camelCase")]
317pub struct Amount {
318 /// The amount in minor units: `1050` with `exponent: 2` is 10.50.
319 pub minor: i64,
320 /// Decimal places in `minor`. `2` for currencies with cents; `0` for whole
321 /// credits or points.
322 pub exponent: u8,
323 /// What the amount is denominated in: a currency code like `"USD"`, or a
324 /// provider's own label for its credits.
325 ///
326 /// A free string rather than a currency enum, because not every pool is
327 /// money — some are points that convert to no currency, and an enum would
328 /// force those into a currency slot or drop them.
329 pub unit: String,
330}
331
332/// Where a pool's balance came from, which decides what a consumer may promise.
333#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
334#[serde(rename_all = "snake_case")]
335pub enum PoolFunding {
336 /// Given by the provider: a promotion, a trial grant, a voucher. Spendable
337 /// without a bill.
338 Granted,
339 /// Bought. Spending it costs money.
340 Purchased,
341 /// Included in a subscription the account already pays for.
342 Subscription,
343 /// The provider separates this pool but does not say what funds it, **or**
344 /// the producer named a funding kind this consumer does not recognise.
345 ///
346 /// A correct answer rather than a failure one: some providers name their
347 /// pools without defining them, and guessing the funding is how a consumer
348 /// ends up spending money it meant to protect.
349 ///
350 /// It is also the deserialization fallback, and the two meanings genuinely
351 /// agree — a funding kind added after this consumer was built is, to this
352 /// consumer, of unknown funding. Without the fallback an unrecognised value
353 /// fails the whole `ProviderUsage` entry rather than this one field, so a
354 /// new pool kind would take an account's *usage* down with it and read as
355 /// the provider being unavailable.
356 #[serde(other)]
357 Unknown,
358}
359
360/// How a pool's `remaining` was obtained.
361#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
362#[serde(rename_all = "snake_case")]
363pub enum PoolBasis {
364 /// The provider states this pool's remaining balance directly.
365 Reported,
366 /// Computed from a total and a consumption figure that covers several pools
367 /// at once, so the split between them is not known.
368 ///
369 /// The distinction is load-bearing for any "spend only granted credits"
370 /// policy: against a `Reported` pool it is exact, and against a `Derived`
371 /// one it can only be a ceiling.
372 Derived,
373 /// No basis was stated, or one was stated that this consumer does not
374 /// recognise. **Treat `remaining` as a ceiling, never as exact.**
375 ///
376 /// This is deliberately its own variant rather than folding an unrecognised
377 /// value into [`Self::Derived`]. Both are read conservatively, so the
378 /// spending behaviour is the same either way — but `Derived` is a statement
379 /// about how a number was obtained, and answering "I do not know" with it
380 /// would have the producer assert a fact it does not hold. That is the
381 /// failure this type exists to prevent, one level up.
382 ///
383 /// Reading it conservatively is safe in the direction that matters: an
384 /// exact remainder treated as a ceiling under-spends, while a ceiling
385 /// treated as exact spends money that may not be there.
386 #[serde(other)]
387 Unstated,
388}
389
390/// A prepaid balance or credit pool on an account.
391///
392/// Plural by necessity: one figure cannot express "9.50 granted and 40
393/// purchased", which is exactly the distinction a consumer needs to spend the
394/// first without spending the second.
395#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
396#[serde(rename_all = "camelCase")]
397pub struct Pool {
398 /// The provider's own name for this pool, never one invented here.
399 ///
400 /// Providers separate pools without always defining them — a wallet may list
401 /// voucher, cash and credit balances and document none of them. Passing the
402 /// provider's name through lets a consumer decide; renaming one `granted`
403 /// would be inventing the label a spend policy keys on.
404 pub id: String,
405 /// Human-readable name for display.
406 pub label: String,
407 /// What funds this pool.
408 pub funding: PoolFunding,
409 /// What is left, when it can be established.
410 #[serde(skip_serializing_if = "Option::is_none", default)]
411 pub remaining: Option<Amount>,
412 /// The pool's size, when the provider reports one.
413 #[serde(skip_serializing_if = "Option::is_none", default)]
414 pub total: Option<Amount>,
415 /// How `remaining` was obtained. Read it before acting on `remaining`.
416 pub basis: PoolBasis,
417 /// Whether the provider says this pool may currently be drawn on.
418 ///
419 /// Read from the provider, never inferred from `remaining > 0`: a pool can
420 /// be non-empty and closed, which several providers publish directly through
421 /// their own enable flags. Absent means the provider does not say.
422 #[serde(skip_serializing_if = "Option::is_none", default)]
423 pub spendable: Option<bool>,
424 /// When the pool's period renews, as RFC 3339, if the provider states one.
425 ///
426 /// **Absent means not stated, never "does not renew".** Some providers state
427 /// a period for a money pool (a monthly workspace credit limit with its own
428 /// reset time); others state none for a pool that may well be monthly (paid
429 /// overage named `monthly_limit` with no date anywhere in the payload). A
430 /// consumer that reads absence as "this balance is all there will ever be"
431 /// under-spends at best, and at worst treats a pool that refills on the 1st
432 /// as permanently exhausted.
433 ///
434 /// A producer sets it only from a value the provider sent. A period guessed
435 /// from a field name is the fabricated-precision failure this crate refuses
436 /// everywhere else.
437 #[serde(skip_serializing_if = "Option::is_none", default)]
438 pub resets_at: Option<String>,
439}
440
441/// Account labels and subscription information supplied by a provider or vault.
442#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
443#[serde(rename_all = "camelCase")]
444pub struct AccountInfo {
445 /// Account email. Absent when the upstream does not identify the account that
446 /// way — not a signal about the account itself.
447 #[serde(skip_serializing_if = "Option::is_none", default)]
448 pub email: Option<String>,
449 /// Organisation label. Absent when the upstream reports none; absent does not
450 /// mean a personal account.
451 #[serde(skip_serializing_if = "Option::is_none", default)]
452 pub org_name: Option<String>,
453 /// The upstream's **own** plan label, not a normalised vocabulary, so it is
454 /// not comparable across providers. Display and grouping only. Absent when
455 /// the upstream states no plan.
456 #[serde(skip_serializing_if = "Option::is_none", default)]
457 pub plan_type: Option<String>,
458}
459
460impl AccountInfo {
461 pub fn is_empty(&self) -> bool {
462 self.email.is_none() && self.org_name.is_none() && self.plan_type.is_none()
463 }
464}
465
466/// One saved reset credit and its expiry time.
467#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
468#[serde(rename_all = "camelCase")]
469pub struct CreditExpiry {
470 pub expires_at: String,
471}
472
473/// Saved reset credits reported by Codex's read-only credits endpoint.
474#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
475#[serde(rename_all = "camelCase")]
476pub struct SavedResets {
477 #[serde(default)]
478 pub available_count: u32,
479 /// When the next credit lapses. Absent means **no credit states an expiry**,
480 /// which is not the same as none expiring soon.
481 #[serde(skip_serializing_if = "Option::is_none", default)]
482 pub soonest_expires_at: Option<String>,
483 #[serde(default)]
484 pub credits: Vec<CreditExpiry>,
485}
486
487fn account_info_is_empty(value: &Option<AccountInfo>) -> bool {
488 value.as_ref().map(AccountInfo::is_empty).unwrap_or(true)
489}
490
491/// One provider/account's usage entry. The `/usage` response is an array of
492/// these. A fetch failure becomes an entry carrying `error` (silent-degrade),
493/// never a failure of the whole array.
494#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
495#[serde(rename_all = "camelCase")]
496pub struct ProviderUsage {
497 /// CodexBar provider name (e.g. "codex"), which consumers map to their own id.
498 pub provider: String,
499 /// Canonical API provider identifier — the models.dev slug for the same
500 /// provider (e.g. "openai" when `provider == "codex"`, "anthropic" for
501 /// "claude", "google" for "gemini", "xai" for "grok"). Present when the
502 /// producer knows the canonical name; absent for providers with no models.dev
503 /// counterpart, where consumers fall back to `provider`. Lets every consumer
504 /// key on one canonical name instead of each maintaining its own
505 /// CodexBar-name → canonical map.
506 #[serde(skip_serializing_if = "Option::is_none", default)]
507 pub api_provider: Option<String>,
508 /// The account this entry describes, as the credential store identifies it.
509 ///
510 /// Absent means the producer **could not resolve an identity for this
511 /// credential**, not that the provider has one account. Some credentials
512 /// carry no account identity at all (a bare API key), and an entry is also
513 /// emitted unlabelled while an identity is still being confirmed — so an
514 /// unlabelled entry is not evidence that a labelled one does not exist.
515 #[serde(skip_serializing_if = "Option::is_none")]
516 pub account: Option<String>,
517 /// Which retrieval path produced this (e.g. "oauth") — observability only.
518 ///
519 /// **Per lane, not per account, and it moves.** One account can be reached
520 /// through more than one credential path, and which one answers is decided
521 /// per fetch by whichever is healthy. So the same account can report one
522 /// value on a poll and another on the next with nothing having changed about
523 /// the account, the credential, or anything the consumer did. Do not key on
524 /// it, branch on it, or treat a change in it as an event.
525 #[serde(skip_serializing_if = "Option::is_none")]
526 pub source: Option<String>,
527 /// Display labels for the account. Absent when the upstream supplies none of
528 /// them; carries no operational meaning.
529 #[serde(skip_serializing_if = "account_info_is_empty", default)]
530 pub account_info: Option<AccountInfo>,
531 /// When this entry's figures were last **successfully** fetched — producer
532 /// time, per entry, never a common instant across the array.
533 ///
534 /// Absent means this credential has never had a successful fetch. It keeps
535 /// its old value while a failure is being retried, so it ages honestly rather
536 /// than pausing; never restamp it with your own poll time.
537 #[serde(skip_serializing_if = "Option::is_none", default)]
538 pub fetched_at: Option<String>,
539 /// Banked quota-reset credits held by this account.
540 ///
541 /// Absent means there is no credit inventory to report — which includes the
542 /// inventory lookup having **failed** on this fetch, since it is separate
543 /// from the usage fetch and may fail without degrading the entry. Absent is
544 /// therefore not "zero credits held".
545 #[serde(skip_serializing_if = "Option::is_none", default)]
546 pub saved_resets: Option<SavedResets>,
547 /// The windows. Absent on a degraded entry, and on an entry whose credential
548 /// works but whose account reports no quota at all — read `error` and
549 /// `error_class` to tell those apart, rather than inferring from this field.
550 #[serde(skip_serializing_if = "Option::is_none")]
551 pub usage: Option<Usage>,
552 /// Prepaid balances and credit pools on this account, when the provider
553 /// reports any.
554 ///
555 /// Deliberately apart from [`Self::usage`], because a pool and a rate window
556 /// are different facts that fail in opposite directions: over-consuming a
557 /// window gets you throttled and recovers by waiting, while over-consuming a
558 /// balance gets you billed and recovers by paying. Nothing in a routing loop
559 /// can undo the second, so a balance is never expressed as a window, never
560 /// carries a reset, and never appears as a percentage — a consumer that
561 /// found one where it expects headroom would pace into a bill.
562 ///
563 /// Absent means the producer has nothing to say, which is not the same as an
564 /// account having no credit. Empty means it looked and the provider reports
565 /// no pools.
566 #[serde(skip_serializing_if = "Option::is_none", default)]
567 pub spend: Option<Vec<Pool>>,
568 /// Present only on a degraded entry. The consumer skips any entry with a
569 /// truthy `error`.
570 #[serde(skip_serializing_if = "Option::is_none")]
571 pub error: Option<String>,
572 /// A stable, machine-readable name for *why* a degraded entry failed,
573 /// published beside the human-readable `error`.
574 ///
575 /// `error` is prose with no stability promise, so consumers are told not to
576 /// branch on it — which leaves them no way to separate failures that mean
577 /// something from failures that are a permanent, correct state. A host that
578 /// never configured a provider and a host whose credential broke this
579 /// morning both produce a degraded entry, and only the second is worth
580 /// anyone's attention.
581 ///
582 /// Classes currently produced:
583 ///
584 /// | Value | Meaning |
585 /// |---|---|
586 /// | `credential_absent` | No credential was found. Permanent and correct on a host that never configured this provider; nothing to fix. |
587 /// | `credential_unusable` | A credential was found but cannot be used as it stands (empty, incomplete, or refused by the credential store). Someone configured this and it needs fixing. |
588 /// | `credential_rejected` | The upstream rejected the credential (401/403). Usually means logging in again. |
589 /// | `no_quota_reported` | The credential works and the account genuinely has no quota to report. Not a failure. |
590 /// | `upstream_failed` | The upstream could not be reached or returned an error status. Usually transient. |
591 /// | `decode_failed` | The response arrived but was not the expected shape. |
592 ///
593 /// **This list will grow.** A consumer must render an unrecognised class as
594 /// a degraded entry with an unknown reason — never drop the entry, and
595 /// never fold it into an existing bucket. It is a `String` rather than an
596 /// enum for exactly that reason: on an observability surface, meeting an
597 /// unknown value must not turn into a parse failure that makes a provider
598 /// disappear at the moment its state changed.
599 ///
600 /// Absent on healthy entries, and absent from any producer that predates
601 /// this field.
602 #[serde(skip_serializing_if = "Option::is_none", default)]
603 pub error_class: Option<String>,
604 /// Present when this entry is a last-known-good reading served through an
605 /// ongoing failure, absent when it is a fresh success.
606 ///
607 /// Without it a preserved reading is byte-identical to a fresh one apart
608 /// from `fetched_at`, so a consumer cannot separate "this figure is old
609 /// because the producer has been unable to reach the provider" from "this
610 /// figure is old because nothing polled recently". Those have opposite
611 /// remedies — the first is a reason to stop acting on the number, the
612 /// second is not — and a consumer with only a timestamp has to guess with a
613 /// wall-clock threshold, which denies fresh-enough data to catch stale data.
614 ///
615 /// A producer serving preserved readings is behaving correctly: a brief
616 /// upstream failure should not blank a window. This field discloses that it
617 /// is happening rather than reporting a fault.
618 #[serde(skip_serializing_if = "Option::is_none", default)]
619 pub stale: Option<Stale>,
620}
621
622/// Why an entry is being served through a failure, and since when.
623#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
624#[serde(rename_all = "camelCase")]
625pub struct Stale {
626 /// When the producer first failed to refresh this entry, RFC3339.
627 ///
628 /// Distinct from `fetched_at`, which is when the served reading was
629 /// obtained. The gap between them is how long the producer has been unable
630 /// to look, which is the quantity a staleness policy actually wants: a
631 /// reading can be minutes old with the producer perfectly healthy, or
632 /// seconds old with the producer failing since just after it was taken.
633 pub since: String,
634 /// The failure class, using the same vocabulary as `error_class` on a
635 /// degraded entry.
636 ///
637 /// Carried so a consumer can tell a flapping upstream from a credential
638 /// that has started refusing, without branching on prose. Optional because
639 /// a producer may preserve a reading for a reason it cannot classify.
640 #[serde(skip_serializing_if = "Option::is_none", default)]
641 pub class: Option<String>,
642}
643
644impl ProviderUsage {
645 /// A healthy entry with resolved windows.
646 pub fn healthy(provider: &str, account: Option<String>, source: &str, usage: Usage) -> Self {
647 Self {
648 provider: provider.to_string(),
649 api_provider: None,
650 account,
651 source: Some(source.to_string()),
652 account_info: None,
653 fetched_at: None,
654 saved_resets: None,
655 usage: Some(usage),
656 spend: None,
657 error: None,
658 error_class: None,
659 stale: None,
660 }
661 }
662
663 /// A degraded entry: the provider is named so the consumer can correlate,
664 /// but it carries only an error string and no windows.
665 pub fn degraded(provider: &str, error: impl std::fmt::Display) -> Self {
666 Self {
667 provider: provider.to_string(),
668 api_provider: None,
669 account: None,
670 source: None,
671 account_info: None,
672 fetched_at: None,
673 saved_resets: None,
674 usage: None,
675 spend: None,
676 error: Some(error.to_string()),
677 error_class: None,
678 stale: None,
679 }
680 }
681
682 /// A degraded entry that also names *why* it failed.
683 ///
684 /// Prefer this over [`Self::degraded`] wherever the producer knows the
685 /// class: without it a consumer can only tell an unconfigured provider from
686 /// a broken one by reading prose it has been told not to parse. See
687 /// [`ProviderUsage::error_class`] for the classes and for the rule that an
688 /// unrecognised one must still render.
689 pub fn degraded_with_class(
690 provider: &str,
691 error: impl std::fmt::Display,
692 error_class: impl Into<String>,
693 ) -> Self {
694 Self {
695 error_class: Some(error_class.into()),
696 ..Self::degraded(provider, error)
697 }
698 }
699}
700
701/// Shared account-identity type (commons#13, operator-ratified 2026-08-29).
702///
703/// `provider` was two namespaces wearing one name across the fleet: usage
704/// sources, credential configs, sweep-unit names, and catalog slugs all emit
705/// plausible provider strings, so a wrong join never fails loudly. This type
706/// makes the namespace explicit so no consumer ever writes the alias map that
707/// a silent join failure invites.
708///
709/// Absence is ordinary here, not exceptional: at ratification time 34 of 40
710/// live wire entries carried no verified identity. Consumers must treat a
711/// missing `account_ref` as the expected shape, never as an error.
712#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
713pub struct AccountIdentity {
714 /// Source-scoped provider name, spelled in the emitting module's own
715 /// namespace (a usage source's "claude", a registry's invented plan
716 /// name). MANDATORY. The same string under two sources need not mean the
717 /// same thing; this field never claims cross-source meaning.
718 pub provider: String,
719
720 /// The models.dev slug for this provider, when a join to the model
721 /// catalog EXISTS. Named for its source deliberately: a second catalog
722 /// source would get its own field rather than silently changing this
723 /// one's meaning.
724 ///
725 /// `None` means NO JOIN EXISTS — never fall back to [`Self::provider`].
726 /// models.dev publishes no alias metadata of any kind (measured:
727 /// no `alias`, `renamed_from`, `supersedes`, or `deprecated_by`), so
728 /// there is nothing for a fallback to fall back to; "use the other name"
729 /// fabricates a join, and a fabricated join produces plausible rows
730 /// forever instead of erroring.
731 #[serde(default, skip_serializing_if = "Option::is_none")]
732 pub models_dev_provider_slug: Option<String>,
733
734 /// Verified account identity, when the provider disclosed one.
735 ///
736 /// PROPAGATION RULE: provenance travels with the value and is NEVER
737 /// re-derived downstream. The moment a consumer writes
738 /// `if provider == "anthropic" { assume frozen }` they have re-implemented
739 /// the producer's discriminant from the outside, keyed on a provider
740 /// string — the exact namespace hazard this type exists to prevent,
741 /// recreated one level down. The producer that holds the value at its
742 /// source knows which branch produced it; nobody else does.
743 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub account_ref: Option<AccountRef>,
745}
746
747/// An account identity value bundled with how it was obtained.
748///
749/// Bundled rather than parallel fields, so the bug-causing states — a value
750/// with no provenance, or a provenance with no value — are unrepresentable.
751/// Absent identity carries no provenance because there is nothing to qualify.
752#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
753pub struct AccountRef {
754 /// The identity value as the provider disclosed it (an email, an account
755 /// id, an org slug — whatever the source speaks).
756 pub value: String,
757 /// Which staleness story produced [`Self::value`]. See
758 /// [`AccountRefProvenance`] for why the two must never be conflated.
759 pub provenance: AccountRefProvenance,
760}
761
762/// The two ways an account identity reaches the wire, with opposite staleness
763/// properties.
764///
765/// The discriminant says a value *could* be wrong, not that it *is*: the
766/// frozen branch goes stale only if a record is re-pointed without a
767/// re-login. A consumer holding a [`Self::StoredLogin`] value knows it needs
768/// watching; a [`Self::LiveClaim`] value re-corrects on every read.
769///
770/// This enum is CLOSED on purpose — identity-bearing, not diagnostic. An
771/// unknown provenance must refuse to decode rather than default: a wrong
772/// guess here poisons joins silently, which is worse than a loud decode
773/// error on a version skew.
774///
775/// WHAT CLOSURE COSTS: because decoders refuse unknown spellings, adding a
776/// variant is a WIRE-BREAKING change for every consumer on an older crate
777/// version — a coordinated version boundary across all adopters, never an
778/// additive edit. That cost is deliberate. It is also a boundary nobody
779/// should be crossing:
780///
781/// This enum discriminates STALENESS AMONG CUSTODIAN-VOUCHED VALUES. A
782/// consumer-derived identity — parsed from a logged-in page, say — is not a
783/// third staleness case: it changes WHO VOUCHES, and belongs in its own
784/// field rather than as a variant here. [`AccountIdentity::account_ref`]
785/// means "the custodian observed this"; a value the custodian did not vouch
786/// for does not belong in it at any spelling, because then a provenance tag
787/// does load-bearing work AGAINST its own field's semantics — the shape
788/// that fails quietly. A separate field is additive and breaks no decoder;
789/// a variant here is the coordinated wire boundary AND an unattested value
790/// in an attested field — the expensive mistake and the semantic one at
791/// once.
792#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
793#[serde(rename_all = "snake_case")]
794pub enum AccountRefProvenance {
795 /// Parsed from the served token at read time — re-derived on every get,
796 /// self-correcting.
797 LiveClaim,
798 /// Stored at login time and returned unchanged — frozen, can go stale
799 /// silently if the account is re-pointed without a re-login.
800 StoredLogin,
801}
802
803#[cfg(test)]
804mod tests {
805 /// `AccountInfo` IS AN IDENTITY STRUCT, SO AN ADDITIVE FIELD HERE IS A
806 /// DECISION RATHER THAN A DETAIL. This pins its serialised key set closed
807 /// in both directions so adding one reddens here, at the moment it is
808 /// written, rather than at whatever a consumer notices later.
809 ///
810 /// Why an identity struct earns a pin that an ordinary payload does not:
811 /// downstream, `ck quota --redact` renders these fields for screenshots and
812 /// removes the identifying ones BY NAME -- so a new identifying field
813 /// defaults to visible, the redaction filter keeps passing, its tests keep
814 /// going green, and a published screenshot carries a name nobody can
815 /// unpublish. Measured live 2026-09-18: Anthropic's `/api/oauth/profile`
816 /// carries `account.full_name`, `account.display_name` and
817 /// `organization.name` beside the subscription tier a consumer wanted, so
818 /// the pressure to widen this struct is real and already arrived once.
819 ///
820 /// THE THREE-LINK CHAIN, so nobody mistakes one link for the whole:
821 /// 1 the capturing consumer decodes only the fields it means to keep,
822 /// 2 THIS PIN (the shared struct's key set, closed at the producer),
823 /// 3 the rendering consumer's redaction filter, downstream.
824 ///
825 /// Link 2 alone does not stop a field being added; it stops one being added
826 /// WITHOUT SOMEONE SAYING SO. If you are here because this test is red and
827 /// the field is genuinely wanted, add it, update this test, and tell the
828 /// `ck quota --redact` owner -- that last step is the whole reason the test
829 /// exists.
830 #[test]
831 fn the_account_info_key_set_is_closed_in_both_directions() {
832 let populated = AccountInfo {
833 email: Some("operator@example.com".to_string()),
834 org_name: Some("Example Org".to_string()),
835 plan_type: Some("max".to_string()),
836 };
837 let value = serde_json::to_value(&populated).expect("serialise");
838 let object = value.as_object().expect("object");
839 let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
840 keys.sort_unstable();
841 assert_eq!(
842 keys,
843 ["email", "orgName", "planType"],
844 "AccountInfo's serialised key set changed. If a field was ADDED: is it \
845 personally identifying? If so it reaches `ck quota --redact`, whose filter \
846 removes fields by name and will pass it straight through into a screenshot. \
847 Update this test and notify that owner."
848 );
849
850 // The other direction: every empty account must serialise to nothing at
851 // all, so a consumer cannot read an absent identity as an empty one.
852 let empty = serde_json::to_value(AccountInfo::default()).expect("serialise");
853 assert_eq!(
854 empty.as_object().expect("object").len(),
855 0,
856 "an empty AccountInfo must emit no keys; a present-but-null field reads to a \
857 consumer as a resolved-and-blank identity rather than an unresolved one"
858 );
859 }
860
861 /// Full AccountIdentity round-trips with every field present, and the
862 /// wire spelling of both provenance branches is pinned.
863 #[test]
864 fn account_identity_full_round_trip_pins_provenance_spellings() {
865 let full = AccountIdentity {
866 provider: "claude".into(),
867 models_dev_provider_slug: Some("anthropic".into()),
868 account_ref: Some(AccountRef {
869 value: "ufuk@example.com".into(),
870 provenance: AccountRefProvenance::StoredLogin,
871 }),
872 };
873 let wire = serde_json::to_string(&full).unwrap();
874 assert!(
875 wire.contains("\"stored_login\""),
876 "frozen branch spelling: {wire}"
877 );
878 let back: AccountIdentity = serde_json::from_str(&wire).unwrap();
879 assert_eq!(back, full);
880
881 let live = serde_json::to_string(&AccountRefProvenance::LiveClaim).unwrap();
882 assert_eq!(live, "\"live_claim\"");
883 }
884
885 /// A minimal identity (provider only) keeps absent fields ABSENT on the
886 /// wire — not null — so pre-identity consumers see byte-identical output.
887 #[test]
888 fn a_minimal_identity_serializes_provider_only() {
889 let min = AccountIdentity {
890 provider: "kimi-for-coding".into(),
891 models_dev_provider_slug: None,
892 account_ref: None,
893 };
894 let wire = serde_json::to_string(&min).unwrap();
895 assert_eq!(wire, r#"{"provider":"kimi-for-coding"}"#);
896 let back: AccountIdentity = serde_json::from_str(&wire).unwrap();
897 assert_eq!(back, min);
898 }
899
900 /// A null slug stays None through a round trip and never inherits the
901 /// provider's value: the fallback is fabrication, and this asserts the
902 /// bytes, not the intent.
903 #[test]
904 fn a_none_slug_never_becomes_the_provider_value() {
905 let id = AccountIdentity {
906 provider: "qwen-cloud".into(),
907 models_dev_provider_slug: None,
908 account_ref: None,
909 };
910 let wire = serde_json::to_string(&id).unwrap();
911 assert!(
912 !wire.contains("models_dev_provider_slug"),
913 "absent, not null: {wire}"
914 );
915 let back: AccountIdentity = serde_json::from_str(&wire).unwrap();
916 assert_eq!(back.models_dev_provider_slug, None);
917 assert_ne!(
918 back.models_dev_provider_slug.as_deref(),
919 Some(back.provider.as_str()),
920 "a decode path that mirrors provider into the slug has fabricated a join"
921 );
922 }
923
924 /// Unknown provenance REFUSES to decode. Identity-bearing enum: a
925 /// wrong-guess default poisons joins silently, so version skew must fail
926 /// loud here, unlike the diagnostic value enums.
927 #[test]
928 fn an_unknown_provenance_refuses_to_decode() {
929 let err = serde_json::from_str::<AccountRef>(r#"{"value":"x","provenance":"vibes"}"#);
930 assert!(err.is_err(), "unknown provenance must refuse, got {err:?}");
931 // And a bare value with no provenance is unrepresentable:
932 let err2 = serde_json::from_str::<AccountRef>(r#"{"value":"x"}"#);
933 assert!(
934 err2.is_err(),
935 "value without provenance must refuse, got {err2:?}"
936 );
937 }
938
939 /// A window with no stated mechanic serializes exactly as before.
940 ///
941 /// The additive guarantee: every existing producer omits the field, and a
942 /// consumer on the previous version must see byte-identical output.
943 #[test]
944 fn a_window_without_regeneration_is_unchanged_on_the_wire() {
945 let window = RateWindow {
946 used_percent: 42.0,
947 raw_used_percent: None,
948 resets_at: Some("2026-08-17T00:00:00Z".to_string()),
949 window_minutes: Some(300),
950 used_count: None,
951 total_count: None,
952 regeneration: None,
953 window_kind: None,
954 breakdown: None,
955 };
956 let json = serde_json::to_string(&window).expect("serializes");
957 assert!(
958 !json.contains("regeneration"),
959 "an absent mechanic must not appear on the wire: {json}"
960 );
961 }
962
963 /// A payload from before this field decodes into the new shape.
964 #[test]
965 fn a_pre_regeneration_payload_still_decodes() {
966 let json = r#"{"usedPercent":42.0,"resetsAt":"2026-08-17T00:00:00Z","windowMinutes":300}"#;
967 let window: RateWindow = serde_json::from_str(json).expect("older payloads must decode");
968 assert_eq!(window.regeneration, None);
969 }
970
971 /// The observed cliff shape round-trips, rate and all.
972 ///
973 /// SHAPE FROM A LIVE CAPTURE (insula#1, 2026-08-17): a credentialed JetBrains
974 /// account stating `tariff: { amount: "1000000", duration: "PT720H" }` beside
975 /// a known next-refill instant. First observed rate-bearing payload; the
976 /// numbers here are its scrubbed values.
977 #[test]
978 fn a_stated_cliff_refill_round_trips() {
979 let window = RateWindow {
980 used_percent: 0.67,
981 raw_used_percent: None,
982 resets_at: Some("2026-08-15T06:00:00.000Z".to_string()),
983 window_minutes: None,
984 used_count: Some(8100.0),
985 total_count: Some(1_207_000.0),
986 regeneration: Some(Regeneration {
987 mechanic: "cliff".to_string(),
988 rate: Some(RegenerationRate {
989 amount: 1_000_000.0,
990 per_minutes: 43_200,
991 }),
992 }),
993 window_kind: None,
994 breakdown: None,
995 };
996 let json = serde_json::to_string(&window).expect("serializes");
997 let back: RateWindow = serde_json::from_str(&json).expect("round-trips");
998 assert_eq!(back, window);
999 assert!(
1000 json.contains("\"perMinutes\":43200"),
1001 "camelCase on the wire: {json}"
1002 );
1003 }
1004
1005 /// A mechanic with no rate is a valid statement.
1006 ///
1007 /// "Credits refresh monthly" with no amount is a real upstream shape, and it
1008 /// is precisely the case a rate-only field could not have expressed — which
1009 /// is why this is an object rather than a bare rate.
1010 #[test]
1011 fn a_mechanic_without_a_rate_is_valid() {
1012 let json = r#"{"usedPercent":10.0,"regeneration":{"mechanic":"drip"}}"#;
1013 let window: RateWindow = serde_json::from_str(json).expect("decodes");
1014 let regeneration = window.regeneration.expect("the mechanic is stated");
1015 assert_eq!(regeneration.mechanic, "drip");
1016 assert_eq!(
1017 regeneration.rate, None,
1018 "the mechanic stands without a rate"
1019 );
1020 }
1021
1022 /// A mechanic this version has never seen decodes intact.
1023 ///
1024 /// THE REASON `mechanic` IS A STRING. On an observability wire a new variant
1025 /// must not delete the record that reports it: an enum here would fail the
1026 /// whole entry, so the state a consumer most needs to see is the one that
1027 /// would vanish. Consumers treat an unrecognised value as `unstated` --
1028 /// render it, pace on nothing.
1029 #[test]
1030 fn an_unrecognised_mechanic_decodes_rather_than_dropping_the_window() {
1031 let json = r#"{"usedPercent":10.0,"regeneration":{"mechanic":"stepped_thaw"}}"#;
1032 let window: RateWindow = serde_json::from_str(json).expect("a future variant must decode");
1033 assert_eq!(
1034 window.regeneration.expect("present").mechanic,
1035 "stepped_thaw"
1036 );
1037 assert_eq!(window.used_percent, 10.0, "the rest of the window survives");
1038 }
1039
1040 /// An entry without the field serializes exactly as before.
1041 ///
1042 /// Every consumer decoding today's shape must keep working, so absence has
1043 /// to be byte-identical rather than merely tolerated.
1044 #[test]
1045 fn a_fresh_entry_carries_no_stale_key() {
1046 let entry = ProviderUsage::healthy("codex", None, "oauth", Usage::default());
1047 let json = serde_json::to_string(&entry).expect("entry serializes");
1048
1049 assert!(
1050 !json.contains("stale"),
1051 "a fresh entry must not emit the key at all: {json}"
1052 );
1053 }
1054
1055 /// A preserved reading states when the producer stopped being able to look.
1056 ///
1057 /// `since` is deliberately not `fetchedAt`: the reading was taken when it
1058 /// was taken, and the failure began afterwards. The gap between the two is
1059 /// how long the producer has been blind, which is the quantity a staleness
1060 /// policy wants -- an entry can be minutes old with the producer healthy,
1061 /// or seconds old with it failing since just after the read.
1062 #[test]
1063 fn a_preserved_reading_states_when_the_failure_began() {
1064 let mut entry = ProviderUsage::healthy("codex", None, "oauth", Usage::default());
1065 entry.fetched_at = Some("2026-08-13T10:00:00Z".to_string());
1066 entry.stale = Some(Stale {
1067 since: "2026-08-13T10:02:00Z".to_string(),
1068 class: Some("upstream_failed".to_string()),
1069 });
1070
1071 let json = serde_json::to_string(&entry).expect("entry serializes");
1072 let back: ProviderUsage = serde_json::from_str(&json).expect("entry round-trips");
1073 let stale = back.stale.expect("the disclosure survives the round trip");
1074
1075 assert_eq!(stale.since, "2026-08-13T10:02:00Z");
1076 assert_eq!(stale.class.as_deref(), Some("upstream_failed"));
1077 assert_ne!(
1078 Some(stale.since.as_str()),
1079 back.fetched_at.as_deref(),
1080 "the two timestamps answer different questions and must not be conflated"
1081 );
1082 assert!(
1083 json.contains("\"stale\""),
1084 "the key is camelCase on the wire: {json}"
1085 );
1086 }
1087
1088 /// A producer that cannot classify the failure still discloses the state.
1089 ///
1090 /// Optional rather than required so a preserved reading is never suppressed
1091 /// for want of a label -- disclosing "this is stale, cause unstated" beats
1092 /// looking fresh.
1093 #[test]
1094 fn a_disclosure_without_a_class_still_decodes() {
1095 let json = r#"{"provider":"codex","stale":{"since":"2026-08-13T10:02:00Z"}}"#;
1096 let entry: ProviderUsage = serde_json::from_str(json).expect("decodes");
1097 let stale = entry.stale.expect("present");
1098
1099 assert_eq!(stale.class, None);
1100 assert_eq!(stale.since, "2026-08-13T10:02:00Z");
1101 }
1102
1103 /// An entry from a producer that predates the field decodes unchanged.
1104 #[test]
1105 fn an_entry_without_the_field_decodes() {
1106 let json = r#"{"provider":"codex","source":"oauth"}"#;
1107 let entry: ProviderUsage = serde_json::from_str(json).expect("decodes");
1108
1109 assert_eq!(entry.stale, None);
1110 assert_eq!(entry.provider, "codex");
1111 }
1112
1113 use super::*;
1114
1115 #[test]
1116 fn account_info_is_omitted_when_empty_and_keeps_partial_labels() {
1117 let bare = ProviderUsage::healthy(
1118 "codex",
1119 None,
1120 "oauth",
1121 Usage {
1122 primary: Some(RateWindow {
1123 used_percent: 10.0,
1124 raw_used_percent: None,
1125 resets_at: None,
1126 window_minutes: Some(300),
1127 used_count: None,
1128 total_count: None,
1129 regeneration: None,
1130 window_kind: None,
1131 breakdown: None,
1132 }),
1133 ..Default::default()
1134 },
1135 );
1136 let json = serde_json::to_string(&bare).unwrap();
1137 assert!(
1138 !json.contains("accountInfo"),
1139 "empty accountInfo must be omitted"
1140 );
1141
1142 let mut labeled = bare.clone();
1143 labeled.account_info = Some(AccountInfo {
1144 email: Some("a@b.com".to_string()),
1145 org_name: None,
1146 plan_type: Some("pro".to_string()),
1147 });
1148 let json = serde_json::to_string(&labeled).unwrap();
1149 assert!(json.contains("\"email\":\"a@b.com\""));
1150 assert!(json.contains("\"planType\":\"pro\""));
1151 assert!(!json.contains("orgName"), "absent orgName must be omitted");
1152 }
1153
1154 #[test]
1155 fn saved_resets_use_camel_case_and_round_trip() {
1156 let entry = ProviderUsage {
1157 saved_resets: Some(SavedResets {
1158 available_count: 2,
1159 soonest_expires_at: Some("2026-07-31T20:11:35Z".to_string()),
1160 credits: vec![CreditExpiry {
1161 expires_at: "2026-07-31T20:11:35Z".to_string(),
1162 }],
1163 }),
1164 ..ProviderUsage::degraded("codex", "x")
1165 };
1166 let json = serde_json::to_string(&entry).unwrap();
1167 assert!(json.contains("\"savedResets\""));
1168 assert!(json.contains("\"availableCount\":2"));
1169 assert!(json.contains("\"soonestExpiresAt\""));
1170 let back: ProviderUsage = serde_json::from_str(&json).unwrap();
1171 assert_eq!(back, entry);
1172 }
1173
1174 #[test]
1175 fn raw_used_percent_is_absent_from_unrelaxed_windows_and_camel_case_when_present() {
1176 let unrelaxed = RateWindow {
1177 used_percent: 41.0,
1178 raw_used_percent: None,
1179 resets_at: Some("2026-07-20T00:00:00Z".to_string()),
1180 window_minutes: Some(10080),
1181 used_count: None,
1182 total_count: None,
1183 regeneration: None,
1184 window_kind: None,
1185 breakdown: None,
1186 };
1187 let json = serde_json::to_string(&unrelaxed).unwrap();
1188 assert!(
1189 !json.contains("rawUsedPercent"),
1190 "unrelaxed window must not carry the field"
1191 );
1192
1193 let relaxed = RateWindow {
1194 used_percent: 0.0,
1195 raw_used_percent: Some(70.0),
1196 resets_at: Some("2026-07-20T00:00:00Z".to_string()),
1197 window_minutes: Some(10080),
1198 used_count: None,
1199 total_count: None,
1200 regeneration: None,
1201 window_kind: None,
1202 breakdown: None,
1203 };
1204 let json = serde_json::to_string(&relaxed).unwrap();
1205 assert!(json.contains("\"rawUsedPercent\":70.0"));
1206 let back: RateWindow = serde_json::from_str(&json).unwrap();
1207 assert_eq!(back, relaxed);
1208 }
1209
1210 #[test]
1211 fn healthy_entry_omits_error_and_degraded_entry_omits_usage() {
1212 let healthy = ProviderUsage::healthy("codex", None, "oauth", Usage::default());
1213 let json = serde_json::to_string(&healthy).unwrap();
1214 assert!(!json.contains("error"));
1215
1216 let degraded = ProviderUsage::degraded("codex", "no session");
1217 let json = serde_json::to_string(°raded).unwrap();
1218 assert!(json.contains("\"error\":\"no session\""));
1219 assert!(!json.contains("usage"));
1220 }
1221
1222 #[test]
1223 fn api_provider_is_camel_case_present_when_set_and_omitted_when_absent() {
1224 let mut entry = ProviderUsage::healthy("codex", None, "oauth", Usage::default());
1225 let json = serde_json::to_string(&entry).unwrap();
1226 assert!(
1227 !json.contains("apiProvider"),
1228 "absent api_provider must be omitted"
1229 );
1230
1231 entry.api_provider = Some("openai".to_string());
1232 let json = serde_json::to_string(&entry).unwrap();
1233 assert!(json.contains("\"apiProvider\":\"openai\""));
1234 let back: ProviderUsage = serde_json::from_str(&json).unwrap();
1235 assert_eq!(back, entry);
1236 }
1237
1238 #[test]
1239 fn used_count_and_total_count_are_camel_case_and_omitted_when_absent() {
1240 let window = RateWindow {
1241 used_percent: 25.8,
1242 raw_used_percent: None,
1243 resets_at: Some("2026-07-26T14:09:00Z".to_string()),
1244 window_minutes: Some(10080),
1245 used_count: None,
1246 total_count: None,
1247 regeneration: None,
1248 window_kind: None,
1249 breakdown: None,
1250 };
1251 let json = serde_json::to_string(&window).unwrap();
1252 assert!(
1253 !json.contains("usedCount"),
1254 "absent used_count must be omitted"
1255 );
1256 assert!(
1257 !json.contains("totalCount"),
1258 "absent total_count must be omitted"
1259 );
1260
1261 let enriched = RateWindow {
1262 used_count: Some(10336.0),
1263 total_count: Some(40000.0),
1264 ..window
1265 };
1266 let json = serde_json::to_string(&enriched).unwrap();
1267 assert!(json.contains("\"usedCount\":10336.0"));
1268 assert!(json.contains("\"totalCount\":40000.0"));
1269 let back: RateWindow = serde_json::from_str(&json).unwrap();
1270 assert_eq!(back, enriched);
1271 }
1272
1273 /// The field is additive: a producer that does not set it must serialize
1274 /// exactly as before, or adding it changes every existing entry on the wire.
1275 #[test]
1276 fn an_entry_without_a_class_serializes_as_it_did_before_the_field_existed() {
1277 let entry = ProviderUsage::degraded("codex", "no session: nothing configured");
1278 let json = serde_json::to_string(&entry).unwrap();
1279
1280 assert!(!json.contains("errorClass"), "absent class must be omitted");
1281 // Not vacuous: the entry really is a degraded one carrying its message,
1282 // so this cannot pass by serializing something empty.
1283 assert!(json.contains("\"error\":\"no session: nothing configured\""));
1284
1285 let back: ProviderUsage = serde_json::from_str(&json).unwrap();
1286 assert_eq!(back, entry);
1287 assert_eq!(back.error_class, None);
1288 }
1289
1290 #[test]
1291 fn a_class_round_trips_under_its_camel_case_wire_name() {
1292 let entry = ProviderUsage::degraded_with_class(
1293 "gemini",
1294 "credential unusable: gemini creds have no refresh_token",
1295 "credential_unusable",
1296 );
1297 let json = serde_json::to_string(&entry).unwrap();
1298
1299 assert!(json.contains("\"errorClass\":\"credential_unusable\""));
1300 let back: ProviderUsage = serde_json::from_str(&json).unwrap();
1301 assert_eq!(back, entry);
1302 }
1303
1304 /// The classes are open by design, so a consumer built today must survive a
1305 /// producer that ships a class it has never heard of. Modelling the field as
1306 /// a `String` is what buys that: an enum would make this a parse failure,
1307 /// and on an observability surface a parse failure means the entry vanishes
1308 /// at the moment its state changed.
1309 #[test]
1310 fn an_unknown_class_decodes_rather_than_failing() {
1311 let json = r#"{"provider":"someprovider","error":"something new","errorClass":"a_class_from_the_future"}"#;
1312
1313 let entry: ProviderUsage =
1314 serde_json::from_str(json).expect("an unrecognised class must not fail to decode");
1315
1316 assert_eq!(
1317 entry.error_class.as_deref(),
1318 Some("a_class_from_the_future")
1319 );
1320 // The rest of the entry survives intact, so a consumer can still render
1321 // it as degraded-with-unknown-reason rather than dropping it.
1322 assert_eq!(entry.provider, "someprovider");
1323 assert_eq!(entry.error.as_deref(), Some("something new"));
1324 }
1325
1326 /// An entry with no pools serializes exactly as it did before pools existed.
1327 ///
1328 /// Consumers pin these payloads, so an additive field that appears as `null`
1329 /// on every existing entry is not additive in practice. The check is on the
1330 /// rendered text rather than on the field, because that is what a consumer
1331 /// parses.
1332 #[test]
1333 fn an_entry_without_pools_does_not_mention_them() {
1334 let entry = ProviderUsage::healthy("codex", None, "oauth", Usage::default());
1335 let json = serde_json::to_string(&entry).unwrap();
1336 assert!(!json.contains("spend"), "unexpected spend key: {json}");
1337 }
1338
1339 /// Pools survive a round trip, including the two fields a consumer must read
1340 /// before acting on an amount.
1341 ///
1342 /// `basis` and `funding` are what separate "you have 10 granted credits
1343 /// left" from "you were granted 10 credits and we cannot tell how many
1344 /// remain". A consumer that loses either one is left with a number it cannot
1345 /// safely spend against.
1346 #[test]
1347 fn pools_round_trip_with_their_basis_and_funding() {
1348 let pool = Pool {
1349 id: "granted_balance".to_string(),
1350 label: "Granted".to_string(),
1351 funding: PoolFunding::Granted,
1352 remaining: Some(Amount {
1353 minor: 1050,
1354 exponent: 2,
1355 unit: "CNY".to_string(),
1356 }),
1357 total: None,
1358 basis: PoolBasis::Reported,
1359 spendable: Some(true),
1360 resets_at: None,
1361 };
1362 let mut entry = ProviderUsage::healthy("deepseek", None, "api", Usage::default());
1363 entry.spend = Some(vec![pool.clone()]);
1364
1365 let json = serde_json::to_string(&entry).unwrap();
1366 let back: ProviderUsage = serde_json::from_str(&json).unwrap();
1367 assert_eq!(back.spend, Some(vec![pool]));
1368
1369 // Rendered as the wire spells them, since consumers key on these.
1370 assert!(json.contains(r#""funding":"granted""#), "{json}");
1371 assert!(json.contains(r#""basis":"reported""#), "{json}");
1372 // 10.50 CNY is carried as minor units, never as a float.
1373 assert!(json.contains(r#""minor":1050"#), "{json}");
1374 assert!(
1375 !json.contains("10.5"),
1376 "an amount was rendered as a decimal: {json}"
1377 );
1378 }
1379
1380 /// A stated reset survives a round trip under its wire name, and an absent
1381 /// one is not rendered at all.
1382 #[test]
1383 fn a_pool_reset_round_trips_and_is_omitted_when_absent() {
1384 let pool = Pool {
1385 id: "individual_limit".to_string(),
1386 label: "Credit limit".to_string(),
1387 funding: PoolFunding::Unknown,
1388 remaining: None,
1389 total: None,
1390 basis: PoolBasis::Unstated,
1391 spendable: None,
1392 resets_at: Some("2026-10-01T00:00:00Z".to_string()),
1393 };
1394 let json = serde_json::to_string(&pool).unwrap();
1395 assert!(
1396 json.contains(r#""resetsAt":"2026-10-01T00:00:00Z""#),
1397 "{json}"
1398 );
1399 assert_eq!(serde_json::from_str::<Pool>(&json).unwrap(), pool);
1400
1401 let unstated = Pool {
1402 resets_at: None,
1403 ..pool
1404 };
1405 let json = serde_json::to_string(&unstated).unwrap();
1406 assert!(!json.contains("resetsAt"), "{json}");
1407 }
1408
1409 /// A pool written before `resetsAt` existed still decodes, to `None`.
1410 ///
1411 /// The direction that bites: a producer on an older crate, or a stored
1412 /// payload, has no such key. A required field would fail every such pool,
1413 /// and the whole entry with it, rate windows included. serde already decodes
1414 /// a missing `Option` as `None` (dropping `default` alone leaves this green,
1415 /// measured), so what this pins is that the field stays optional.
1416 #[test]
1417 fn a_pool_without_a_reset_key_decodes_to_none() {
1418 let json = r#"{ "id": "credits", "label": "Credits", "funding": "unknown", "basis": "reported",
1419 "remaining": { "minor": 2402, "exponent": 2, "unit": "credit" } }"#;
1420 let pool: Pool = serde_json::from_str(json).unwrap();
1421 assert_eq!(pool.resets_at, None);
1422 }
1423
1424 /// An unrecognised funding kind must not take the entry down with it.
1425 ///
1426 /// This payload crosses a repository boundary: one project produces it,
1427 /// others consume it, and their versions move independently. A closed enum
1428 /// makes the first new funding kind fail deserialization of the WHOLE
1429 /// `ProviderUsage` entry rather than one field, so an account's rate windows
1430 /// would vanish because of a credit pool the consumer had never heard of --
1431 /// and a vanished entry reads as the provider being unavailable.
1432 ///
1433 /// Asserted on a mixed entry rather than on the enum alone, because the
1434 /// blast radius is the point: the usage figure below is what a router acts
1435 /// on, and it is downstream of the pool that failed.
1436 #[test]
1437 fn an_unknown_funding_kind_does_not_discard_the_entry() {
1438 let json = r#"{
1439 "provider": "minimax",
1440 "usage": { "primary": { "usedPercent": 42.0 } },
1441 "spend": [
1442 { "id": "a", "label": "A", "funding": "granted", "basis": "reported" },
1443 { "id": "b", "label": "B", "funding": "crypto_grant", "basis": "reported" }
1444 ]
1445 }"#;
1446
1447 let entry: ProviderUsage = serde_json::from_str(json).expect("entry must survive");
1448 let pools = entry.spend.expect("pools present");
1449 assert_eq!(pools.len(), 2, "no pool may be dropped");
1450 assert_eq!(pools[0].funding, PoolFunding::Granted);
1451 // The unrecognised kind lands on Unknown, which is the correct reading:
1452 // a funding this consumer cannot name is one it must not spend from.
1453 assert_eq!(pools[1].funding, PoolFunding::Unknown);
1454 // And the part a router acts on survived.
1455 assert_eq!(
1456 entry.usage.and_then(|u| u.primary).map(|w| w.used_percent),
1457 Some(42.0)
1458 );
1459 }
1460
1461 /// An unrecognised basis reads as unstated, never as exact.
1462 ///
1463 /// The two poles are not symmetrical. Treating an exact remainder as a
1464 /// ceiling under-spends and costs nothing; treating a ceiling as exact
1465 /// spends money that may not be there. So the fallback folds to the
1466 /// conservative side, and does so under its own name rather than claiming
1467 /// the number was derived -- which would assert a fact about a computation
1468 /// the consumer knows nothing about.
1469 #[test]
1470 fn an_unknown_basis_is_unstated_rather_than_exact() {
1471 let json = r#"{ "id": "a", "label": "A", "funding": "granted",
1472 "basis": "sampled_hourly" }"#;
1473 let pool: Pool = serde_json::from_str(json).expect("pool must survive");
1474 assert_eq!(pool.basis, PoolBasis::Unstated);
1475 assert_ne!(
1476 pool.basis,
1477 PoolBasis::Reported,
1478 "an unknown basis must never read as an exact remainder"
1479 );
1480 }
1481
1482 /// A healthy entry must never carry a class: the field's presence is itself
1483 /// a signal, and a class on a working provider would be a contradiction a
1484 /// consumer has to resolve.
1485 #[test]
1486 fn a_healthy_entry_carries_no_class() {
1487 let entry = ProviderUsage::healthy("codex", None, "oauth", Usage::default());
1488 assert_eq!(entry.error_class, None);
1489 assert!(!serde_json::to_string(&entry)
1490 .unwrap()
1491 .contains("errorClass"));
1492 }
1493
1494 fn weekly(breakdown: Option<UsageBreakdown>) -> RateWindow {
1495 RateWindow {
1496 used_percent: 85.0,
1497 raw_used_percent: None,
1498 resets_at: Some("2026-09-30T14:00:00Z".to_string()),
1499 window_minutes: Some(10_080),
1500 used_count: None,
1501 total_count: None,
1502 regeneration: None,
1503 window_kind: None,
1504 breakdown,
1505 }
1506 }
1507
1508 /// `windowKind` is additive: a window that names no period serializes with no
1509 /// key, so every existing entry is byte-for-byte unchanged.
1510 #[test]
1511 fn a_window_naming_no_period_omits_the_kind_key() {
1512 let json = serde_json::to_string(&weekly(None)).unwrap();
1513 assert!(!json.contains("windowKind"), "{json}");
1514 }
1515
1516 /// A window written before `windowKind` existed still decodes, to `None`.
1517 #[test]
1518 fn a_window_from_before_the_kind_decodes_without_one() {
1519 let json =
1520 r#"{"usedPercent":85.0,"resetsAt":"2026-09-30T14:00:00Z","windowMinutes":10080}"#;
1521 let window: RateWindow = serde_json::from_str(json).unwrap();
1522 assert_eq!(window.window_kind, None);
1523 }
1524
1525 /// The case the field exists for: a monthly window with no stated length
1526 /// carries its kind under the camelCase key and round-trips.
1527 #[test]
1528 fn a_monthly_window_with_no_length_carries_its_kind() {
1529 let window = RateWindow {
1530 window_minutes: None,
1531 window_kind: Some(window_kind::MONTHLY.to_string()),
1532 ..weekly(None)
1533 };
1534 let json = serde_json::to_string(&window).unwrap();
1535 assert!(json.contains(r#""windowKind":"monthly""#), "{json}");
1536 assert!(!json.contains("windowMinutes"), "{json}");
1537 let back: RateWindow = serde_json::from_str(&json).unwrap();
1538 assert_eq!(back, window);
1539 }
1540
1541 /// A kind no consumer has seen arrives as itself rather than failing the
1542 /// decode: the field is an open string, and an enum here would turn one new
1543 /// period into a response nobody can read.
1544 #[test]
1545 fn an_unknown_kind_decodes_as_itself() {
1546 let json = r#"{"usedPercent":5.0,"windowKind":"fortnightly"}"#;
1547 let window: RateWindow = serde_json::from_str(json).unwrap();
1548 assert_eq!(window.window_kind.as_deref(), Some("fortnightly"));
1549 }
1550
1551 /// The vocabulary is pinned, so renaming a value (which every consumer
1552 /// matches as a string) fails here instead of silently on the wire.
1553 #[test]
1554 fn the_window_kind_vocabulary_is_pinned() {
1555 assert_eq!(
1556 [
1557 window_kind::HOURLY,
1558 window_kind::FIVE_HOUR,
1559 window_kind::DAILY,
1560 window_kind::WEEKLY,
1561 window_kind::MONTHLY,
1562 ],
1563 ["hourly", "five_hour", "daily", "weekly", "monthly"]
1564 );
1565 }
1566
1567 /// The field is additive: a window without a split serializes exactly as
1568 /// before, with no `breakdown` key, so every existing entry is unchanged.
1569 #[test]
1570 fn a_window_without_a_breakdown_omits_the_key() {
1571 let json = serde_json::to_string(&weekly(None)).unwrap();
1572 assert!(!json.contains("breakdown"), "{json}");
1573 }
1574
1575 /// A window written before `breakdown` existed still decodes, to `None`.
1576 #[test]
1577 fn a_window_from_before_the_field_decodes_without_one() {
1578 let json =
1579 r#"{"usedPercent":85.0,"resetsAt":"2026-09-30T14:00:00Z","windowMinutes":10080}"#;
1580 let window: RateWindow = serde_json::from_str(json).unwrap();
1581 assert_eq!(window.breakdown, None);
1582 }
1583
1584 /// The split round-trips with the upstream's keys verbatim, including one no
1585 /// consumer has seen, and a row with no figure stays without one rather than
1586 /// becoming zero.
1587 #[test]
1588 fn a_breakdown_round_trips_keys_verbatim_and_keeps_a_missing_share_absent() {
1589 let breakdown = UsageBreakdown {
1590 as_of: Some("2026-09-27T08:37:37Z".to_string()),
1591 window_started_at: Some("2026-09-23T14:00:00Z".to_string()),
1592 rows: vec![
1593 BreakdownRow {
1594 key: "claude_code".to_string(),
1595 share_percent: Some(100.0),
1596 },
1597 BreakdownRow {
1598 key: "chat".to_string(),
1599 share_percent: Some(0.0),
1600 },
1601 BreakdownRow {
1602 key: "a_surface_from_the_future".to_string(),
1603 share_percent: None,
1604 },
1605 ],
1606 };
1607 let window = weekly(Some(breakdown));
1608 let json = serde_json::to_string(&window).unwrap();
1609 assert!(
1610 json.contains(r#""breakdown":{"asOf":"2026-09-27T08:37:37Z","windowStartedAt":"2026-09-23T14:00:00Z","rows":[{"key":"claude_code","sharePercent":100.0},{"key":"chat","sharePercent":0.0},{"key":"a_surface_from_the_future"}]}"#),
1611 "{json}"
1612 );
1613 let back: RateWindow = serde_json::from_str(&json).unwrap();
1614 assert_eq!(back, window);
1615 assert_eq!(back.breakdown.unwrap().rows[2].share_percent, None);
1616 }
1617}