Skip to content
980 linesCodeBlameRaw

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
Merge branch 'worktree-agent-a633ac0f7f66d419d'33use crate::{Billing, RunRow};
Prices keep themselves current with what g1t pays34
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
Merge branch 'worktree-agent-a633ac0f7f66d419d'113 /// AI Gateway's id, empty when there is none.
114 pub(crate) fn gateway(&self) -> &str {
115 &self.gateway
116 }
117
Billing: AI Gateway's analytics are read with the token that can see them, and a gateway that priced nothing is said118 /// 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. Not the
120 /// other way round: Cloudflare answers a token that cannot see AI
121 /// Gateway with no rows, not an error, so the bill's token would read
122 /// as a gateway that priced nothing.
123 pub(crate) async fn gateway_graphql(&self, body: Value) -> Result<Value> {
124 let Some(token) = &self.token else {
125 return self.graphql(body).await;
126 };
127 match send_with(token, Method::Post, "https://api.cloudflare.com/client/v4/graphql", Some(body.clone())).await {
Merge branch 'worktree-agent-a633ac0f7f66d419d'128 Ok(answer) => Ok(answer),
Billing: AI Gateway's analytics are read with the token that can see them, and a gateway that priced nothing is said129 Err(error) => match &self.billing_token {
130 Some(billing) if billing != token => self.graphql(body).await,
Merge branch 'worktree-agent-a633ac0f7f66d419d'131 _ => Err(error),
132 },
133 }
134 }
135
136 /// What AI Gateway priced a session's requests at, and how many there
137 /// were, with the requests it had no price for.
138 async fn session_cost(&self, session: &str) -> Result<SessionCost> {
139 let mut total = SessionCost { complete: true, ..SessionCost::default() };
140 for page in 1..=MAX_LOG_PAGES {
The keeper reads Cloudflare as it really answers141 // The filter goes as URL-encoded JSON; the bracket form is
142 // ignored, and would sum every log there is. Session ids are
143 // [a-z0-9_], which need no escaping inside it.
144 let filter = format!(
145 "%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"
146 );
Prices keep themselves current with what g1t pays147 let url = self.api(&format!(
The keeper reads Cloudflare as it really answers148 "/ai-gateway/gateways/{}/logs?per_page=50&page={page}&filters={filter}",
Prices keep themselves current with what g1t pays149 self.gateway
150 ));
151 let body = self.send(Method::Get, &url, None).await?;
152 let logs = body["result"].as_array().cloned().unwrap_or_default();
153 for log in &logs {
Merge branch 'worktree-agent-a633ac0f7f66d419d'154 total.add(log);
Prices keep themselves current with what g1t pays155 }
156 if logs.len() < 50 {
Merge branch 'worktree-agent-a633ac0f7f66d419d'157 return Ok(total);
Prices keep themselves current with what g1t pays158 }
159 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'160 // More logs than were read: what was read is less than the run.
161 total.complete = false;
162 Ok(total)
Prices keep themselves current with what g1t pays163 }
164
The keeper reads Cloudflare as it really answers165 /// The account's billable usage, one row per service per day, as
166 /// Cloudflare reports it.
Prices keep themselves current with what g1t pays167 async fn billable_usage(&self, from: &str, to: &str) -> Result<Vec<UsageRow>> {
168 let body = self
The keeper reads Cloudflare as it really answers169 .send(Method::Get, &self.api(&format!("/billable-usage?from={from}&to={to}")), None)
Prices keep themselves current with what g1t pays170 .await?;
171 let rows = body["result"].as_array().cloned().unwrap_or_default();
172 Ok(rows.iter().filter_map(UsageRow::from_value).collect())
173 }
174
The keeper reads Cloudflare as it really answers175 /// What g1t's containers used from `since` to `until` (dates), as
176 /// Cloudflare bills it: memory in byte-seconds, and CPU seconds.
177 async fn container_usage(&self, since: &str, until: &str) -> Result<ContainerUsage> {
178 let query = "query ($account: String!, $since: Date!, $until: Date!) {
Prices keep themselves current with what g1t pays179 viewer { accounts(filter: { accountTag: $account }) {
The keeper reads Cloudflare as it really answers180 containersUsageAdaptiveGroups(limit: 1000, filter: { date_geq: $since, date_leq: $until }) {
181 sum { cpuTimeSec allocatedMemory }
Prices keep themselves current with what g1t pays182 }
183 } }
184 }";
185 let body = self
186 .send(
187 Method::Post,
188 "https://api.cloudflare.com/client/v4/graphql",
189 Some(json!({ "query": query, "variables": { "account": self.account, "since": since, "until": until } })),
190 )
191 .await?;
The keeper reads Cloudflare as it really answers192 let groups = body["data"]["viewer"]["accounts"][0]["containersUsageAdaptiveGroups"]
Prices keep themselves current with what g1t pays193 .as_array()
194 .cloned()
195 .unwrap_or_default();
The keeper reads Cloudflare as it really answers196 Ok(groups.iter().fold(ContainerUsage::default(), |total, g| ContainerUsage {
197 cpu_seconds: total.cpu_seconds + g["sum"]["cpuTimeSec"].as_f64().unwrap_or(0.0),
198 memory_byte_seconds: total.memory_byte_seconds + g["sum"]["allocatedMemory"].as_f64().unwrap_or(0.0),
199 }))
Prices keep themselves current with what g1t pays200 }
201}
202
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily203/// A request to Cloudflare's API with a bearer token; anything but 200 is
204/// an error with what Cloudflare said.
205async fn send_with(token: &str, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
206 let headers = Headers::new();
207 headers.set("authorization", &format!("Bearer {token}"))?;
208 headers.set("content-type", "application/json")?;
209 let mut init = RequestInit::new();
210 init.with_method(method).with_headers(headers);
211 if let Some(body) = body {
212 init.with_body(Some(body.to_string().into()));
213 }
214 let mut response = Fetch::Request(Request::new_with_init(url, &init)?).send().await?;
215 let status = response.status_code();
216 let value: Value = response.json().await.unwrap_or(Value::Null);
217 if status != 200 {
218 return Err(worker::Error::RustError(format!("Cloudflare answered {status}: {value}")));
219 }
220 Ok(value)
221}
222
The keeper reads Cloudflare as it really answers223#[derive(Debug, Default, Clone, Copy)]
224pub(crate) struct ContainerUsage {
225 cpu_seconds: f64,
226 memory_byte_seconds: f64,
227}
228
229/// g1t's sandboxes: Containers' standard-1, half a vCPU, 4 GiB, 8 GB disk.
230const SANDBOX_GIB: f64 = 4.0;
231const SANDBOX_DISK_GB: f64 = 8.0;
232const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look233/// The Durable Object behind each container is billed for as long as the
234/// container runs, at 128 MB.
235const SANDBOX_DO_GB: f64 = 0.125;
The keeper reads Cloudflare as it really answers236
237/// Cloudflare's published Containers rates, in dollars, used for any rate
238/// the bill does not show yet (while usage is inside the included amount).
239const LIST_MEMORY_GIB_SECOND: f64 = 0.000_002_5;
240const LIST_DISK_GB_SECOND: f64 = 0.000_000_07;
241const LIST_VCPU_SECOND: f64 = 0.000_02;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look242/// Durable Objects duration: $12.50 per million GB-seconds.
243const LIST_DO_GB_SECOND: f64 = 0.000_012_5;
The keeper reads Cloudflare as it really answers244
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look245/// What one second of a sandbox costs whatever it does, in millionths of a
246/// dollar: its memory and disk, and the Durable Object behind it, for the
247/// whole second. CPU is billed only while busy, on top.
248pub(crate) fn sandbox_base_micros(memory: f64, disk: f64, durable_object: f64) -> f64 {
249 (SANDBOX_GIB * memory + SANDBOX_DISK_GB * disk + SANDBOX_DO_GB * durable_object) * MICROS_PER_DOLLAR as f64
250}
251
252/// What one second of a sandbox costs on average, in millionths of a
253/// dollar: its base, and the CPU sandboxes actually use per second of
254/// running. Runs that report their own CPU are priced on it instead (see
255/// `run_cost`).
256pub(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 answers257 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
258 if instance_seconds < 3600.0 {
259 return None;
260 }
261 let cpu_share = usage.cpu_seconds / instance_seconds;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look262 Some(sandbox_base_micros(memory, disk, durable_object) + cpu_share * vcpu * MICROS_PER_DOLLAR as f64)
263}
264
Fast pages, required checks on the branch, self-hosted runners, honest incidents265/// How much more a second of a larger machine's memory and disk (and the
266/// Durable Object behind it) costs than the standard sandbox's, at
267/// Cloudflare's list rates: 1 for the standard machine.
268pub(crate) fn base_scale(memory_gib: f64, disk_gb: f64) -> f64 {
269 let base = |memory: f64, disk: f64| memory * LIST_MEMORY_GIB_SECOND + disk * LIST_DISK_GB_SECOND + SANDBOX_DO_GB * LIST_DO_GB_SECOND;
270 base(memory_gib, disk_gb) / base(SANDBOX_GIB, SANDBOX_DISK_GB)
271}
272
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look273/// What a run that reported its own CPU cost g1t: its base for every
274/// second, and its vCPU-seconds at the vCPU rate.
275pub(crate) fn run_cost(seconds: i64, cpu_seconds: f64, base_per_second: f64, per_vcpu_second: f64) -> f64 {
276 seconds.max(0) as f64 * base_per_second + cpu_seconds.max(0.0) * per_vcpu_second
The keeper reads Cloudflare as it really answers277}
278
279/// A unit's marginal rate from the bill: the median, over the days that
280/// were charged, of cost over quantity. None while nothing was charged.
281pub(crate) fn billed_rate(rows: &[&UsageRow]) -> Option<f64> {
282 let mut rates: Vec<f64> = rows
283 .iter()
284 .filter(|r| r.cost > 0.0 && r.quantity > 0.0)
285 .map(|r| r.cost / r.quantity)
286 .collect();
287 if rates.is_empty() {
288 return None;
289 }
290 rates.sort_by(f64::total_cmp);
291 Some(rates[rates.len() / 2])
292}
293
Prices keep themselves current with what g1t pays294/// One line of Cloudflare's billable usage.
295#[derive(Debug, Clone)]
296pub(crate) struct UsageRow {
297 period_start: String,
298 period_end: String,
299 service: String,
300 unit: String,
301 quantity: f64,
302 cost: f64,
303}
304
305impl UsageRow {
306 /// Read leniently: the API is new, and its field names are FOCUS's.
307 fn from_value(row: &Value) -> Option<Self> {
308 let text = |keys: &[&str]| keys.iter().find_map(|k| row[*k].as_str()).unwrap_or_default().to_owned();
309 let number = |keys: &[&str]| {
310 keys.iter()
311 .find_map(|k| row[*k].as_f64().or_else(|| row[*k].as_str().and_then(|s| s.parse().ok())))
312 .unwrap_or(0.0)
313 };
314 let service = text(&["ServiceName", "service_name", "service"]);
315 if service.is_empty() {
316 return None;
317 }
318 let family = text(&["ServiceFamilyName", "service_family_name"]);
319 Some(UsageRow {
320 period_start: text(&["ChargePeriodStart", "charge_period_start"]),
321 period_end: text(&["ChargePeriodEnd", "charge_period_end"]),
322 service: if family.is_empty() { service } else { format!("{family} / {service}") },
The keeper reads Cloudflare as it really answers323 unit: text(&["PricingUnit", "ConsumedUnit", "consumed_unit"]),
Prices keep themselves current with what g1t pays324 quantity: number(&["PricingQuantity", "ConsumedQuantity", "pricing_quantity"]),
The keeper reads Cloudflare as it really answers325 // What g1t pays; list price if nothing was contracted.
326 cost: Some(number(&["ContractedCost", "BilledCost", "contracted_cost"]))
327 .filter(|cost| *cost > 0.0)
328 .unwrap_or_else(|| number(&["ListCost", "list_cost"])),
Prices keep themselves current with what g1t pays329 })
330 }
331}
332
333#[derive(Deserialize)]
334struct PriceRow {
335 meter: String,
336 title: String,
337 unit: String,
338 cost_micros: f64,
339 markup_percent: u32,
340 source: String,
341 checked_at: Option<String>,
342 updated_at: String,
343}
344
345#[derive(Deserialize)]
346struct ChangeRow {
347 meter: String,
348 old_cost_micros: f64,
349 new_cost_micros: f64,
350 markup_percent: u32,
Prices are what g1t pays plus 20%, from the first second351 old_markup_percent: Option<u32>,
Prices keep themselves current with what g1t pays352 reason: String,
353 created_at: String,
354}
355
356#[derive(Deserialize)]
357struct Unsettled {
358 id: String,
359 workspace: String,
360 repo: String,
361 number: u32,
362 task: String,
363 model: String,
364 token_hash: String,
365 billed_to: Option<String>,
366 session_id: String,
367 created_at: String,
368 finished_at: Option<String>,
369}
370
371#[derive(Deserialize)]
372struct Charged {
373 cost_micros: Option<i64>,
374 description: String,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put375 amount_micros: i64,
376}
377
378/// What a settled run's correction comes to, from the charges at the
379/// reported and the gateway's cost and what the workspace was charged at
380/// first. A charge up is drawn down like any charge; a charge down is
381/// given back only up to what the workspace paid, since what a credit or
382/// a pool paid was never the workspace's money.
383pub(crate) fn correction(reported_charge: i64, gateway_charge: i64, first_charged: i64) -> i64 {
384 let delta = gateway_charge - reported_charge;
385 if delta >= 0 { delta } else { delta.max(-first_charged.max(0)) }
Prices keep themselves current with what g1t pays386}
387
Merge branch 'worktree-agent-a633ac0f7f66d419d'388/// A session's logs are read 50 at a time, up to this many pages.
389const MAX_LOG_PAGES: u32 = 40;
390
391/// What AI Gateway's logs say a session cost.
392#[derive(Clone, Debug, Default, PartialEq)]
393pub(crate) struct SessionCost {
394 /// What the gateway priced the requests at, in dollars.
395 pub cost_usd: f64,
396 pub requests: u32,
397 /// Requests that used tokens but that the gateway put no price on: a
398 /// model it has no price for. Their cost is not in `cost_usd`.
399 pub unpriced: u32,
400 /// The models of those, for the statement and the drift.
401 pub unpriced_models: Vec<String>,
402 /// False when there were more logs than were read.
403 pub complete: bool,
404}
405
406impl SessionCost {
407 /// Adds one log, read leniently: `cost` in dollars, `tokens_in` and
408 /// `tokens_out`, `cached` for an answer from the gateway's own cache
409 /// (which costs nothing).
410 pub(crate) fn add(&mut self, log: &Value) {
411 self.requests += 1;
412 let number = |key: &str| log[key].as_f64().or_else(|| log[key].as_str().and_then(|s| s.parse().ok()));
413 let cost = number("cost").filter(|c| c.is_finite() && *c > 0.0);
414 let tokens = number("tokens_in").unwrap_or(0.0) + number("tokens_out").unwrap_or(0.0);
415 let cached = log["cached"].as_bool().unwrap_or(false);
416 match cost {
417 Some(cost) => self.cost_usd += cost,
418 None if tokens > 0.0 && !cached => {
419 self.unpriced += 1;
420 let model = log["model"].as_str().unwrap_or("an unnamed model").to_owned();
421 if !self.unpriced_models.contains(&model) {
422 self.unpriced_models.push(model);
423 }
424 }
425 None => {}
426 }
427 }
428
429 /// Whether the gateway's figure is the whole of what the run cost.
430 pub(crate) fn whole(&self) -> bool {
431 self.complete && self.unpriced == 0
432 }
433}
434
435/// The cost a run is settled at, in millionths: the gateway's figure when
436/// it priced every request; otherwise (a model it has no price for, or
437/// more logs than were read) never less than the sandbox reported, since
438/// the gateway's sum is then short of what the provider bills. With a
439/// reason for the statement and the drift when it is not the gateway's
440/// figure alone.
441pub(crate) fn settled_cost(reported_micros: i64, gateway: &SessionCost) -> (i64, Option<String>) {
442 // Not held to MAX_RUN_COST_USD: the gateway's figure is trusted.
443 let priced = if gateway.cost_usd.is_finite() { (gateway.cost_usd.max(0.0) * MICROS_PER_DOLLAR as f64).ceil() as i64 } else { 0 };
444 if gateway.whole() {
445 return (priced, None);
446 }
447 let mut why = Vec::new();
448 if gateway.unpriced > 0 {
449 why.push(format!(
450 "AI Gateway has no price for {} of its {} requests ({})",
451 gateway.unpriced,
452 gateway.requests,
453 gateway.unpriced_models.join(", ")
454 ));
455 }
456 if !gateway.complete {
457 why.push(format!("more than {} of its requests were logged", gateway.requests));
458 }
459 (priced.max(reported_micros.max(0)), Some(why.join("; ")))
460}
461
Prices keep themselves current with what g1t pays462fn ms(timestamp: &str) -> u64 {
463 // RFC 3339 in UTC, as g1t writes them.
464 worker::js_sys::Date::parse(timestamp) as u64
465}
466
467impl Billing {
468 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 index469 // Three reads at once; the plans are priced from the rows already
470 // read, not one query per meter (status.g1t.sh times this call).
471 let (prices, changes, coming) = futures_util::future::join3(
472 async { self.db.prepare("SELECT * FROM prices ORDER BY rowid").all().await?.results::<PriceRow>() },
473 async {
474 self.db
475 .prepare("SELECT * FROM price_changes ORDER BY created_at DESC LIMIT 20")
476 .all()
477 .await?
478 .results::<ChangeRow>()
479 },
480 // Changes still to come first, so a rise is seen before it is charged.
481 self.coming_changes(),
482 )
483 .await;
484 let (prices, changes, coming) = (prices?, changes?, coming?);
485 let book: std::collections::BTreeMap<&str, f64> = prices
486 .iter()
487 .map(|row| (row.meter.as_str(), Price::price_for(row.cost_micros, row.markup_percent)))
488 .collect();
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar489 let plans: Vec<_> = g1t_contracts::billing::Feature::ALL
490 .iter()
491 .map(|feature| match feature {
492 g1t_contracts::billing::Feature::Security => crate::features::security_plan_at(&book),
493 _ => self.plan_at(&book),
494 })
495 .collect();
Prices keep themselves current with what g1t pays496 Ok(PriceBook {
497 prices: prices
498 .into_iter()
499 .map(|row| Price {
500 price_micros: Price::price_for(row.cost_micros, row.markup_percent),
501 meter: row.meter,
502 title: row.title,
503 unit: row.unit,
504 cost_micros: row.cost_micros,
505 markup_percent: row.markup_percent,
506 source: row.source,
507 checked_at: row.checked_at,
508 updated_at: row.updated_at,
509 })
510 .collect(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily511 changes: coming
Prices keep themselves current with what g1t pays512 .into_iter()
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily513 .chain(changes.into_iter().map(|row| PriceChange {
Prices keep themselves current with what g1t pays514 meter: row.meter,
515 old_cost_micros: row.old_cost_micros,
516 new_cost_micros: row.new_cost_micros,
517 markup_percent: row.markup_percent,
Prices are what g1t pays plus 20%, from the first second518 old_markup_percent: row.old_markup_percent,
Prices keep themselves current with what g1t pays519 reason: row.reason,
520 created_at: row.created_at,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily521 effective_at: None,
522 }))
Prices keep themselves current with what g1t pays523 .collect(),
524 model_margin_percent: self.margin_percent,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily525 plans,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put526 free: Some(g1t_contracts::billing::FreeTier {
527 trial_workspace_micros: if self.trials_on { self.plans.trial_workspace_micros } else { 0 },
528 trial_monthly_pool_micros: if self.trials_on { self.plans.trial_monthly_pool_micros } else { 0 },
529 oss_pool_micros: self.plans.oss_pool_micros,
530 oss_repo_micros: self.plans.oss_repo_micros,
531 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 sudo532 audit_retention_days: self.plans.free_audit_days,
533 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 put534 min_charge_micros: self.plans.min_charge_micros,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look535 git_operations_included: self.plans.git_included,
536 paid_start_ceiling_micros: self.plans.paid_start_micros,
537 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 put538 }),
Prices keep themselves current with what g1t pays539 })
540 }
541
The keeper reads Cloudflare as it really answers542 /// Whether the costs have never been checked against Cloudflare's bill.
543 pub(crate) async fn never_checked(&self) -> Result<bool> {
544 Ok(self
545 .db
546 .prepare("SELECT meter FROM prices WHERE checked_at IS NOT NULL LIMIT 1")
547 .first::<Value>(None)
548 .await?
549 .is_none())
550 }
551
Prices keep themselves current with what g1t pays552 /// A meter's cost and price per unit, from the book.
553 pub(crate) async fn price(&self, meter: &str) -> Result<Option<(f64, f64)>> {
554 #[derive(Deserialize)]
555 struct Row {
556 cost_micros: f64,
557 markup_percent: u32,
558 }
559 Ok(self
560 .db
561 .prepare("SELECT cost_micros, markup_percent FROM prices WHERE meter = ?")
562 .bind(&[meter.into()])?
563 .first::<Row>(None)
564 .await?
565 .map(|row| (row.cost_micros, Price::price_for(row.cost_micros, row.markup_percent))))
566 }
567
568 /// Corrects finished runs to what AI Gateway priced them at, and
569 /// charges runs whose sandbox died before reporting.
570 pub(crate) async fn settle_runs(&self, keeper: &Keeper) -> Result<()> {
571 if keeper.token.is_none() || keeper.gateway.is_empty() {
572 return Ok(());
573 }
574 let now = now_ms();
575 let runs = self
576 .db
577 .prepare(
578 "SELECT id, workspace, repo, number, task, model, token_hash, billed_to, session_id, created_at, finished_at
579 FROM runs
580 WHERE session_id IS NOT NULL AND settled_at IS NULL
581 AND ((finished_at IS NOT NULL AND finished_at < ?1) OR created_at < ?2)
582 ORDER BY created_at LIMIT 10",
583 )
584 .bind(&[rfc3339(now - SETTLE_AFTER_MS).into(), rfc3339(now - ABANDONED_AFTER_MS).into()])?
585 .all()
586 .await?
587 .results::<Unsettled>()?;
588 for run in runs {
Merge branch 'worktree-agent-a633ac0f7f66d419d'589 let gateway = match keeper.session_cost(&run.session_id).await {
Prices keep themselves current with what g1t pays590 Ok(found) => found,
591 Err(error) => {
592 worker::console_error!("could not read gateway logs for {}: {error}", run.id);
593 continue;
594 }
595 };
596 let since = ms(run.finished_at.as_deref().unwrap_or(&run.created_at));
Merge branch 'worktree-agent-a633ac0f7f66d419d'597 if gateway.requests == 0 && now.saturating_sub(since) < GIVE_UP_AFTER_MS {
Prices keep themselves current with what g1t pays598 continue;
599 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'600 self.settle(&run, &gateway).await?;
Prices keep themselves current with what g1t pays601 }
602 Ok(())
603 }
604
Merge branch 'worktree-agent-a633ac0f7f66d419d'605 async fn settle(&self, run: &Unsettled, gateway: &SessionCost) -> Result<()> {
606 let requests = gateway.requests;
Prices keep themselves current with what g1t pays607 let row = RunRow {
608 workspace: run.workspace.clone(),
609 repo: run.repo.clone(),
610 number: run.number,
611 task: run.task.clone(),
612 model: run.model.clone(),
613 token_hash: run.token_hash.clone(),
614 billed_to: run.billed_to.clone(),
615 };
616 let charged = self
617 .db
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put618 .prepare("SELECT cost_micros, description, amount_micros FROM ledger WHERE reference = ?")
Prices keep themselves current with what g1t pays619 .bind(&[run.id.as_str().into()])?
620 .first::<Charged>(None)
621 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'622 let reported = charged.as_ref().and_then(|c| c.cost_micros).unwrap_or(0);
623 // The gateway's figure; never under what the sandbox reported when
624 // the gateway could not price all of it (see `settled_cost`).
625 let (gateway_micros, short) = settled_cost(reported, gateway);
Billing accounts, terms and enterprises; g1t is no longer free626 let terms = self.terms_of(&run.workspace).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'627 // A cost's charge on the account's terms, and what a discount gave
628 // below cost plus the margin (counted as given, see `charged`).
Prices keep themselves current with what g1t pays629 let charge_for = |micros: i64| {
Merge branch 'worktree-agent-a633ac0f7f66d419d'630 if self.free { (0, 0) } else { terms.discounted(crate::margin_on(micros, self.margin_percent)) }
Prices keep themselves current with what g1t pays631 };
632 let settled_at = rfc3339(now_ms());
633 // Claim it, so two crons never settle it twice.
634 let claimed = self
635 .db
Merge branch 'worktree-agent-a633ac0f7f66d419d'636 .prepare(
637 "UPDATE runs SET settled_at = ?, gateway_cost_micros = ?, gateway_note = ?, finished_at = COALESCE(finished_at, ?)
638 WHERE id = ? AND settled_at IS NULL RETURNING id",
639 )
Prices keep themselves current with what g1t pays640 .bind(&[
641 settled_at.as_str().into(),
642 (gateway_micros as f64).into(),
Merge branch 'worktree-agent-a633ac0f7f66d419d'643 short.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
Prices keep themselves current with what g1t pays644 settled_at.as_str().into(),
645 run.id.as_str().into(),
646 ])?
647 .first::<Value>(None)
648 .await?;
649 if claimed.is_none() || requests == 0 {
650 return Ok(());
651 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'652 if let Some(why) = &short {
653 worker::console_warn!("run {} settled at no less than reported: {why}", run.id);
654 }
655 let short_note = short.as_ref().map_or(String::new(), |why| format!(" ({why}; charged at no less than the sandbox reported)"));
Prices keep themselves current with what g1t pays656 let free_note = if self.free { " (free while g1t is being built out)" } else { "" };
657 match charged {
658 // Never reported: charged now, from the gateway's figure.
659 None => {
Merge branch 'worktree-agent-a633ac0f7f66d419d'660 let (charge, discount) = charge_for(gateway_micros);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look661 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 put662 let drawn = self.draw(&run.workspace, charge, &settled_at[..7], &eligible).await?;
Prices keep themselves current with what g1t pays663 let description = format!(
Merge branch 'worktree-agent-a633ac0f7f66d419d'664 "Work on {}#{}, settled from AI Gateway after the sandbox stopped without reporting{short_note}{free_note}{}",
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put665 run.repo,
666 run.number,
667 drawn.note()
Prices keep themselves current with what g1t pays668 );
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put669 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 pays670 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put671 self.record_drawn(&run.id, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'672 self.record_discount(&run.id, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays673 self.count_spend(&run.workspace, gateway_micros, charge - drawn.total(), &drawn).await;
Prices keep themselves current with what g1t pays674 }
675 Some(charged) => {
676 let delta = gateway_micros - reported;
677 if delta == 0 {
678 return Ok(());
679 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'680 let ((was, was_given), (now, now_given)) = (charge_for(reported), charge_for(gateway_micros));
681 let change = correction(was, now, -charged.amount_micros);
682 // What the discount gives moves with the charge.
683 let discount = now_given - was_given;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put684 // A charge up is paid for like any other charge.
685 let drawn = if change > 0 {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look686 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 put687 self.draw(&run.workspace, change, &settled_at[..7], &eligible).await?
688 } else {
689 crate::credits::Drawn::default()
690 };
Prices keep themselves current with what g1t pays691 let description = format!(
Merge branch 'worktree-agent-a633ac0f7f66d419d'692 "Correction to “{}”: AI Gateway priced its {requests} model requests at {}, not {}{short_note}{}",
Prices keep themselves current with what g1t pays693 charged.description,
694 crate::features::dollars(gateway_micros),
695 crate::features::dollars(reported),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put696 drawn.note(),
Prices keep themselves current with what g1t pays697 );
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put698 let reference = format!("{}/settled", run.id);
Prices keep themselves current with what g1t pays699 self.enter(
700 &run.workspace,
701 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put702 -(change - drawn.total()),
Prices keep themselves current with what g1t pays703 &description,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put704 &reference,
Prices keep themselves current with what g1t pays705 Some(&row),
706 Some(delta),
707 None,
708 None,
709 )
710 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put711 self.record_drawn(&reference, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'712 self.record_discount(&reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays713 self.count_spend(&run.workspace, delta, change - drawn.total(), &drawn).await;
Prices keep themselves current with what g1t pays714 }
715 }
716 Ok(())
717 }
718
719 /// Checks each cost against what Cloudflare billed this month, and
720 /// moves the ones that changed.
721 pub(crate) async fn reconcile(&self, keeper: &Keeper) -> Result<()> {
722 if keeper.token.is_none() {
723 return Ok(());
724 }
725 let now = rfc3339(now_ms());
726 let today = &now[..10];
The keeper reads Cloudflare as it really answers727 let since = rfc3339(now_ms() - 30 * 24 * 60 * 60 * 1000);
728 let rows = keeper.billable_usage(&since[..10], today).await?;
Prices keep themselves current with what g1t pays729 for row in &rows {
730 self.db
731 .prepare(
732 "INSERT INTO cloudflare_usage (period_start, period_end, service, unit, quantity, cost_usd, fetched_at)
733 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
734 ON CONFLICT (period_start, service, unit) DO UPDATE SET
735 period_end = ?2, quantity = ?5, cost_usd = ?6, fetched_at = ?7",
736 )
737 .bind(&[
738 row.period_start.as_str().into(),
739 row.period_end.as_str().into(),
740 row.service.as_str().into(),
741 row.unit.as_str().into(),
742 row.quantity.into(),
743 row.cost.into(),
744 now.as_str().into(),
745 ])?
746 .run()
747 .await?;
748 }
749
The keeper reads Cloudflare as it really answers750 let named = |words: &[&str]| -> Vec<&UsageRow> {
Prices keep themselves current with what g1t pays751 rows.iter()
The keeper reads Cloudflare as it really answers752 .filter(|r| {
753 let service = r.service.to_lowercase();
754 words.iter().all(|word| service.contains(word))
755 })
756 .collect()
Prices keep themselves current with what g1t pays757 };
758
The keeper reads Cloudflare as it really answers759 // Containers: each resource at what the bill shows it costs, or
760 // the published rate while the included amount still covers it,
761 // over how much CPU g1t's sandboxes really use per second.
762 let memory = billed_rate(&named(&["container memory"]));
763 let disk = billed_rate(&named(&["container disk"]));
764 let vcpu = billed_rate(&named(&["container vcpu"]));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look765 let durable_object = billed_rate(&named(&["durable objects", "duration"]));
The keeper reads Cloudflare as it really answers766 let usage = keeper.container_usage(&since[..10], today).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look767 let rates = (
The keeper reads Cloudflare as it really answers768 memory.unwrap_or(LIST_MEMORY_GIB_SECOND),
769 disk.unwrap_or(LIST_DISK_GB_SECOND),
770 vcpu.unwrap_or(LIST_VCPU_SECOND),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look771 durable_object.unwrap_or(LIST_DO_GB_SECOND),
772 );
773 // The parts, for runs that report their own CPU.
774 let parts_reason = "Cloudflare's Containers and Durable Objects rates, as billed or published";
775 self.measure("sandbox_base_second", sandbox_base_micros(rates.0, rates.1, rates.3), parts_reason).await?;
776 self.measure("sandbox_cpu_second", rates.2 * MICROS_PER_DOLLAR as f64, parts_reason).await?;
777 if let Some(per_second) = sandbox_second_micros(usage, rates.0, rates.1, rates.2, rates.3) {
The keeper reads Cloudflare as it really answers778 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 look779 let billed = [("memory", memory), ("disk", disk), ("vCPU", vcpu), ("Durable Object duration", durable_object)]
The keeper reads Cloudflare as it really answers780 .iter()
781 .filter(|(_, rate)| rate.is_some())
782 .map(|(name, _)| *name)
783 .collect::<Vec<_>>();
784 let reason = format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look785 "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 answers786 usage.cpu_seconds / instance_seconds,
787 instance_seconds / 3600.0,
788 if billed.is_empty() {
789 "rates are Cloudflare's published ones".to_owned()
790 } else {
791 format!("{} at what Cloudflare billed", billed.join(", "))
792 },
793 );
794 for meter in ["sandbox_second", "build_second"] {
795 self.measure(meter, per_second, &reason).await?;
Prices keep themselves current with what g1t pays796 }
797 }
The keeper reads Cloudflare as it really answers798 // Apps run as Workers: per million requests and CPU milliseconds,
799 // 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 put800 // Security scans' CPU follows the same Workers CPU rate.
801 let app_meters: [(&str, &[&str], &str); 3] = [
The keeper reads Cloudflare as it really answers802 ("app_requests", &["workers", "requests"], "requests"),
803 ("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 put804 ("scan_cpu", &["workers cpu"], "CPU ms"),
The keeper reads Cloudflare as it really answers805 ];
806 for (meter, words, unit) in app_meters {
807 if let Some(rate) = billed_rate(&named(words)) {
808 let reason = format!("Cloudflare billed Workers {unit} at ${:.2} per million", rate * 1e6);
809 self.measure(meter, rate * 1e6 * MICROS_PER_DOLLAR as f64, &reason).await?;
Prices keep themselves current with what g1t pays810 }
811 }
812 self.db
813 .prepare("UPDATE prices SET checked_at = ?")
814 .bind(&[now.as_str().into()])?
815 .run()
816 .await?;
817 Ok(())
818 }
819
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily820 /// Proposes moving a meter's cost to a measurement (see `pricing`):
821 /// applied on its own when small, after notice when a rise; left for
822 /// staff when large or suspect.
Prices keep themselves current with what g1t pays823 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 daily824 if let Some(outcome) = self.propose(meter, measured, reason, "keeper").await? {
825 worker::console_log!("{meter}: {outcome}");
Prices keep themselves current with what g1t pays826 }
827 Ok(())
828 }
829}
830
831#[cfg(test)]
832mod tests {
833 use super::*;
834
835 #[test]
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put836 fn a_correction_never_gives_back_what_the_workspace_did_not_pay() {
837 // Up by 2 cents: charged in full (then drawn down like any charge).
838 assert_eq!(correction(100_000, 120_000, 100_000), 20_000);
839 // Down by 2 cents, all of it paid by the workspace: given back.
840 assert_eq!(correction(120_000, 100_000, 120_000), -20_000);
841 // Down, but the open-source pool paid all but a cent: a cent back.
842 assert_eq!(correction(120_000, 100_000, 10_000), -10_000);
843 // Paid entirely by a credit or pool: nothing back.
844 assert_eq!(correction(120_000, 100_000, 0), 0);
Prices keep themselves current with what g1t pays845 }
846
Merge branch 'worktree-agent-a633ac0f7f66d419d'847 fn logs(entries: &[Value]) -> SessionCost {
848 let mut total = SessionCost { complete: true, ..SessionCost::default() };
849 for log in entries {
850 total.add(log);
851 }
852 total
853 }
854
855 #[test]
856 fn a_run_is_settled_at_the_gateways_figure_when_it_priced_every_request() {
857 let gateway = logs(&[
858 json!({ "cost": 0.012, "tokens_in": 4000, "tokens_out": 300, "model": "claude-sonnet-5-5" }),
859 json!({ "cost": "0.003", "tokens_in": 900, "tokens_out": 40, "model": "claude-haiku-4-5" }),
860 // Served from the gateway's own cache: no cost, and none owed.
861 json!({ "cost": 0, "tokens_in": 900, "tokens_out": 40, "cached": true }),
862 // An error with no tokens costs nothing either.
863 json!({ "cost": null, "tokens_in": 0, "tokens_out": 0 }),
864 ]);
865 assert!(gateway.whole());
866 assert_eq!(gateway.requests, 4);
867 // Down from what the sandbox said, or up: the gateway's figure.
868 assert_eq!(settled_cost(20_000, &gateway), (15_000, None));
869 assert_eq!(settled_cost(9_000, &gateway), (15_000, None));
870 }
871
872 #[test]
873 fn a_model_the_gateway_cannot_price_is_never_settled_down_to_nothing() {
874 let gateway = logs(&[
875 json!({ "cost": 0.002, "tokens_in": 100, "tokens_out": 10, "model": "claude-haiku-4-5" }),
876 json!({ "cost": 0, "tokens_in": 50_000, "tokens_out": 2_000, "model": "claude-new-1" }),
877 json!({ "tokens_in": 50_000, "tokens_out": 2_000, "model": "claude-new-1" }),
878 ]);
879 assert!(!gateway.whole());
880 assert_eq!((gateway.unpriced, gateway.unpriced_models.clone()), (2, vec!["claude-new-1".to_owned()]));
881 // The sandbox said $0.90: kept, not cut to the gateway's $0.002.
882 let (cost, why) = settled_cost(900_000, &gateway);
883 assert_eq!(cost, 900_000);
884 assert!(why.unwrap().contains("no price for 2 of its 3 requests (claude-new-1)"));
885 // A sandbox that reported less than the gateway priced: the gateway's.
886 assert_eq!(settled_cost(1_000, &gateway).0, 2_000);
887 }
888
889 #[test]
890 fn more_logs_than_were_read_never_settle_a_run_down() {
891 let mut gateway = logs(&[json!({ "cost": 1.0, "tokens_in": 1, "tokens_out": 1 })]);
892 gateway.complete = false;
893 let (cost, why) = settled_cost(3_000_000, &gateway);
894 assert_eq!(cost, 3_000_000);
895 assert!(why.unwrap().contains("more than 1 of its requests"));
896 }
897
898 #[test]
899 fn a_gateway_figure_over_the_report_cap_is_charged_in_full() {
900 // A sandbox's report is believed up to $100; the gateway's is not capped.
901 let gateway = logs(&[json!({ "cost": 140.0, "tokens_in": 1, "tokens_out": 1 })]);
902 assert_eq!(settled_cost(100_000_000, &gateway).0, 140_000_000);
903 assert_eq!(crate::charge_micros(140.0, 20), 120_000_000);
904 assert_eq!(crate::margin_on(140_000_000, 20), 168_000_000);
905 // Exactly cost plus the margin, rounded up, in whole micros (dollars
906 // as floats can come out a micro high), never under it.
907 for cost in [0_i64, 1, 7, 999, 123_457, 99_999_999] {
908 let exact = (cost * 120 + 99) / 100;
909 assert_eq!(crate::margin_on(cost, 20), exact, "{cost}");
910 assert!(crate::margin_on(cost, 20) * 100 >= cost * 120, "{cost}");
911 assert!(crate::charge_micros(cost as f64 / 1e6, 20) >= exact, "{cost}");
912 }
913 }
914
Prices keep themselves current with what g1t pays915 #[test]
The keeper reads Cloudflare as it really answers916 fn a_sandbox_second_is_its_memory_and_disk_and_the_cpu_it_uses() {
917 // An hour of sandboxes that kept a fifth of a vCPU busy.
918 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 look919 let micros =
920 sandbox_second_micros(usage, LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_VCPU_SECOND, LIST_DO_GB_SECOND).unwrap();
921 // 4 x 2.5 + 8 x 0.07 + 0.125 x 12.5 + 0.2 x 20 = 16.1225
922 assert!((micros - 16.1225).abs() < 1e-9, "{micros}");
923 // The Durable Object adds about 11% to the second it left out.
924 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 answers925 // Too little use to say anything.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look926 assert!(sandbox_second_micros(ContainerUsage { cpu_seconds: 1.0, memory_byte_seconds: GIB }, 1.0, 1.0, 1.0, 1.0).is_none());
927 }
928
929 #[test]
930 fn a_run_that_reports_its_cpu_is_priced_on_it() {
931 let base = sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND);
932 let vcpu = LIST_VCPU_SECOND * MICROS_PER_DOLLAR as f64;
933 // A 10-minute cargo build that kept its half vCPU busy throughout.
934 let heavy = run_cost(600, 300.0, base, vcpu);
935 assert!((heavy - (600.0 * 12.1225 + 300.0 * 20.0)).abs() < 1e-6);
936 // The same ten minutes, mostly idle, costs less.
937 let light = run_cost(600, 30.0, base, vcpu);
938 assert!(light < heavy);
939 // The average would have under-priced the heavy one.
940 let average = 600.0 * (base + 0.195 * vcpu);
941 assert!(average < heavy && average > light);
942 assert_eq!(run_cost(0, -1.0, base, vcpu), 0.0);
Fast pages, required checks on the branch, self-hosted runners, honest incidents943 // A larger machine's base: its memory and disk, not its CPU.
944 assert!((base_scale(SANDBOX_GIB, SANDBOX_DISK_GB) - 1.0).abs() < 1e-12);
945 assert!((base_scale(12.0, 20.0) - 2.72).abs() < 0.01, "{}", base_scale(12.0, 20.0));
946 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 answers947 }
948
949 #[test]
950 fn a_billed_rate_is_the_median_of_the_charged_days() {
951 let row = |quantity: f64, cost: f64| UsageRow {
952 period_start: String::new(),
953 period_end: String::new(),
954 service: "Containers / Container Memory".into(),
955 unit: "Count".into(),
956 quantity,
957 cost,
958 };
959 let rows = [row(100.0, 0.0), row(100.0, 0.0002), row(100.0, 0.00025), row(100.0, 0.00025)];
960 assert_eq!(billed_rate(&rows.iter().collect::<Vec<_>>()), Some(0.000_002_5));
961 assert_eq!(billed_rate(&[&row(5.0, 0.0)]), None);
962 }
963
964 #[test]
Prices keep themselves current with what g1t pays965 fn usage_rows_are_read_by_their_focus_names() {
966 let row = UsageRow::from_value(&json!({
967 "ServiceFamilyName": "Containers",
968 "ServiceName": "Memory",
The keeper reads Cloudflare as it really answers969 "PricingUnit": "GiB-seconds",
Prices keep themselves current with what g1t pays970 "PricingQuantity": "1200.5",
971 "ContractedCost": 0.003,
972 "ChargePeriodStart": "2026-10-01",
973 }))
974 .unwrap();
975 assert_eq!(row.service, "Containers / Memory");
976 assert_eq!(row.quantity, 1200.5);
977 assert_eq!(row.cost, 0.003);
978 assert!(UsageRow::from_value(&json!({ "nothing": 1 })).is_none());
979 }
980}

This file's history is long; its oldest lines are credited to the oldest commit read.