Skip to content
1,101 linesCodeBlameRaw
1//! Keeps every price current with what g1t actually pays.
2//!
3//! g1t passes its own costs through, so a price is only right while the
4//! cost under it is. Two jobs keep them right, on the billing service's
5//! cron:
6//!
7//! - **Settling runs** (every 15 minutes). A model run is charged when it
8//! finishes at what the sandbox reported. Each of g1t's hosted runs goes
9//! through its AI Gateway, which prices every request at the provider's
10//! current rates and logs it with the run's session. Settling sums those
11//! logs and corrects the charge to the gateway's figure, with a
12//! correction on the statement. A run whose sandbox died before
13//! reporting is charged here instead of never.
14//! - **Checking costs** (daily). What Cloudflare billed g1t's account, from
15//! its usage API, is measured against how much was used: Containers
16//! against the seconds containers ran, Workers for Platforms per request
17//! and per CPU millisecond. When a measured cost moves, the price book
18//! moves with it, since each price is its cost plus a set markup, and
19//! the change is recorded where anyone can see it. A measurement goes
20//! through `pricing` as a proposal: a small move is applied on its own (a
21//! rise only after customers have had notice), a large or suspect one
22//! waits for staff in sudo, so one odd day of data cannot reprice
23//! everything.
24
25use g1t_contracts::billing::{EntryKind, MICROS_PER_DOLLAR, Price, PriceBook, PriceChange};
26
27use g1t_contracts::time::rfc3339;
28use g1t_kit::now_ms;
29use serde::Deserialize;
30use serde_json::{Value, json};
31use worker::{Env, Fetch, Headers, Method, Request, RequestInit, Result};
32
33use crate::{Billing, RunRow};
34
35/// The cron that also checks costs against Cloudflare's bill.
36pub(crate) const DAILY: &str = "17 4 * * *";
37
38/// A run is settled once its logs have had time to land.
39const SETTLE_AFTER_MS: u64 = 5 * 60 * 1000;
40/// A run with no gateway logs after this is left as reported.
41const GIVE_UP_AFTER_MS: u64 = 3 * 60 * 60 * 1000;
42/// A run never finished after this died without reporting.
43const ABANDONED_AFTER_MS: u64 = 3 * 60 * 60 * 1000;
44
45/// Where the keeper reads what g1t pays.
46pub(crate) struct Keeper {
47 /// `CLOUDFLARE_USAGE_TOKEN`: Billing, Account Analytics and AI Gateway,
48 /// read only.
49 token: Option<String>,
50 /// What reads the bill for `costs`: `CLOUDFLARE_BILLING_TOKEN`
51 /// (Account: Billing Read and Account Analytics Read), or the usage
52 /// token, which has both.
53 billing_token: Option<String>,
54 account: String,
55 gateway: String,
56}
57
58impl Keeper {
59 pub(crate) fn from_env(env: &Env) -> Self {
60 let var = |name: &str| env.var(name).map(|v| v.to_string()).unwrap_or_default();
61 let secret = |name: &str| env.secret(name).ok().map(|v| v.to_string()).filter(|v| !v.is_empty());
62 let token = secret("CLOUDFLARE_USAGE_TOKEN");
63 Keeper {
64 billing_token: secret("CLOUDFLARE_BILLING_TOKEN").or_else(|| token.clone()),
65 token,
66 account: var("CLOUDFLARE_ACCOUNT_ID"),
67 gateway: var("AI_GATEWAY_ID"),
68 }
69 }
70
71 async fn send(&self, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
72 let Some(token) = &self.token else {
73 return Err(worker::Error::RustError("no CLOUDFLARE_USAGE_TOKEN".into()));
74 };
75 send_with(token, method, url, body).await
76 }
77
78 /// Whether Cloudflare's bill can be read.
79 pub(crate) fn can_read_bill(&self) -> bool {
80 self.billing_token.is_some() && !self.account.is_empty()
81 }
82
83 fn billing_token(&self) -> Result<&str> {
84 self.billing_token
85 .as_deref()
86 .ok_or_else(|| worker::Error::RustError("no CLOUDFLARE_BILLING_TOKEN or CLOUDFLARE_USAGE_TOKEN".into()))
87 }
88
89 /// Billable usage from `from` to `to` (dates), every page of it, as one
90 /// answer (`result` holds all the rows), and how many pages it took.
91 /// An answer that says it failed is returned as it is.
92 pub(crate) async fn billable_usage_pages(&self, from: &str, to: &str) -> Result<(Value, u32)> {
93 usage_pages(self.billing_token()?, &self.api(&format!("/billable-usage?from={from}&to={to}"))).await
94 }
95
96 /// The account's subscriptions (Workers Paid, add-ons), as Cloudflare
97 /// answers them. Needs Account: Billing Read.
98 pub(crate) async fn subscriptions_body(&self) -> Result<Value> {
99 send_with(self.billing_token()?, Method::Get, &self.api("/subscriptions"), None).await
100 }
101
102 /// A GraphQL Analytics query, as Cloudflare answers it, errors and all.
103 pub(crate) async fn graphql(&self, body: Value) -> Result<Value> {
104 send_with(self.billing_token()?, Method::Post, "https://api.cloudflare.com/client/v4/graphql", Some(body)).await
105 }
106
107 pub(crate) fn account(&self) -> &str {
108 &self.account
109 }
110
111 fn api(&self, path: &str) -> String {
112 format!("https://api.cloudflare.com/client/v4/accounts/{}{path}", self.account)
113 }
114
115 /// AI Gateway's id, empty when there is none.
116 pub(crate) fn gateway(&self) -> &str {
117 &self.gateway
118 }
119
120 /// A GraphQL query over AI Gateway's analytics: with the keeper's token
121 /// (AI Gateway Read) first, and on failure with the bill's. A token
122 /// without Account Analytics Read gets an error ("caller does not hold
123 /// any of the required permissions for this dataset"); when the answer
124 /// has no rows, `gateway_visible` tells a token that cannot see the
125 /// gateway from a gateway nothing went through.
126 pub(crate) async fn gateway_graphql(&self, body: Value) -> Result<Value> {
127 let Some(token) = &self.token else {
128 return self.graphql(body).await;
129 };
130 match send_with(token, Method::Post, "https://api.cloudflare.com/client/v4/graphql", Some(body.clone())).await {
131 Ok(answer) => Ok(answer),
132 Err(error) => match &self.billing_token {
133 Some(billing) if billing != token => self.graphql(body).await,
134 _ => Err(error),
135 },
136 }
137 }
138
139 /// Whether the token AI Gateway's analytics are read with can see the
140 /// gateway: the REST API answers 403 for a token without AI Gateway
141 /// Read and 404 for a gateway id that is not there. None when the
142 /// answer says neither (Cloudflare down, no token).
143 pub(crate) async fn gateway_visible(&self) -> Option<bool> {
144 let token = self.token.as_deref().or(self.billing_token.as_deref())?;
145 match send_with(token, Method::Get, &self.api(&format!("/ai-gateway/gateways/{}", self.gateway)), None).await {
146 Ok(_) => Some(true),
147 Err(error) => refused(&error.to_string()).then_some(false),
148 }
149 }
150
151 /// What AI Gateway priced a session's requests at, and how many there
152 /// were, with the requests it had no price for.
153 async fn session_cost(&self, session: &str) -> Result<SessionCost> {
154 let mut total = SessionCost { complete: true, ..SessionCost::default() };
155 for page in 1..=MAX_LOG_PAGES {
156 // The filter goes as URL-encoded JSON; the bracket form is
157 // ignored, and would sum every log there is. Session ids are
158 // [a-z0-9_], which need no escaping inside it.
159 let filter = format!(
160 "%5B%7B%22key%22%3A%22metadata.value%22%2C%22operator%22%3A%22eq%22%2C%22value%22%3A%5B%22{session}%22%5D%7D%5D"
161 );
162 let url = self.api(&format!(
163 "/ai-gateway/gateways/{}/logs?per_page=50&page={page}&filters={filter}",
164 self.gateway
165 ));
166 let body = self.send(Method::Get, &url, None).await?;
167 let logs = body["result"].as_array().cloned().unwrap_or_default();
168 for log in &logs {
169 total.add(log);
170 }
171 if logs.len() < 50 {
172 return Ok(total);
173 }
174 }
175 // More logs than were read: what was read is less than the run.
176 total.complete = false;
177 Ok(total)
178 }
179
180 /// The account's billable usage, one row per service per day, as
181 /// Cloudflare reports it.
182 async fn billable_usage(&self, from: &str, to: &str) -> Result<Vec<UsageRow>> {
183 let Some(token) = &self.token else {
184 return Err(worker::Error::RustError("no CLOUDFLARE_USAGE_TOKEN".into()));
185 };
186 let (body, _) = usage_pages(token, &self.api(&format!("/billable-usage?from={from}&to={to}"))).await?;
187 let rows = body["result"].as_array().cloned().unwrap_or_default();
188 Ok(rows.iter().filter_map(UsageRow::from_value).collect())
189 }
190
191 /// What g1t's containers used from `since` to `until` (dates), as
192 /// Cloudflare bills it: memory in byte-seconds, and CPU seconds.
193 async fn container_usage(&self, since: &str, until: &str) -> Result<ContainerUsage> {
194 let query = "query ($account: String!, $since: Date!, $until: Date!) {
195 viewer { accounts(filter: { accountTag: $account }) {
196 containersUsageAdaptiveGroups(limit: 1000, filter: { date_geq: $since, date_leq: $until }) {
197 sum { cpuTimeSec allocatedMemory }
198 }
199 } }
200 }";
201 let body = self
202 .send(
203 Method::Post,
204 "https://api.cloudflare.com/client/v4/graphql",
205 Some(json!({ "query": query, "variables": { "account": self.account, "since": since, "until": until } })),
206 )
207 .await?;
208 let groups = body["data"]["viewer"]["accounts"][0]["containersUsageAdaptiveGroups"]
209 .as_array()
210 .cloned()
211 .unwrap_or_default();
212 Ok(groups.iter().fold(ContainerUsage::default(), |total, g| ContainerUsage {
213 cpu_seconds: total.cpu_seconds + g["sum"]["cpuTimeSec"].as_f64().unwrap_or(0.0),
214 memory_byte_seconds: total.memory_byte_seconds + g["sum"]["allocatedMemory"].as_f64().unwrap_or(0.0),
215 }))
216 }
217}
218
219/// Whether an error from `send_with` is Cloudflare saying no to the token
220/// (401, 403) or that there is no such thing for it (404), rather than
221/// failing.
222pub(crate) fn refused(error: &str) -> bool {
223 ["Cloudflare answered 401", "Cloudflare answered 403", "Cloudflare answered 404"].iter().any(|s| error.contains(s))
224}
225
226/// A request to Cloudflare's API with a bearer token; anything but 200 is
227/// an error with what Cloudflare said.
228/// The most pages of billable usage read in one go: far more than a few
229/// months of g1t's meters.
230const MAX_USAGE_PAGES: u32 = 50;
231
232/// Every page of a billable-usage answer, its rows together. Before
233/// 2026-10-09 only the first page was read.
234async fn usage_pages(token: &str, url: &str) -> Result<(Value, u32)> {
235 let mut rows: Vec<Value> = Vec::new();
236 let mut pages = 0;
237 let mut next = url.to_owned();
238 loop {
239 let body = send_with(token, Method::Get, &next, None).await?;
240 if body["success"] == Value::Bool(false) {
241 return Ok((body, pages + 1));
242 }
243 pages += 1;
244 rows.extend(body["result"].as_array().cloned().unwrap_or_default());
245 match crate::costs::next_page(&body, pages).filter(|_| pages < MAX_USAGE_PAGES) {
246 Some(query) => next = format!("{url}&{query}"),
247 None => break,
248 }
249 }
250 Ok((json!({ "success": true, "result": rows }), pages))
251}
252
253async fn send_with(token: &str, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
254 let headers = Headers::new();
255 headers.set("authorization", &format!("Bearer {token}"))?;
256 headers.set("content-type", "application/json")?;
257 let mut init = RequestInit::new();
258 init.with_method(method).with_headers(headers);
259 if let Some(body) = body {
260 init.with_body(Some(body.to_string().into()));
261 }
262 let mut response = Fetch::Request(Request::new_with_init(url, &init)?).send().await?;
263 let status = response.status_code();
264 let value: Value = response.json().await.unwrap_or(Value::Null);
265 if status != 200 {
266 return Err(worker::Error::RustError(format!("Cloudflare answered {status}: {value}")));
267 }
268 Ok(value)
269}
270
271#[derive(Debug, Default, Clone, Copy)]
272pub(crate) struct ContainerUsage {
273 cpu_seconds: f64,
274 memory_byte_seconds: f64,
275}
276
277/// g1t's sandboxes: Containers' standard-1, half a vCPU, 4 GiB, 8 GB disk.
278const SANDBOX_GIB: f64 = 4.0;
279const SANDBOX_DISK_GB: f64 = 8.0;
280const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
281/// The Durable Object behind each container is billed for as long as the
282/// container runs, at 128 MB.
283const SANDBOX_DO_GB: f64 = 0.125;
284
285/// Cloudflare's published Containers rates, in dollars, used for any rate
286/// the bill does not show yet (while usage is inside the included amount).
287const LIST_MEMORY_GIB_SECOND: f64 = 0.000_002_5;
288const LIST_DISK_GB_SECOND: f64 = 0.000_000_07;
289const LIST_VCPU_SECOND: f64 = 0.000_02;
290/// Durable Objects duration: $12.50 per million GB-seconds.
291const LIST_DO_GB_SECOND: f64 = 0.000_012_5;
292
293/// What one second of a sandbox costs whatever it does, in millionths of a
294/// dollar: its memory and disk, and the Durable Object behind it, for the
295/// whole second. CPU is billed only while busy, on top.
296pub(crate) fn sandbox_base_micros(memory: f64, disk: f64, durable_object: f64) -> f64 {
297 (SANDBOX_GIB * memory + SANDBOX_DISK_GB * disk + SANDBOX_DO_GB * durable_object) * MICROS_PER_DOLLAR as f64
298}
299
300/// What one second of a sandbox costs on average, in millionths of a
301/// dollar: its base, and the CPU sandboxes actually use per second of
302/// running. Runs that report their own CPU are priced on it instead (see
303/// `run_cost`).
304pub(crate) fn sandbox_second_micros(usage: ContainerUsage, memory: f64, disk: f64, vcpu: f64, durable_object: f64) -> Option<f64> {
305 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
306 if instance_seconds < 3600.0 {
307 return None;
308 }
309 let cpu_share = usage.cpu_seconds / instance_seconds;
310 Some(sandbox_base_micros(memory, disk, durable_object) + cpu_share * vcpu * MICROS_PER_DOLLAR as f64)
311}
312
313/// How much more a second of a larger machine's memory and disk (and the
314/// Durable Object behind it) costs than the standard sandbox's, at
315/// Cloudflare's list rates: 1 for the standard machine.
316pub(crate) fn base_scale(memory_gib: f64, disk_gb: f64) -> f64 {
317 let base = |memory: f64, disk: f64| memory * LIST_MEMORY_GIB_SECOND + disk * LIST_DISK_GB_SECOND + SANDBOX_DO_GB * LIST_DO_GB_SECOND;
318 base(memory_gib, disk_gb) / base(SANDBOX_GIB, SANDBOX_DISK_GB)
319}
320
321/// What a run that reported its own CPU cost g1t: its base for every
322/// second, and its vCPU-seconds at the vCPU rate.
323pub(crate) fn run_cost(seconds: i64, cpu_seconds: f64, base_per_second: f64, per_vcpu_second: f64) -> f64 {
324 seconds.max(0) as f64 * base_per_second + cpu_seconds.max(0.0) * per_vcpu_second
325}
326
327/// A unit's marginal rate from the bill: the median, over the days that
328/// were charged, of cost over quantity. None while nothing was charged.
329pub(crate) fn billed_rate(rows: &[&UsageRow]) -> Option<f64> {
330 let mut rates: Vec<f64> = rows
331 .iter()
332 .filter(|r| r.cost > 0.0 && r.quantity > 0.0)
333 .map(|r| r.cost / r.quantity)
334 .collect();
335 if rates.is_empty() {
336 return None;
337 }
338 rates.sort_by(f64::total_cmp);
339 Some(rates[rates.len() / 2])
340}
341
342/// One line of Cloudflare's billable usage.
343#[derive(Debug, Clone)]
344pub(crate) struct UsageRow {
345 period_start: String,
346 period_end: String,
347 service: String,
348 unit: String,
349 quantity: f64,
350 cost: f64,
351}
352
353impl UsageRow {
354 /// Read leniently: the API is new, and its field names are FOCUS's.
355 fn from_value(row: &Value) -> Option<Self> {
356 let text = |keys: &[&str]| keys.iter().find_map(|k| row[*k].as_str()).unwrap_or_default().to_owned();
357 let number = |keys: &[&str]| {
358 keys.iter()
359 .find_map(|k| row[*k].as_f64().or_else(|| row[*k].as_str().and_then(|s| s.parse().ok())))
360 .unwrap_or(0.0)
361 };
362 let service = text(&["ServiceName", "service_name", "service"]);
363 if service.is_empty() {
364 return None;
365 }
366 let family = text(&["ServiceFamilyName", "service_family_name"]);
367 Some(UsageRow {
368 period_start: text(&["ChargePeriodStart", "charge_period_start"]),
369 period_end: text(&["ChargePeriodEnd", "charge_period_end"]),
370 service: if family.is_empty() { service } else { format!("{family} / {service}") },
371 unit: text(&["PricingUnit", "ConsumedUnit", "consumed_unit"]),
372 quantity: number(&["PricingQuantity", "ConsumedQuantity", "pricing_quantity"]),
373 // What g1t pays; list price if nothing was contracted.
374 cost: Some(number(&["ContractedCost", "BilledCost", "contracted_cost"]))
375 .filter(|cost| *cost > 0.0)
376 .unwrap_or_else(|| number(&["ListCost", "list_cost"])),
377 })
378 }
379}
380
381#[derive(Deserialize)]
382struct PriceRow {
383 meter: String,
384 title: String,
385 unit: String,
386 cost_micros: f64,
387 markup_percent: u32,
388 source: String,
389 checked_at: Option<String>,
390 updated_at: String,
391}
392
393#[derive(Deserialize)]
394struct ChangeRow {
395 meter: String,
396 old_cost_micros: f64,
397 new_cost_micros: f64,
398 markup_percent: u32,
399 old_markup_percent: Option<u32>,
400 reason: String,
401 created_at: String,
402}
403
404#[derive(Deserialize)]
405struct Unsettled {
406 id: String,
407 workspace: String,
408 repo: String,
409 number: u32,
410 task: String,
411 model: String,
412 token_hash: String,
413 billed_to: Option<String>,
414 session_id: String,
415 created_at: String,
416 finished_at: Option<String>,
417}
418
419#[derive(Deserialize)]
420struct Charged {
421 cost_micros: Option<i64>,
422 description: String,
423 amount_micros: i64,
424}
425
426/// What a settled run's correction comes to, from the charges at the
427/// reported and the gateway's cost and what the workspace was charged at
428/// first. A charge up is drawn down like any charge; a charge down is
429/// given back only up to what the workspace paid, since what a credit or
430/// a pool paid was never the workspace's money.
431pub(crate) fn correction(reported_charge: i64, gateway_charge: i64, first_charged: i64) -> i64 {
432 let delta = gateway_charge - reported_charge;
433 if delta >= 0 { delta } else { delta.max(-first_charged.max(0)) }
434}
435
436/// A session's logs are read 50 at a time, up to this many pages.
437const MAX_LOG_PAGES: u32 = 40;
438
439/// What AI Gateway's logs say a session cost.
440#[derive(Clone, Debug, Default, PartialEq)]
441pub(crate) struct SessionCost {
442 /// What the gateway priced the requests at, in dollars.
443 pub cost_usd: f64,
444 pub requests: u32,
445 /// Requests that used tokens but that the gateway put no price on: a
446 /// model it has no price for. Their cost is not in `cost_usd`.
447 pub unpriced: u32,
448 /// The models of those, for the statement and the drift.
449 pub unpriced_models: Vec<String>,
450 /// False when there were more logs than were read.
451 pub complete: bool,
452}
453
454impl SessionCost {
455 /// Adds one log, read leniently: `cost` in dollars, `tokens_in` and
456 /// `tokens_out`, `cached` for an answer from the gateway's own cache
457 /// (which costs nothing).
458 pub(crate) fn add(&mut self, log: &Value) {
459 self.requests += 1;
460 let number = |key: &str| log[key].as_f64().or_else(|| log[key].as_str().and_then(|s| s.parse().ok()));
461 let cost = number("cost").filter(|c| c.is_finite() && *c > 0.0);
462 let tokens = number("tokens_in").unwrap_or(0.0) + number("tokens_out").unwrap_or(0.0);
463 let cached = log["cached"].as_bool().unwrap_or(false);
464 match cost {
465 Some(cost) => self.cost_usd += cost,
466 None if tokens > 0.0 && !cached => {
467 self.unpriced += 1;
468 let model = log["model"].as_str().unwrap_or("an unnamed model").to_owned();
469 if !self.unpriced_models.contains(&model) {
470 self.unpriced_models.push(model);
471 }
472 }
473 None => {}
474 }
475 }
476
477 /// Whether the gateway's figure is the whole of what the run cost.
478 pub(crate) fn whole(&self) -> bool {
479 self.complete && self.unpriced == 0
480 }
481}
482
483/// The cost a run is settled at, in millionths: the gateway's figure when
484/// it priced every request; otherwise (a model it has no price for, or
485/// more logs than were read) never less than the sandbox reported, since
486/// the gateway's sum is then short of what the provider bills. With a
487/// reason for the statement and the drift when it is not the gateway's
488/// figure alone.
489pub(crate) fn settled_cost(reported_micros: i64, gateway: &SessionCost) -> (i64, Option<String>) {
490 // Not held to MAX_RUN_COST_USD: the gateway's figure is trusted.
491 let priced = if gateway.cost_usd.is_finite() { (gateway.cost_usd.max(0.0) * MICROS_PER_DOLLAR as f64).ceil() as i64 } else { 0 };
492 if gateway.whole() {
493 return (priced, None);
494 }
495 let mut why = Vec::new();
496 if gateway.unpriced > 0 {
497 why.push(format!(
498 "AI Gateway has no price for {} of its {} requests ({})",
499 gateway.unpriced,
500 gateway.requests,
501 gateway.unpriced_models.join(", ")
502 ));
503 }
504 if !gateway.complete {
505 why.push(format!("more than {} of its requests were logged", gateway.requests));
506 }
507 (priced.max(reported_micros.max(0)), Some(why.join("; ")))
508}
509
510fn ms(timestamp: &str) -> u64 {
511 // RFC 3339 in UTC, as g1t writes them.
512 worker::js_sys::Date::parse(timestamp) as u64
513}
514
515impl Billing {
516 pub(crate) async fn prices(&self) -> Result<PriceBook> {
517 // Three reads at once; the plans are priced from the rows already
518 // read, not one query per meter (status.g1t.sh times this call).
519 let (prices, changes, coming) = futures_util::future::join3(
520 async { self.db.prepare("SELECT * FROM prices ORDER BY rowid").all().await?.results::<PriceRow>() },
521 async {
522 self.db
523 .prepare("SELECT * FROM price_changes ORDER BY created_at DESC LIMIT 20")
524 .all()
525 .await?
526 .results::<ChangeRow>()
527 },
528 // Changes still to come first, so a rise is seen before it is charged.
529 self.coming_changes(),
530 )
531 .await;
532 let (prices, changes, coming) = (prices?, changes?, coming?);
533 let model_markup = prices.iter().find(|row| row.meter == "agent_models").map_or(self.margin_percent, |row| row.markup_percent);
534 let book: std::collections::BTreeMap<&str, f64> = prices
535 .iter()
536 .map(|row| (row.meter.as_str(), Price::price_for(row.cost_micros, row.markup_percent)))
537 .collect();
538 // With the card fee on top of each monthly price, as it is charged.
539 let card_fee = self.card_fee().await?;
540 let plans: Vec<_> = g1t_contracts::billing::Feature::ALL
541 .iter()
542 .map(|feature| {
543 let mut plan = match feature {
544 g1t_contracts::billing::Feature::Security => crate::features::security_plan_at(&book),
545 _ => self.plan_at(&book),
546 };
547 plan.card_fee_cents = crate::tax::fee_for(i64::from(plan.monthly_cents), &card_fee) as u32;
548 plan
549 })
550 .collect();
551 Ok(PriceBook {
552 prices: prices
553 .into_iter()
554 .map(|row| Price {
555 price_micros: Price::price_for(row.cost_micros, row.markup_percent),
556 meter: row.meter,
557 title: row.title,
558 unit: row.unit,
559 cost_micros: row.cost_micros,
560 markup_percent: row.markup_percent,
561 source: row.source,
562 checked_at: row.checked_at,
563 updated_at: row.updated_at,
564 })
565 .collect(),
566 changes: coming
567 .into_iter()
568 .chain(changes.into_iter().map(|row| PriceChange {
569 meter: row.meter,
570 old_cost_micros: row.old_cost_micros,
571 new_cost_micros: row.new_cost_micros,
572 markup_percent: row.markup_percent,
573 old_markup_percent: row.old_markup_percent,
574 reason: row.reason,
575 created_at: row.created_at,
576 effective_at: None,
577 }))
578 .collect(),
579 // The markup on models' provider price: the price book's
580 // `agent_models` (none from 2026-10-08).
581 model_margin_percent: model_markup,
582 plans,
583 free: Some(g1t_contracts::billing::FreeTier {
584 trial_workspace_micros: if self.trials_on { self.plans.trial_workspace_micros } else { 0 },
585 trial_monthly_pool_micros: if self.trials_on { self.plans.trial_monthly_pool_micros } else { 0 },
586 oss_pool_micros: self.plans.oss_pool_micros,
587 oss_repo_micros: self.plans.oss_repo_micros,
588 free_private_storage_bytes: self.plans.free_storage_bytes,
589 audit_retention_days: self.plans.free_audit_days,
590 plan_audit_retention_days: self.plans.audit_days,
591 min_charge_micros: self.plans.min_charge_micros,
592 git_operations_included: self.plans.git_included,
593 paid_start_ceiling_micros: self.plans.paid_start_micros,
594 overage_forgive_cost_micros: self.plans.forgive_cost_micros,
595 }),
596 })
597 }
598
599 /// Whether the costs have never been checked against Cloudflare's bill.
600 pub(crate) async fn never_checked(&self) -> Result<bool> {
601 Ok(self
602 .db
603 .prepare("SELECT meter FROM prices WHERE checked_at IS NOT NULL LIMIT 1")
604 .first::<Value>(None)
605 .await?
606 .is_none())
607 }
608
609 /// A meter's cost and price per unit, from the book.
610 pub(crate) async fn price(&self, meter: &str) -> Result<Option<(f64, f64)>> {
611 #[derive(Deserialize)]
612 struct Row {
613 cost_micros: f64,
614 markup_percent: u32,
615 }
616 Ok(self
617 .db
618 .prepare("SELECT cost_micros, markup_percent FROM prices WHERE meter = ?")
619 .bind(&[meter.into()])?
620 .first::<Row>(None)
621 .await?
622 .map(|row| (row.cost_micros, Price::price_for(row.cost_micros, row.markup_percent))))
623 }
624
625 /// Corrects finished runs to what AI Gateway priced them at, and
626 /// charges runs whose sandbox died before reporting.
627 pub(crate) async fn settle_runs(&self, keeper: &Keeper) -> Result<()> {
628 if keeper.token.is_none() || keeper.gateway.is_empty() {
629 return Ok(());
630 }
631 let now = now_ms();
632 let runs = self
633 .db
634 .prepare(
635 "SELECT id, workspace, repo, number, task, model, token_hash, billed_to, session_id, created_at, finished_at
636 FROM runs
637 WHERE session_id IS NOT NULL AND settled_at IS NULL AND COALESCE(billed_to, 'g1t') = 'g1t'
638 AND ((finished_at IS NOT NULL AND finished_at < ?1) OR created_at < ?2)
639 ORDER BY created_at LIMIT 10",
640 )
641 .bind(&[rfc3339(now - SETTLE_AFTER_MS).into(), rfc3339(now - ABANDONED_AFTER_MS).into()])?
642 .all()
643 .await?
644 .results::<Unsettled>()?;
645 for run in runs {
646 let gateway = match keeper.session_cost(&run.session_id).await {
647 Ok(found) => found,
648 Err(error) => {
649 worker::console_error!("could not read gateway logs for {}: {error}", run.id);
650 continue;
651 }
652 };
653 let since = ms(run.finished_at.as_deref().unwrap_or(&run.created_at));
654 if gateway.requests == 0 && now.saturating_sub(since) < GIVE_UP_AFTER_MS {
655 continue;
656 }
657 self.settle(&run, &gateway).await?;
658 }
659 Ok(())
660 }
661
662 /// Closes runs on a workspace's own model provider: none is on g1t's
663 /// gateway, so nothing is corrected, but tokens the proxy counted after
664 /// the run reported, or for a sandbox that died before reporting, are
665 /// charged their agent rate now. Needs no gateway token.
666 pub(crate) async fn settle_own_runs(&self) -> Result<()> {
667 #[derive(Deserialize)]
668 struct Own {
669 id: String,
670 workspace: String,
671 repo: String,
672 number: u32,
673 task: String,
674 model: String,
675 token_hash: String,
676 billed_to: Option<String>,
677 }
678 let now = now_ms();
679 let runs = self
680 .db
681 .prepare(
682 "SELECT id, workspace, repo, number, task, model, token_hash, billed_to
683 FROM runs
684 WHERE billed_to = 'workspace' AND session_id IS NOT NULL AND settled_at IS NULL
685 AND ((finished_at IS NOT NULL AND finished_at < ?1) OR created_at < ?2)
686 ORDER BY created_at LIMIT 25",
687 )
688 .bind(&[rfc3339(now - SETTLE_AFTER_MS).into(), rfc3339(now - ABANDONED_AFTER_MS).into()])?
689 .all()
690 .await?
691 .results::<Own>()?;
692 for run in runs {
693 let settled_at = rfc3339(now_ms());
694 let claimed = self
695 .db
696 .prepare(
697 "UPDATE runs SET settled_at = ?1, finished_at = COALESCE(finished_at, ?1)
698 WHERE id = ?2 AND settled_at IS NULL RETURNING id",
699 )
700 .bind(&[settled_at.as_str().into(), run.id.as_str().into()])?
701 .first::<Value>(None)
702 .await?;
703 if claimed.is_none() {
704 continue;
705 }
706 let row = RunRow {
707 workspace: run.workspace,
708 repo: run.repo,
709 number: run.number,
710 task: run.task,
711 model: run.model,
712 token_hash: run.token_hash,
713 billed_to: run.billed_to,
714 };
715 self.charge_agent_rate(&run.id, &row, None).await?;
716 }
717 Ok(())
718 }
719
720 async fn settle(&self, run: &Unsettled, gateway: &SessionCost) -> Result<()> {
721 let requests = gateway.requests;
722 let row = RunRow {
723 workspace: run.workspace.clone(),
724 repo: run.repo.clone(),
725 number: run.number,
726 task: run.task.clone(),
727 model: run.model.clone(),
728 token_hash: run.token_hash.clone(),
729 billed_to: run.billed_to.clone(),
730 };
731 let charged = self
732 .db
733 .prepare("SELECT cost_micros, description, amount_micros FROM ledger WHERE reference = ?")
734 .bind(&[run.id.as_str().into()])?
735 .first::<Charged>(None)
736 .await?;
737 let reported = charged.as_ref().and_then(|c| c.cost_micros).unwrap_or(0);
738 // The gateway's figure; never under what the sandbox reported when
739 // the gateway could not price all of it (see `settled_cost`).
740 let (gateway_micros, short) = settled_cost(reported, gateway);
741 let terms = self.terms_of(&run.workspace).await?;
742 // Models at the price book's markup on the provider's price
743 // (`agent_models`), as `finish_run` charges them.
744 let markup = self.model_markup().await?;
745 // A cost's charge on the account's terms, and what a discount gave
746 // below cost plus the markup (counted as given, see `charged`).
747 let charge_for = |micros: i64| {
748 if self.free { (0, 0) } else { terms.discounted(crate::margin_on(micros, markup)) }
749 };
750 let settled_at = rfc3339(now_ms());
751 // Claim it, so two crons never settle it twice.
752 let claimed = self
753 .db
754 .prepare(
755 "UPDATE runs SET settled_at = ?, gateway_cost_micros = ?, gateway_note = ?, finished_at = COALESCE(finished_at, ?)
756 WHERE id = ? AND settled_at IS NULL RETURNING id",
757 )
758 .bind(&[
759 settled_at.as_str().into(),
760 (gateway_micros as f64).into(),
761 short.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
762 settled_at.as_str().into(),
763 run.id.as_str().into(),
764 ])?
765 .first::<Value>(None)
766 .await?;
767 if claimed.is_none() || requests == 0 {
768 return Ok(());
769 }
770 // Tokens counted after the run reported are charged their agent
771 // rate now (ai.rs).
772 self.charge_agent_rate(&run.id, &row, None).await?;
773 if let Some(why) = &short {
774 worker::console_warn!("run {} settled at no less than reported: {why}", run.id);
775 }
776 let short_note = short.as_ref().map_or(String::new(), |why| format!(" ({why}; charged at no less than the sandbox reported)"));
777 let free_note = if self.free { " (free while g1t is being built out)" } else { "" };
778 match charged {
779 // Never reported: charged now, from the gateway's figure.
780 None => {
781 let (charge, discount) = charge_for(gateway_micros);
782 let eligible = crate::credits::eligible_for(Some(g1t_contracts::billing::ComputeKind::Agent), None);
783 let drawn = self.draw(&run.workspace, charge, &settled_at[..7], &eligible).await?;
784 let description = format!(
785 "Work on {}#{}, settled from AI Gateway after the sandbox stopped without reporting{short_note}{free_note}{}",
786 run.repo,
787 run.number,
788 drawn.note()
789 );
790 self.enter(&run.workspace, EntryKind::Usage, -(charge - drawn.total()), &description, &run.id, Some(&row), Some(gateway_micros), None, None)
791 .await?;
792 self.record_drawn(&run.id, &drawn).await?;
793 self.record_discount(&run.id, discount).await?;
794 self.count_spend(&run.workspace, gateway_micros, charge - drawn.total(), &drawn).await;
795 }
796 Some(charged) => {
797 let delta = gateway_micros - reported;
798 if delta == 0 {
799 return Ok(());
800 }
801 let ((was, was_given), (now, now_given)) = (charge_for(reported), charge_for(gateway_micros));
802 let change = correction(was, now, -charged.amount_micros);
803 // What the discount gives moves with the charge.
804 let discount = now_given - was_given;
805 // A charge up is paid for like any other charge.
806 let drawn = if change > 0 {
807 let eligible = crate::credits::eligible_for(Some(g1t_contracts::billing::ComputeKind::Agent), None);
808 self.draw(&run.workspace, change, &settled_at[..7], &eligible).await?
809 } else {
810 crate::credits::Drawn::default()
811 };
812 let description = format!(
813 "Correction to “{}”: AI Gateway priced its {requests} model requests at {}, not {}{short_note}{}",
814 charged.description,
815 crate::features::dollars(gateway_micros),
816 crate::features::dollars(reported),
817 drawn.note(),
818 );
819 let reference = format!("{}/settled", run.id);
820 self.enter(
821 &run.workspace,
822 EntryKind::Usage,
823 -(change - drawn.total()),
824 &description,
825 &reference,
826 Some(&row),
827 Some(delta),
828 None,
829 None,
830 )
831 .await?;
832 self.record_drawn(&reference, &drawn).await?;
833 self.record_discount(&reference, discount).await?;
834 self.count_spend(&run.workspace, delta, change - drawn.total(), &drawn).await;
835 }
836 }
837 Ok(())
838 }
839
840 /// Checks each cost against what Cloudflare billed this month, and
841 /// moves the ones that changed.
842 pub(crate) async fn reconcile(&self, keeper: &Keeper) -> Result<()> {
843 if keeper.token.is_none() {
844 return Ok(());
845 }
846 let now = rfc3339(now_ms());
847 let today = &now[..10];
848 let since = rfc3339(now_ms() - 30 * 24 * 60 * 60 * 1000);
849 let rows = keeper.billable_usage(&since[..10], today).await?;
850 for row in &rows {
851 self.db
852 .prepare(
853 "INSERT INTO cloudflare_usage (period_start, period_end, service, unit, quantity, cost_usd, fetched_at)
854 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
855 ON CONFLICT (period_start, service, unit) DO UPDATE SET
856 period_end = ?2, quantity = ?5, cost_usd = ?6, fetched_at = ?7",
857 )
858 .bind(&[
859 row.period_start.as_str().into(),
860 row.period_end.as_str().into(),
861 row.service.as_str().into(),
862 row.unit.as_str().into(),
863 row.quantity.into(),
864 row.cost.into(),
865 now.as_str().into(),
866 ])?
867 .run()
868 .await?;
869 }
870
871 let named = |words: &[&str]| -> Vec<&UsageRow> {
872 rows.iter()
873 .filter(|r| {
874 let service = r.service.to_lowercase();
875 words.iter().all(|word| service.contains(word))
876 })
877 .collect()
878 };
879
880 // Containers: each resource at what the bill shows it costs, or
881 // the published rate while the included amount still covers it,
882 // over how much CPU g1t's sandboxes really use per second.
883 let memory = billed_rate(&named(&["container memory"]));
884 let disk = billed_rate(&named(&["container disk"]));
885 let vcpu = billed_rate(&named(&["container vcpu"]));
886 let durable_object = billed_rate(&named(&["durable objects", "duration"]));
887 let usage = keeper.container_usage(&since[..10], today).await?;
888 let rates = (
889 memory.unwrap_or(LIST_MEMORY_GIB_SECOND),
890 disk.unwrap_or(LIST_DISK_GB_SECOND),
891 vcpu.unwrap_or(LIST_VCPU_SECOND),
892 durable_object.unwrap_or(LIST_DO_GB_SECOND),
893 );
894 // The parts, for runs that report their own CPU.
895 let parts_reason = "Cloudflare's Containers and Durable Objects rates, as billed or published";
896 self.measure("sandbox_base_second", sandbox_base_micros(rates.0, rates.1, rates.3), parts_reason).await?;
897 self.measure("sandbox_cpu_second", rates.2 * MICROS_PER_DOLLAR as f64, parts_reason).await?;
898 if let Some(per_second) = sandbox_second_micros(usage, rates.0, rates.1, rates.2, rates.3) {
899 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
900 let billed = [("memory", memory), ("disk", disk), ("vCPU", vcpu), ("Durable Object duration", durable_object)]
901 .iter()
902 .filter(|(_, rate)| rate.is_some())
903 .map(|(name, _)| *name)
904 .collect::<Vec<_>>();
905 let reason = format!(
906 "Sandboxes used {:.2} vCPU per second over {:.0} hours of Cloudflare Containers in the last 30 days, with the Durable Object behind each; {}",
907 usage.cpu_seconds / instance_seconds,
908 instance_seconds / 3600.0,
909 if billed.is_empty() {
910 "rates are Cloudflare's published ones".to_owned()
911 } else {
912 format!("{} at what Cloudflare billed", billed.join(", "))
913 },
914 );
915 for meter in ["sandbox_second", "build_second"] {
916 self.measure(meter, per_second, &reason).await?;
917 }
918 }
919 // Apps run as Workers: per million requests and CPU milliseconds,
920 // once the bill shows them charged.
921 // Security scans' CPU follows the same Workers CPU rate.
922 let app_meters: [(&str, &[&str], &str); 3] = [
923 ("app_requests", &["workers", "requests"], "requests"),
924 ("app_cpu", &["workers cpu"], "CPU ms"),
925 ("scan_cpu", &["workers cpu"], "CPU ms"),
926 ];
927 for (meter, words, unit) in app_meters {
928 if let Some(rate) = billed_rate(&named(words)) {
929 let reason = format!("Cloudflare billed Workers {unit} at ${:.2} per million", rate * 1e6);
930 self.measure(meter, rate * 1e6 * MICROS_PER_DOLLAR as f64, &reason).await?;
931 }
932 }
933 self.db
934 .prepare("UPDATE prices SET checked_at = ?")
935 .bind(&[now.as_str().into()])?
936 .run()
937 .await?;
938 Ok(())
939 }
940
941 /// Proposes moving a meter's cost to a measurement (see `pricing`):
942 /// applied on its own when small, after notice when a rise; left for
943 /// staff when large or suspect.
944 async fn measure(&self, meter: &str, measured: f64, reason: &str) -> Result<()> {
945 if let Some(outcome) = self.propose(meter, measured, reason, "keeper").await? {
946 worker::console_log!("{meter}: {outcome}");
947 }
948 Ok(())
949 }
950}
951
952#[cfg(test)]
953mod tests {
954 use super::*;
955
956 #[test]
957 fn a_correction_never_gives_back_what_the_workspace_did_not_pay() {
958 // Up by 2 cents: charged in full (then drawn down like any charge).
959 assert_eq!(correction(100_000, 120_000, 100_000), 20_000);
960 // Down by 2 cents, all of it paid by the workspace: given back.
961 assert_eq!(correction(120_000, 100_000, 120_000), -20_000);
962 // Down, but the open-source pool paid all but a cent: a cent back.
963 assert_eq!(correction(120_000, 100_000, 10_000), -10_000);
964 // Paid entirely by a credit or pool: nothing back.
965 assert_eq!(correction(120_000, 100_000, 0), 0);
966 }
967
968 fn logs(entries: &[Value]) -> SessionCost {
969 let mut total = SessionCost { complete: true, ..SessionCost::default() };
970 for log in entries {
971 total.add(log);
972 }
973 total
974 }
975
976 #[test]
977 fn a_run_is_settled_at_the_gateways_figure_when_it_priced_every_request() {
978 let gateway = logs(&[
979 json!({ "cost": 0.012, "tokens_in": 4000, "tokens_out": 300, "model": "claude-sonnet-5-5" }),
980 json!({ "cost": "0.003", "tokens_in": 900, "tokens_out": 40, "model": "claude-haiku-4-5" }),
981 // Served from the gateway's own cache: no cost, and none owed.
982 json!({ "cost": 0, "tokens_in": 900, "tokens_out": 40, "cached": true }),
983 // An error with no tokens costs nothing either.
984 json!({ "cost": null, "tokens_in": 0, "tokens_out": 0 }),
985 ]);
986 assert!(gateway.whole());
987 assert_eq!(gateway.requests, 4);
988 // Down from what the sandbox said, or up: the gateway's figure.
989 assert_eq!(settled_cost(20_000, &gateway), (15_000, None));
990 assert_eq!(settled_cost(9_000, &gateway), (15_000, None));
991 }
992
993 #[test]
994 fn a_model_the_gateway_cannot_price_is_never_settled_down_to_nothing() {
995 let gateway = logs(&[
996 json!({ "cost": 0.002, "tokens_in": 100, "tokens_out": 10, "model": "claude-haiku-4-5" }),
997 json!({ "cost": 0, "tokens_in": 50_000, "tokens_out": 2_000, "model": "claude-new-1" }),
998 json!({ "tokens_in": 50_000, "tokens_out": 2_000, "model": "claude-new-1" }),
999 ]);
1000 assert!(!gateway.whole());
1001 assert_eq!((gateway.unpriced, gateway.unpriced_models.clone()), (2, vec!["claude-new-1".to_owned()]));
1002 // The sandbox said $0.90: kept, not cut to the gateway's $0.002.
1003 let (cost, why) = settled_cost(900_000, &gateway);
1004 assert_eq!(cost, 900_000);
1005 assert!(why.unwrap().contains("no price for 2 of its 3 requests (claude-new-1)"));
1006 // A sandbox that reported less than the gateway priced: the gateway's.
1007 assert_eq!(settled_cost(1_000, &gateway).0, 2_000);
1008 }
1009
1010 #[test]
1011 fn more_logs_than_were_read_never_settle_a_run_down() {
1012 let mut gateway = logs(&[json!({ "cost": 1.0, "tokens_in": 1, "tokens_out": 1 })]);
1013 gateway.complete = false;
1014 let (cost, why) = settled_cost(3_000_000, &gateway);
1015 assert_eq!(cost, 3_000_000);
1016 assert!(why.unwrap().contains("more than 1 of its requests"));
1017 }
1018
1019 #[test]
1020 fn a_gateway_figure_over_the_report_cap_is_charged_in_full() {
1021 // A sandbox's report is believed up to $100; the gateway's is not capped.
1022 let gateway = logs(&[json!({ "cost": 140.0, "tokens_in": 1, "tokens_out": 1 })]);
1023 assert_eq!(settled_cost(100_000_000, &gateway).0, 140_000_000);
1024 assert_eq!(crate::charge_micros(140.0, 20), 120_000_000);
1025 assert_eq!(crate::margin_on(140_000_000, 20), 168_000_000);
1026 // Exactly cost plus the margin, rounded up, in whole micros (dollars
1027 // as floats can come out a micro high), never under it.
1028 for cost in [0_i64, 1, 7, 999, 123_457, 99_999_999] {
1029 let exact = (cost * 120 + 99) / 100;
1030 assert_eq!(crate::margin_on(cost, 20), exact, "{cost}");
1031 assert!(crate::margin_on(cost, 20) * 100 >= cost * 120, "{cost}");
1032 assert!(crate::charge_micros(cost as f64 / 1e6, 20) >= exact, "{cost}");
1033 }
1034 }
1035
1036 #[test]
1037 fn a_sandbox_second_is_its_memory_and_disk_and_the_cpu_it_uses() {
1038 // An hour of sandboxes that kept a fifth of a vCPU busy.
1039 let usage = ContainerUsage { cpu_seconds: 720.0, memory_byte_seconds: 3600.0 * 4.0 * GIB };
1040 let micros =
1041 sandbox_second_micros(usage, LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_VCPU_SECOND, LIST_DO_GB_SECOND).unwrap();
1042 // 4 x 2.5 + 8 x 0.07 + 0.125 x 12.5 + 0.2 x 20 = 16.1225
1043 assert!((micros - 16.1225).abs() < 1e-9, "{micros}");
1044 // The Durable Object adds about 11% to the second it left out.
1045 assert!((sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND) - 12.1225).abs() < 1e-9);
1046 // Too little use to say anything.
1047 assert!(sandbox_second_micros(ContainerUsage { cpu_seconds: 1.0, memory_byte_seconds: GIB }, 1.0, 1.0, 1.0, 1.0).is_none());
1048 }
1049
1050 #[test]
1051 fn a_run_that_reports_its_cpu_is_priced_on_it() {
1052 let base = sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND);
1053 let vcpu = LIST_VCPU_SECOND * MICROS_PER_DOLLAR as f64;
1054 // A 10-minute cargo build that kept its half vCPU busy throughout.
1055 let heavy = run_cost(600, 300.0, base, vcpu);
1056 assert!((heavy - (600.0 * 12.1225 + 300.0 * 20.0)).abs() < 1e-6);
1057 // The same ten minutes, mostly idle, costs less.
1058 let light = run_cost(600, 30.0, base, vcpu);
1059 assert!(light < heavy);
1060 // The average would have under-priced the heavy one.
1061 let average = 600.0 * (base + 0.195 * vcpu);
1062 assert!(average < heavy && average > light);
1063 assert_eq!(run_cost(0, -1.0, base, vcpu), 0.0);
1064 // A larger machine's base: its memory and disk, not its CPU.
1065 assert!((base_scale(SANDBOX_GIB, SANDBOX_DISK_GB) - 1.0).abs() < 1e-12);
1066 assert!((base_scale(12.0, 20.0) - 2.72).abs() < 0.01, "{}", base_scale(12.0, 20.0));
1067 assert!((base_scale(8.0, 16.0) - 1.87).abs() < 0.01, "{}", base_scale(8.0, 16.0));
1068 }
1069
1070 #[test]
1071 fn a_billed_rate_is_the_median_of_the_charged_days() {
1072 let row = |quantity: f64, cost: f64| UsageRow {
1073 period_start: String::new(),
1074 period_end: String::new(),
1075 service: "Containers / Container Memory".into(),
1076 unit: "Count".into(),
1077 quantity,
1078 cost,
1079 };
1080 let rows = [row(100.0, 0.0), row(100.0, 0.0002), row(100.0, 0.00025), row(100.0, 0.00025)];
1081 assert_eq!(billed_rate(&rows.iter().collect::<Vec<_>>()), Some(0.000_002_5));
1082 assert_eq!(billed_rate(&[&row(5.0, 0.0)]), None);
1083 }
1084
1085 #[test]
1086 fn usage_rows_are_read_by_their_focus_names() {
1087 let row = UsageRow::from_value(&json!({
1088 "ServiceFamilyName": "Containers",
1089 "ServiceName": "Memory",
1090 "PricingUnit": "GiB-seconds",
1091 "PricingQuantity": "1200.5",
1092 "ContractedCost": 0.003,
1093 "ChargePeriodStart": "2026-10-01",
1094 }))
1095 .unwrap();
1096 assert_eq!(row.service, "Containers / Memory");
1097 assert_eq!(row.quantity, 1200.5);
1098 assert_eq!(row.cost, 0.003);
1099 assert!(UsageRow::from_value(&json!({ "nothing": 1 })).is_none());
1100 }
1101}