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