g1t/services/billing/src/keeper.rs

795 lines34,950 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Prices keep themselves current with what g1t pays1//! 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
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily19//! 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.
Prices keep themselves current with what g1t pays24
25use g1t_contracts::billing::{EntryKind, MICROS_PER_DOLLAR, Price, PriceBook, PriceChange};
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily26
Prices keep themselves current with what g1t pays27use 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, charge_micros};
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>,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily50 /// 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>,
Prices keep themselves current with what g1t pays54 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();
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily61 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");
Prices keep themselves current with what g1t pays63 Keeper {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily64 billing_token: secret("CLOUDFLARE_BILLING_TOKEN").or_else(|| token.clone()),
65 token,
Prices keep themselves current with what g1t pays66 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 };
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily75 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
Prices keep themselves current with what g1t pays92 }
93
Costs: Cloudflare's subscriptions read from Cloudflare each day, the estimate only until then; sudo's costs split into Costs & margin and Bill & pricing94 /// 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
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily100 /// 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
Prices keep themselves current with what g1t pays109 fn api(&self, path: &str) -> String {
110 format!("https://api.cloudflare.com/client/v4/accounts/{}{path}", self.account)
111 }
112
113 /// What AI Gateway priced a session's requests at, in dollars, and how
114 /// many there were.
115 async fn session_cost(&self, session: &str) -> Result<(f64, u32)> {
116 let mut cost = 0.0;
117 let mut count = 0;
118 for page in 1..=40 {
The keeper reads Cloudflare as it really answers119 // The filter goes as URL-encoded JSON; the bracket form is
120 // ignored, and would sum every log there is. Session ids are
121 // [a-z0-9_], which need no escaping inside it.
122 let filter = format!(
123 "%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"
124 );
Prices keep themselves current with what g1t pays125 let url = self.api(&format!(
The keeper reads Cloudflare as it really answers126 "/ai-gateway/gateways/{}/logs?per_page=50&page={page}&filters={filter}",
Prices keep themselves current with what g1t pays127 self.gateway
128 ));
129 let body = self.send(Method::Get, &url, None).await?;
130 let logs = body["result"].as_array().cloned().unwrap_or_default();
131 for log in &logs {
132 cost += log["cost"].as_f64().unwrap_or(0.0);
133 count += 1;
134 }
135 if logs.len() < 50 {
136 break;
137 }
138 }
139 Ok((cost, count))
140 }
141
The keeper reads Cloudflare as it really answers142 /// The account's billable usage, one row per service per day, as
143 /// Cloudflare reports it.
Prices keep themselves current with what g1t pays144 async fn billable_usage(&self, from: &str, to: &str) -> Result<Vec<UsageRow>> {
145 let body = self
The keeper reads Cloudflare as it really answers146 .send(Method::Get, &self.api(&format!("/billable-usage?from={from}&to={to}")), None)
Prices keep themselves current with what g1t pays147 .await?;
148 let rows = body["result"].as_array().cloned().unwrap_or_default();
149 Ok(rows.iter().filter_map(UsageRow::from_value).collect())
150 }
151
The keeper reads Cloudflare as it really answers152 /// What g1t's containers used from `since` to `until` (dates), as
153 /// Cloudflare bills it: memory in byte-seconds, and CPU seconds.
154 async fn container_usage(&self, since: &str, until: &str) -> Result<ContainerUsage> {
155 let query = "query ($account: String!, $since: Date!, $until: Date!) {
Prices keep themselves current with what g1t pays156 viewer { accounts(filter: { accountTag: $account }) {
The keeper reads Cloudflare as it really answers157 containersUsageAdaptiveGroups(limit: 1000, filter: { date_geq: $since, date_leq: $until }) {
158 sum { cpuTimeSec allocatedMemory }
Prices keep themselves current with what g1t pays159 }
160 } }
161 }";
162 let body = self
163 .send(
164 Method::Post,
165 "https://api.cloudflare.com/client/v4/graphql",
166 Some(json!({ "query": query, "variables": { "account": self.account, "since": since, "until": until } })),
167 )
168 .await?;
The keeper reads Cloudflare as it really answers169 let groups = body["data"]["viewer"]["accounts"][0]["containersUsageAdaptiveGroups"]
Prices keep themselves current with what g1t pays170 .as_array()
171 .cloned()
172 .unwrap_or_default();
The keeper reads Cloudflare as it really answers173 Ok(groups.iter().fold(ContainerUsage::default(), |total, g| ContainerUsage {
174 cpu_seconds: total.cpu_seconds + g["sum"]["cpuTimeSec"].as_f64().unwrap_or(0.0),
175 memory_byte_seconds: total.memory_byte_seconds + g["sum"]["allocatedMemory"].as_f64().unwrap_or(0.0),
176 }))
Prices keep themselves current with what g1t pays177 }
178}
179
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily180/// A request to Cloudflare's API with a bearer token; anything but 200 is
181/// an error with what Cloudflare said.
182async fn send_with(token: &str, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
183 let headers = Headers::new();
184 headers.set("authorization", &format!("Bearer {token}"))?;
185 headers.set("content-type", "application/json")?;
186 let mut init = RequestInit::new();
187 init.with_method(method).with_headers(headers);
188 if let Some(body) = body {
189 init.with_body(Some(body.to_string().into()));
190 }
191 let mut response = Fetch::Request(Request::new_with_init(url, &init)?).send().await?;
192 let status = response.status_code();
193 let value: Value = response.json().await.unwrap_or(Value::Null);
194 if status != 200 {
195 return Err(worker::Error::RustError(format!("Cloudflare answered {status}: {value}")));
196 }
197 Ok(value)
198}
199
The keeper reads Cloudflare as it really answers200#[derive(Debug, Default, Clone, Copy)]
201pub(crate) struct ContainerUsage {
202 cpu_seconds: f64,
203 memory_byte_seconds: f64,
204}
205
206/// g1t's sandboxes: Containers' standard-1, half a vCPU, 4 GiB, 8 GB disk.
207const SANDBOX_GIB: f64 = 4.0;
208const SANDBOX_DISK_GB: f64 = 8.0;
209const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look210/// The Durable Object behind each container is billed for as long as the
211/// container runs, at 128 MB.
212const SANDBOX_DO_GB: f64 = 0.125;
The keeper reads Cloudflare as it really answers213
214/// Cloudflare's published Containers rates, in dollars, used for any rate
215/// the bill does not show yet (while usage is inside the included amount).
216const LIST_MEMORY_GIB_SECOND: f64 = 0.000_002_5;
217const LIST_DISK_GB_SECOND: f64 = 0.000_000_07;
218const LIST_VCPU_SECOND: f64 = 0.000_02;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look219/// Durable Objects duration: $12.50 per million GB-seconds.
220const LIST_DO_GB_SECOND: f64 = 0.000_012_5;
The keeper reads Cloudflare as it really answers221
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look222/// What one second of a sandbox costs whatever it does, in millionths of a
223/// dollar: its memory and disk, and the Durable Object behind it, for the
224/// whole second. CPU is billed only while busy, on top.
225pub(crate) fn sandbox_base_micros(memory: f64, disk: f64, durable_object: f64) -> f64 {
226 (SANDBOX_GIB * memory + SANDBOX_DISK_GB * disk + SANDBOX_DO_GB * durable_object) * MICROS_PER_DOLLAR as f64
227}
228
229/// What one second of a sandbox costs on average, in millionths of a
230/// dollar: its base, and the CPU sandboxes actually use per second of
231/// running. Runs that report their own CPU are priced on it instead (see
232/// `run_cost`).
233pub(crate) fn sandbox_second_micros(usage: ContainerUsage, memory: f64, disk: f64, vcpu: f64, durable_object: f64) -> Option<f64> {
The keeper reads Cloudflare as it really answers234 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
235 if instance_seconds < 3600.0 {
236 return None;
237 }
238 let cpu_share = usage.cpu_seconds / instance_seconds;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look239 Some(sandbox_base_micros(memory, disk, durable_object) + cpu_share * vcpu * MICROS_PER_DOLLAR as f64)
240}
241
Fast pages, required checks on the branch, self-hosted runners, honest incidents242/// How much more a second of a larger machine's memory and disk (and the
243/// Durable Object behind it) costs than the standard sandbox's, at
244/// Cloudflare's list rates: 1 for the standard machine.
245pub(crate) fn base_scale(memory_gib: f64, disk_gb: f64) -> f64 {
246 let base = |memory: f64, disk: f64| memory * LIST_MEMORY_GIB_SECOND + disk * LIST_DISK_GB_SECOND + SANDBOX_DO_GB * LIST_DO_GB_SECOND;
247 base(memory_gib, disk_gb) / base(SANDBOX_GIB, SANDBOX_DISK_GB)
248}
249
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look250/// What a run that reported its own CPU cost g1t: its base for every
251/// second, and its vCPU-seconds at the vCPU rate.
252pub(crate) fn run_cost(seconds: i64, cpu_seconds: f64, base_per_second: f64, per_vcpu_second: f64) -> f64 {
253 seconds.max(0) as f64 * base_per_second + cpu_seconds.max(0.0) * per_vcpu_second
The keeper reads Cloudflare as it really answers254}
255
256/// A unit's marginal rate from the bill: the median, over the days that
257/// were charged, of cost over quantity. None while nothing was charged.
258pub(crate) fn billed_rate(rows: &[&UsageRow]) -> Option<f64> {
259 let mut rates: Vec<f64> = rows
260 .iter()
261 .filter(|r| r.cost > 0.0 && r.quantity > 0.0)
262 .map(|r| r.cost / r.quantity)
263 .collect();
264 if rates.is_empty() {
265 return None;
266 }
267 rates.sort_by(f64::total_cmp);
268 Some(rates[rates.len() / 2])
269}
270
Prices keep themselves current with what g1t pays271/// One line of Cloudflare's billable usage.
272#[derive(Debug, Clone)]
273pub(crate) struct UsageRow {
274 period_start: String,
275 period_end: String,
276 service: String,
277 unit: String,
278 quantity: f64,
279 cost: f64,
280}
281
282impl UsageRow {
283 /// Read leniently: the API is new, and its field names are FOCUS's.
284 fn from_value(row: &Value) -> Option<Self> {
285 let text = |keys: &[&str]| keys.iter().find_map(|k| row[*k].as_str()).unwrap_or_default().to_owned();
286 let number = |keys: &[&str]| {
287 keys.iter()
288 .find_map(|k| row[*k].as_f64().or_else(|| row[*k].as_str().and_then(|s| s.parse().ok())))
289 .unwrap_or(0.0)
290 };
291 let service = text(&["ServiceName", "service_name", "service"]);
292 if service.is_empty() {
293 return None;
294 }
295 let family = text(&["ServiceFamilyName", "service_family_name"]);
296 Some(UsageRow {
297 period_start: text(&["ChargePeriodStart", "charge_period_start"]),
298 period_end: text(&["ChargePeriodEnd", "charge_period_end"]),
299 service: if family.is_empty() { service } else { format!("{family} / {service}") },
The keeper reads Cloudflare as it really answers300 unit: text(&["PricingUnit", "ConsumedUnit", "consumed_unit"]),
Prices keep themselves current with what g1t pays301 quantity: number(&["PricingQuantity", "ConsumedQuantity", "pricing_quantity"]),
The keeper reads Cloudflare as it really answers302 // What g1t pays; list price if nothing was contracted.
303 cost: Some(number(&["ContractedCost", "BilledCost", "contracted_cost"]))
304 .filter(|cost| *cost > 0.0)
305 .unwrap_or_else(|| number(&["ListCost", "list_cost"])),
Prices keep themselves current with what g1t pays306 })
307 }
308}
309
310#[derive(Deserialize)]
311struct PriceRow {
312 meter: String,
313 title: String,
314 unit: String,
315 cost_micros: f64,
316 markup_percent: u32,
317 source: String,
318 checked_at: Option<String>,
319 updated_at: String,
320}
321
322#[derive(Deserialize)]
323struct ChangeRow {
324 meter: String,
325 old_cost_micros: f64,
326 new_cost_micros: f64,
327 markup_percent: u32,
Prices are what g1t pays plus 20%, from the first second328 old_markup_percent: Option<u32>,
Prices keep themselves current with what g1t pays329 reason: String,
330 created_at: String,
331}
332
333#[derive(Deserialize)]
334struct Unsettled {
335 id: String,
336 workspace: String,
337 repo: String,
338 number: u32,
339 task: String,
340 model: String,
341 token_hash: String,
342 billed_to: Option<String>,
343 session_id: String,
344 created_at: String,
345 finished_at: Option<String>,
346}
347
348#[derive(Deserialize)]
349struct Charged {
350 cost_micros: Option<i64>,
351 description: String,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put352 amount_micros: i64,
353}
354
355/// What a settled run's correction comes to, from the charges at the
356/// reported and the gateway's cost and what the workspace was charged at
357/// first. A charge up is drawn down like any charge; a charge down is
358/// given back only up to what the workspace paid, since what a credit or
359/// a pool paid was never the workspace's money.
360pub(crate) fn correction(reported_charge: i64, gateway_charge: i64, first_charged: i64) -> i64 {
361 let delta = gateway_charge - reported_charge;
362 if delta >= 0 { delta } else { delta.max(-first_charged.max(0)) }
Prices keep themselves current with what g1t pays363}
364
365fn ms(timestamp: &str) -> u64 {
366 // RFC 3339 in UTC, as g1t writes them.
367 worker::js_sys::Date::parse(timestamp) as u64
368}
369
370impl Billing {
371 pub(crate) async fn prices(&self) -> Result<PriceBook> {
Billing answers every page in a few round trips, not forty: its reads run together, Stripe is asked at most hourly, and the ledger has a time index372 // Three reads at once; the plans are priced from the rows already
373 // read, not one query per meter (status.g1t.sh times this call).
374 let (prices, changes, coming) = futures_util::future::join3(
375 async { self.db.prepare("SELECT * FROM prices ORDER BY rowid").all().await?.results::<PriceRow>() },
376 async {
377 self.db
378 .prepare("SELECT * FROM price_changes ORDER BY created_at DESC LIMIT 20")
379 .all()
380 .await?
381 .results::<ChangeRow>()
382 },
383 // Changes still to come first, so a rise is seen before it is charged.
384 self.coming_changes(),
385 )
386 .await;
387 let (prices, changes, coming) = (prices?, changes?, coming?);
388 let book: std::collections::BTreeMap<&str, f64> = prices
389 .iter()
390 .map(|row| (row.meter.as_str(), Price::price_for(row.cost_micros, row.markup_percent)))
391 .collect();
392 let plans: Vec<_> = g1t_contracts::billing::Feature::ALL.iter().map(|_| self.plan_at(&book)).collect();
Prices keep themselves current with what g1t pays393 Ok(PriceBook {
394 prices: prices
395 .into_iter()
396 .map(|row| Price {
397 price_micros: Price::price_for(row.cost_micros, row.markup_percent),
398 meter: row.meter,
399 title: row.title,
400 unit: row.unit,
401 cost_micros: row.cost_micros,
402 markup_percent: row.markup_percent,
403 source: row.source,
404 checked_at: row.checked_at,
405 updated_at: row.updated_at,
406 })
407 .collect(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily408 changes: coming
Prices keep themselves current with what g1t pays409 .into_iter()
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily410 .chain(changes.into_iter().map(|row| PriceChange {
Prices keep themselves current with what g1t pays411 meter: row.meter,
412 old_cost_micros: row.old_cost_micros,
413 new_cost_micros: row.new_cost_micros,
414 markup_percent: row.markup_percent,
Prices are what g1t pays plus 20%, from the first second415 old_markup_percent: row.old_markup_percent,
Prices keep themselves current with what g1t pays416 reason: row.reason,
417 created_at: row.created_at,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily418 effective_at: None,
419 }))
Prices keep themselves current with what g1t pays420 .collect(),
421 model_margin_percent: self.margin_percent,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily422 plans,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put423 free: Some(g1t_contracts::billing::FreeTier {
424 trial_workspace_micros: if self.trials_on { self.plans.trial_workspace_micros } else { 0 },
425 trial_monthly_pool_micros: if self.trials_on { self.plans.trial_monthly_pool_micros } else { 0 },
426 oss_pool_micros: self.plans.oss_pool_micros,
427 oss_repo_micros: self.plans.oss_repo_micros,
428 free_private_storage_bytes: self.plans.free_storage_bytes,
Audit logs are kept by plan: a week on free, 90 days on the plan, and what staff set for an account in sudo429 audit_retention_days: self.plans.free_audit_days,
430 plan_audit_retention_days: self.plans.audit_days,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put431 min_charge_micros: self.plans.min_charge_micros,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look432 git_operations_included: self.plans.git_included,
433 paid_start_ceiling_micros: self.plans.paid_start_micros,
434 overage_forgive_cost_micros: self.plans.forgive_cost_micros,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put435 }),
Prices keep themselves current with what g1t pays436 })
437 }
438
The keeper reads Cloudflare as it really answers439 /// Whether the costs have never been checked against Cloudflare's bill.
440 pub(crate) async fn never_checked(&self) -> Result<bool> {
441 Ok(self
442 .db
443 .prepare("SELECT meter FROM prices WHERE checked_at IS NOT NULL LIMIT 1")
444 .first::<Value>(None)
445 .await?
446 .is_none())
447 }
448
Prices keep themselves current with what g1t pays449 /// A meter's cost and price per unit, from the book.
450 pub(crate) async fn price(&self, meter: &str) -> Result<Option<(f64, f64)>> {
451 #[derive(Deserialize)]
452 struct Row {
453 cost_micros: f64,
454 markup_percent: u32,
455 }
456 Ok(self
457 .db
458 .prepare("SELECT cost_micros, markup_percent FROM prices WHERE meter = ?")
459 .bind(&[meter.into()])?
460 .first::<Row>(None)
461 .await?
462 .map(|row| (row.cost_micros, Price::price_for(row.cost_micros, row.markup_percent))))
463 }
464
465 /// Corrects finished runs to what AI Gateway priced them at, and
466 /// charges runs whose sandbox died before reporting.
467 pub(crate) async fn settle_runs(&self, keeper: &Keeper) -> Result<()> {
468 if keeper.token.is_none() || keeper.gateway.is_empty() {
469 return Ok(());
470 }
471 let now = now_ms();
472 let runs = self
473 .db
474 .prepare(
475 "SELECT id, workspace, repo, number, task, model, token_hash, billed_to, session_id, created_at, finished_at
476 FROM runs
477 WHERE session_id IS NOT NULL AND settled_at IS NULL
478 AND ((finished_at IS NOT NULL AND finished_at < ?1) OR created_at < ?2)
479 ORDER BY created_at LIMIT 10",
480 )
481 .bind(&[rfc3339(now - SETTLE_AFTER_MS).into(), rfc3339(now - ABANDONED_AFTER_MS).into()])?
482 .all()
483 .await?
484 .results::<Unsettled>()?;
485 for run in runs {
486 let (cost_usd, requests) = match keeper.session_cost(&run.session_id).await {
487 Ok(found) => found,
488 Err(error) => {
489 worker::console_error!("could not read gateway logs for {}: {error}", run.id);
490 continue;
491 }
492 };
493 let since = ms(run.finished_at.as_deref().unwrap_or(&run.created_at));
494 if requests == 0 && now.saturating_sub(since) < GIVE_UP_AFTER_MS {
495 continue;
496 }
497 self.settle(&run, cost_usd, requests).await?;
498 }
499 Ok(())
500 }
501
502 async fn settle(&self, run: &Unsettled, cost_usd: f64, requests: u32) -> Result<()> {
503 let row = RunRow {
504 workspace: run.workspace.clone(),
505 repo: run.repo.clone(),
506 number: run.number,
507 task: run.task.clone(),
508 model: run.model.clone(),
509 token_hash: run.token_hash.clone(),
510 billed_to: run.billed_to.clone(),
511 };
512 let gateway_micros = charge_micros(cost_usd, 0);
513 let charged = self
514 .db
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put515 .prepare("SELECT cost_micros, description, amount_micros FROM ledger WHERE reference = ?")
Prices keep themselves current with what g1t pays516 .bind(&[run.id.as_str().into()])?
517 .first::<Charged>(None)
518 .await?;
Billing accounts, terms and enterprises; g1t is no longer free519 let terms = self.terms_of(&run.workspace).await?;
Prices keep themselves current with what g1t pays520 let charge_for = |micros: i64| {
521 if self.free {
522 0
523 } else {
Billing accounts, terms and enterprises; g1t is no longer free524 terms.apply(charge_micros(micros as f64 / MICROS_PER_DOLLAR as f64, self.margin_percent))
Prices keep themselves current with what g1t pays525 }
526 };
527 let settled_at = rfc3339(now_ms());
528 // Claim it, so two crons never settle it twice.
529 let claimed = self
530 .db
531 .prepare("UPDATE runs SET settled_at = ?, gateway_cost_micros = ?, finished_at = COALESCE(finished_at, ?) WHERE id = ? AND settled_at IS NULL RETURNING id")
532 .bind(&[
533 settled_at.as_str().into(),
534 (gateway_micros as f64).into(),
535 settled_at.as_str().into(),
536 run.id.as_str().into(),
537 ])?
538 .first::<Value>(None)
539 .await?;
540 if claimed.is_none() || requests == 0 {
541 return Ok(());
542 }
543 let free_note = if self.free { " (free while g1t is being built out)" } else { "" };
544 match charged {
545 // Never reported: charged now, from the gateway's figure.
546 None => {
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put547 let charge = charge_for(gateway_micros);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look548 let eligible = crate::credits::eligible_for(Some(g1t_contracts::billing::ComputeKind::Agent), None);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put549 let drawn = self.draw(&run.workspace, charge, &settled_at[..7], &eligible).await?;
Prices keep themselves current with what g1t pays550 let description = format!(
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put551 "Work on {}#{}, settled from AI Gateway after the sandbox stopped without reporting{free_note}{}",
552 run.repo,
553 run.number,
554 drawn.note()
Prices keep themselves current with what g1t pays555 );
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put556 self.enter(&run.workspace, EntryKind::Usage, -(charge - drawn.total()), &description, &run.id, Some(&row), Some(gateway_micros), None, None)
Prices keep themselves current with what g1t pays557 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put558 self.record_drawn(&run.id, &drawn).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays559 self.count_spend(&run.workspace, gateway_micros, charge - drawn.total(), &drawn).await;
Prices keep themselves current with what g1t pays560 }
561 Some(charged) => {
562 let reported = charged.cost_micros.unwrap_or(0);
563 let delta = gateway_micros - reported;
564 if delta == 0 {
565 return Ok(());
566 }
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put567 let change = correction(charge_for(reported), charge_for(gateway_micros), -charged.amount_micros);
568 // A charge up is paid for like any other charge.
569 let drawn = if change > 0 {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look570 let eligible = crate::credits::eligible_for(Some(g1t_contracts::billing::ComputeKind::Agent), None);
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put571 self.draw(&run.workspace, change, &settled_at[..7], &eligible).await?
572 } else {
573 crate::credits::Drawn::default()
574 };
Prices keep themselves current with what g1t pays575 let description = format!(
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put576 "Correction to “{}”: AI Gateway priced its {requests} model requests at {}, not {}{}",
Prices keep themselves current with what g1t pays577 charged.description,
578 crate::features::dollars(gateway_micros),
579 crate::features::dollars(reported),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put580 drawn.note(),
Prices keep themselves current with what g1t pays581 );
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put582 let reference = format!("{}/settled", run.id);
Prices keep themselves current with what g1t pays583 self.enter(
584 &run.workspace,
585 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put586 -(change - drawn.total()),
Prices keep themselves current with what g1t pays587 &description,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put588 &reference,
Prices keep themselves current with what g1t pays589 Some(&row),
590 Some(delta),
591 None,
592 None,
593 )
594 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put595 self.record_drawn(&reference, &drawn).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays596 self.count_spend(&run.workspace, delta, change - drawn.total(), &drawn).await;
Prices keep themselves current with what g1t pays597 }
598 }
599 Ok(())
600 }
601
602 /// Checks each cost against what Cloudflare billed this month, and
603 /// moves the ones that changed.
604 pub(crate) async fn reconcile(&self, keeper: &Keeper) -> Result<()> {
605 if keeper.token.is_none() {
606 return Ok(());
607 }
608 let now = rfc3339(now_ms());
609 let today = &now[..10];
The keeper reads Cloudflare as it really answers610 let since = rfc3339(now_ms() - 30 * 24 * 60 * 60 * 1000);
611 let rows = keeper.billable_usage(&since[..10], today).await?;
Prices keep themselves current with what g1t pays612 for row in &rows {
613 self.db
614 .prepare(
615 "INSERT INTO cloudflare_usage (period_start, period_end, service, unit, quantity, cost_usd, fetched_at)
616 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
617 ON CONFLICT (period_start, service, unit) DO UPDATE SET
618 period_end = ?2, quantity = ?5, cost_usd = ?6, fetched_at = ?7",
619 )
620 .bind(&[
621 row.period_start.as_str().into(),
622 row.period_end.as_str().into(),
623 row.service.as_str().into(),
624 row.unit.as_str().into(),
625 row.quantity.into(),
626 row.cost.into(),
627 now.as_str().into(),
628 ])?
629 .run()
630 .await?;
631 }
632
The keeper reads Cloudflare as it really answers633 let named = |words: &[&str]| -> Vec<&UsageRow> {
Prices keep themselves current with what g1t pays634 rows.iter()
The keeper reads Cloudflare as it really answers635 .filter(|r| {
636 let service = r.service.to_lowercase();
637 words.iter().all(|word| service.contains(word))
638 })
639 .collect()
Prices keep themselves current with what g1t pays640 };
641
The keeper reads Cloudflare as it really answers642 // Containers: each resource at what the bill shows it costs, or
643 // the published rate while the included amount still covers it,
644 // over how much CPU g1t's sandboxes really use per second.
645 let memory = billed_rate(&named(&["container memory"]));
646 let disk = billed_rate(&named(&["container disk"]));
647 let vcpu = billed_rate(&named(&["container vcpu"]));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look648 let durable_object = billed_rate(&named(&["durable objects", "duration"]));
The keeper reads Cloudflare as it really answers649 let usage = keeper.container_usage(&since[..10], today).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look650 let rates = (
The keeper reads Cloudflare as it really answers651 memory.unwrap_or(LIST_MEMORY_GIB_SECOND),
652 disk.unwrap_or(LIST_DISK_GB_SECOND),
653 vcpu.unwrap_or(LIST_VCPU_SECOND),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look654 durable_object.unwrap_or(LIST_DO_GB_SECOND),
655 );
656 // The parts, for runs that report their own CPU.
657 let parts_reason = "Cloudflare's Containers and Durable Objects rates, as billed or published";
658 self.measure("sandbox_base_second", sandbox_base_micros(rates.0, rates.1, rates.3), parts_reason).await?;
659 self.measure("sandbox_cpu_second", rates.2 * MICROS_PER_DOLLAR as f64, parts_reason).await?;
660 if let Some(per_second) = sandbox_second_micros(usage, rates.0, rates.1, rates.2, rates.3) {
The keeper reads Cloudflare as it really answers661 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look662 let billed = [("memory", memory), ("disk", disk), ("vCPU", vcpu), ("Durable Object duration", durable_object)]
The keeper reads Cloudflare as it really answers663 .iter()
664 .filter(|(_, rate)| rate.is_some())
665 .map(|(name, _)| *name)
666 .collect::<Vec<_>>();
667 let reason = format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look668 "Sandboxes used {:.2} vCPU per second over {:.0} hours of Cloudflare Containers in the last 30 days, with the Durable Object behind each; {}",
The keeper reads Cloudflare as it really answers669 usage.cpu_seconds / instance_seconds,
670 instance_seconds / 3600.0,
671 if billed.is_empty() {
672 "rates are Cloudflare's published ones".to_owned()
673 } else {
674 format!("{} at what Cloudflare billed", billed.join(", "))
675 },
676 );
677 for meter in ["sandbox_second", "build_second"] {
678 self.measure(meter, per_second, &reason).await?;
Prices keep themselves current with what g1t pays679 }
680 }
The keeper reads Cloudflare as it really answers681 // Apps run as Workers: per million requests and CPU milliseconds,
682 // once the bill shows them charged.
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put683 // Security scans' CPU follows the same Workers CPU rate.
684 let app_meters: [(&str, &[&str], &str); 3] = [
The keeper reads Cloudflare as it really answers685 ("app_requests", &["workers", "requests"], "requests"),
686 ("app_cpu", &["workers cpu"], "CPU ms"),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put687 ("scan_cpu", &["workers cpu"], "CPU ms"),
The keeper reads Cloudflare as it really answers688 ];
689 for (meter, words, unit) in app_meters {
690 if let Some(rate) = billed_rate(&named(words)) {
691 let reason = format!("Cloudflare billed Workers {unit} at ${:.2} per million", rate * 1e6);
692 self.measure(meter, rate * 1e6 * MICROS_PER_DOLLAR as f64, &reason).await?;
Prices keep themselves current with what g1t pays693 }
694 }
695 self.db
696 .prepare("UPDATE prices SET checked_at = ?")
697 .bind(&[now.as_str().into()])?
698 .run()
699 .await?;
700 Ok(())
701 }
702
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily703 /// Proposes moving a meter's cost to a measurement (see `pricing`):
704 /// applied on its own when small, after notice when a rise; left for
705 /// staff when large or suspect.
Prices keep themselves current with what g1t pays706 async fn measure(&self, meter: &str, measured: f64, reason: &str) -> Result<()> {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily707 if let Some(outcome) = self.propose(meter, measured, reason, "keeper").await? {
708 worker::console_log!("{meter}: {outcome}");
Prices keep themselves current with what g1t pays709 }
710 Ok(())
711 }
712}
713
714#[cfg(test)]
715mod tests {
716 use super::*;
717
718 #[test]
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put719 fn a_correction_never_gives_back_what_the_workspace_did_not_pay() {
720 // Up by 2 cents: charged in full (then drawn down like any charge).
721 assert_eq!(correction(100_000, 120_000, 100_000), 20_000);
722 // Down by 2 cents, all of it paid by the workspace: given back.
723 assert_eq!(correction(120_000, 100_000, 120_000), -20_000);
724 // Down, but the open-source pool paid all but a cent: a cent back.
725 assert_eq!(correction(120_000, 100_000, 10_000), -10_000);
726 // Paid entirely by a credit or pool: nothing back.
727 assert_eq!(correction(120_000, 100_000, 0), 0);
Prices keep themselves current with what g1t pays728 }
729
730 #[test]
The keeper reads Cloudflare as it really answers731 fn a_sandbox_second_is_its_memory_and_disk_and_the_cpu_it_uses() {
732 // An hour of sandboxes that kept a fifth of a vCPU busy.
733 let usage = ContainerUsage { cpu_seconds: 720.0, memory_byte_seconds: 3600.0 * 4.0 * GIB };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look734 let micros =
735 sandbox_second_micros(usage, LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_VCPU_SECOND, LIST_DO_GB_SECOND).unwrap();
736 // 4 x 2.5 + 8 x 0.07 + 0.125 x 12.5 + 0.2 x 20 = 16.1225
737 assert!((micros - 16.1225).abs() < 1e-9, "{micros}");
738 // The Durable Object adds about 11% to the second it left out.
739 assert!((sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND) - 12.1225).abs() < 1e-9);
The keeper reads Cloudflare as it really answers740 // Too little use to say anything.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look741 assert!(sandbox_second_micros(ContainerUsage { cpu_seconds: 1.0, memory_byte_seconds: GIB }, 1.0, 1.0, 1.0, 1.0).is_none());
742 }
743
744 #[test]
745 fn a_run_that_reports_its_cpu_is_priced_on_it() {
746 let base = sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND);
747 let vcpu = LIST_VCPU_SECOND * MICROS_PER_DOLLAR as f64;
748 // A 10-minute cargo build that kept its half vCPU busy throughout.
749 let heavy = run_cost(600, 300.0, base, vcpu);
750 assert!((heavy - (600.0 * 12.1225 + 300.0 * 20.0)).abs() < 1e-6);
751 // The same ten minutes, mostly idle, costs less.
752 let light = run_cost(600, 30.0, base, vcpu);
753 assert!(light < heavy);
754 // The average would have under-priced the heavy one.
755 let average = 600.0 * (base + 0.195 * vcpu);
756 assert!(average < heavy && average > light);
757 assert_eq!(run_cost(0, -1.0, base, vcpu), 0.0);
Fast pages, required checks on the branch, self-hosted runners, honest incidents758 // A larger machine's base: its memory and disk, not its CPU.
759 assert!((base_scale(SANDBOX_GIB, SANDBOX_DISK_GB) - 1.0).abs() < 1e-12);
760 assert!((base_scale(12.0, 20.0) - 2.72).abs() < 0.01, "{}", base_scale(12.0, 20.0));
761 assert!((base_scale(8.0, 16.0) - 1.87).abs() < 0.01, "{}", base_scale(8.0, 16.0));
The keeper reads Cloudflare as it really answers762 }
763
764 #[test]
765 fn a_billed_rate_is_the_median_of_the_charged_days() {
766 let row = |quantity: f64, cost: f64| UsageRow {
767 period_start: String::new(),
768 period_end: String::new(),
769 service: "Containers / Container Memory".into(),
770 unit: "Count".into(),
771 quantity,
772 cost,
773 };
774 let rows = [row(100.0, 0.0), row(100.0, 0.0002), row(100.0, 0.00025), row(100.0, 0.00025)];
775 assert_eq!(billed_rate(&rows.iter().collect::<Vec<_>>()), Some(0.000_002_5));
776 assert_eq!(billed_rate(&[&row(5.0, 0.0)]), None);
777 }
778
779 #[test]
Prices keep themselves current with what g1t pays780 fn usage_rows_are_read_by_their_focus_names() {
781 let row = UsageRow::from_value(&json!({
782 "ServiceFamilyName": "Containers",
783 "ServiceName": "Memory",
The keeper reads Cloudflare as it really answers784 "PricingUnit": "GiB-seconds",
Prices keep themselves current with what g1t pays785 "PricingQuantity": "1200.5",
786 "ContractedCost": 0.003,
787 "ChargePeriodStart": "2026-10-01",
788 }))
789 .unwrap();
790 assert_eq!(row.service, "Containers / Memory");
791 assert_eq!(row.quantity, 1200.5);
792 assert_eq!(row.cost, 0.003);
793 assert!(UsageRow::from_value(&json!({ "nothing": 1 })).is_none());
794 }
795}