Skip to content
1,075 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 * * *";
Merge platform pause and the hourly usage watcher: staff can pause compute, schedules, indexing or renders for everyone, the watcher emails on a breach and is never blind quietly, and the models proxy holds each run to its cap (billing 0051, integrations 0006)37/// The quarter-hourly tick: settling, and once an hour the platform watch.
38pub(crate) const QUARTER_HOURLY: &str = "*/15 * * * *";
Prices keep themselves current with what g1t pays39
40/// A run is settled once its logs have had time to land.
41const SETTLE_AFTER_MS: u64 = 5 * 60 * 1000;
42/// A run with no gateway logs after this is left as reported.
43const GIVE_UP_AFTER_MS: u64 = 3 * 60 * 60 * 1000;
44/// A run never finished after this died without reporting.
45const ABANDONED_AFTER_MS: u64 = 3 * 60 * 60 * 1000;
46
47/// Where the keeper reads what g1t pays.
48pub(crate) struct Keeper {
49 /// `CLOUDFLARE_USAGE_TOKEN`: Billing, Account Analytics and AI Gateway,
50 /// read only.
51 token: Option<String>,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily52 /// What reads the bill for `costs`: `CLOUDFLARE_BILLING_TOKEN`
53 /// (Account: Billing Read and Account Analytics Read), or the usage
54 /// token, which has both.
55 billing_token: Option<String>,
Prices keep themselves current with what g1t pays56 account: String,
57 gateway: String,
58}
59
60impl Keeper {
61 pub(crate) fn from_env(env: &Env) -> Self {
62 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 daily63 let secret = |name: &str| env.secret(name).ok().map(|v| v.to_string()).filter(|v| !v.is_empty());
64 let token = secret("CLOUDFLARE_USAGE_TOKEN");
Prices keep themselves current with what g1t pays65 Keeper {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily66 billing_token: secret("CLOUDFLARE_BILLING_TOKEN").or_else(|| token.clone()),
67 token,
Prices keep themselves current with what g1t pays68 account: var("CLOUDFLARE_ACCOUNT_ID"),
69 gateway: var("AI_GATEWAY_ID"),
70 }
71 }
72
73 async fn send(&self, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
74 let Some(token) = &self.token else {
75 return Err(worker::Error::RustError("no CLOUDFLARE_USAGE_TOKEN".into()));
76 };
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily77 send_with(token, method, url, body).await
78 }
79
80 /// Whether Cloudflare's bill can be read.
81 pub(crate) fn can_read_bill(&self) -> bool {
82 self.billing_token.is_some() && !self.account.is_empty()
83 }
84
85 fn billing_token(&self) -> Result<&str> {
86 self.billing_token
87 .as_deref()
88 .ok_or_else(|| worker::Error::RustError("no CLOUDFLARE_BILLING_TOKEN or CLOUDFLARE_USAGE_TOKEN".into()))
89 }
90
91 /// Billable usage from `from` to `to` (dates), as Cloudflare answers it.
92 pub(crate) async fn billable_usage_body(&self, from: &str, to: &str) -> Result<Value> {
93 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 pays94 }
95
Costs: Cloudflare's subscriptions read from Cloudflare each day, the estimate only until then; sudo's costs split into Costs & margin and Bill & pricing96 /// The account's subscriptions (Workers Paid, add-ons), as Cloudflare
97 /// answers them. Needs Account: Billing Read.
98 pub(crate) async fn subscriptions_body(&self) -> Result<Value> {
99 send_with(self.billing_token()?, Method::Get, &self.api("/subscriptions"), None).await
100 }
101
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily102 /// A GraphQL Analytics query, as Cloudflare answers it, errors and all.
103 pub(crate) async fn graphql(&self, body: Value) -> Result<Value> {
104 send_with(self.billing_token()?, Method::Post, "https://api.cloudflare.com/client/v4/graphql", Some(body)).await
105 }
106
107 pub(crate) fn account(&self) -> &str {
108 &self.account
109 }
110
Prices keep themselves current with what g1t pays111 fn api(&self, path: &str) -> String {
112 format!("https://api.cloudflare.com/client/v4/accounts/{}{path}", self.account)
113 }
114
Merge branch 'worktree-agent-a633ac0f7f66d419d'115 /// AI Gateway's id, empty when there is none.
116 pub(crate) fn gateway(&self) -> &str {
117 &self.gateway
118 }
119
Billing: AI Gateway's analytics are read with the token that can see them, and a gateway that priced nothing is said120 /// A GraphQL query over AI Gateway's analytics: with the keeper's token
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises121 /// (AI Gateway Read) first, and on failure with the bill's. A token
122 /// without Account Analytics Read gets an error ("caller does not hold
123 /// any of the required permissions for this dataset"); when the answer
124 /// has no rows, `gateway_visible` tells a token that cannot see the
125 /// gateway from a gateway nothing went through.
Billing: AI Gateway's analytics are read with the token that can see them, and a gateway that priced nothing is said126 pub(crate) async fn gateway_graphql(&self, body: Value) -> Result<Value> {
127 let Some(token) = &self.token else {
128 return self.graphql(body).await;
129 };
130 match send_with(token, Method::Post, "https://api.cloudflare.com/client/v4/graphql", Some(body.clone())).await {
Merge branch 'worktree-agent-a633ac0f7f66d419d'131 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 said132 Err(error) => match &self.billing_token {
133 Some(billing) if billing != token => self.graphql(body).await,
Merge branch 'worktree-agent-a633ac0f7f66d419d'134 _ => Err(error),
135 },
136 }
137 }
138
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises139 /// Whether the token AI Gateway's analytics are read with can see the
140 /// gateway: the REST API answers 403 for a token without AI Gateway
141 /// Read and 404 for a gateway id that is not there. None when the
142 /// answer says neither (Cloudflare down, no token).
143 pub(crate) async fn gateway_visible(&self) -> Option<bool> {
144 let token = self.token.as_deref().or(self.billing_token.as_deref())?;
145 match send_with(token, Method::Get, &self.api(&format!("/ai-gateway/gateways/{}", self.gateway)), None).await {
146 Ok(_) => Some(true),
147 Err(error) => refused(&error.to_string()).then_some(false),
148 }
149 }
150
Merge branch 'worktree-agent-a633ac0f7f66d419d'151 /// What AI Gateway priced a session's requests at, and how many there
152 /// were, with the requests it had no price for.
153 async fn session_cost(&self, session: &str) -> Result<SessionCost> {
154 let mut total = SessionCost { complete: true, ..SessionCost::default() };
155 for page in 1..=MAX_LOG_PAGES {
The keeper reads Cloudflare as it really answers156 // The filter goes as URL-encoded JSON; the bracket form is
157 // ignored, and would sum every log there is. Session ids are
158 // [a-z0-9_], which need no escaping inside it.
159 let filter = format!(
160 "%5B%7B%22key%22%3A%22metadata.value%22%2C%22operator%22%3A%22eq%22%2C%22value%22%3A%5B%22{session}%22%5D%7D%5D"
161 );
Prices keep themselves current with what g1t pays162 let url = self.api(&format!(
The keeper reads Cloudflare as it really answers163 "/ai-gateway/gateways/{}/logs?per_page=50&page={page}&filters={filter}",
Prices keep themselves current with what g1t pays164 self.gateway
165 ));
166 let body = self.send(Method::Get, &url, None).await?;
167 let logs = body["result"].as_array().cloned().unwrap_or_default();
168 for log in &logs {
Merge branch 'worktree-agent-a633ac0f7f66d419d'169 total.add(log);
Prices keep themselves current with what g1t pays170 }
171 if logs.len() < 50 {
Merge branch 'worktree-agent-a633ac0f7f66d419d'172 return Ok(total);
Prices keep themselves current with what g1t pays173 }
174 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'175 // More logs than were read: what was read is less than the run.
176 total.complete = false;
177 Ok(total)
Prices keep themselves current with what g1t pays178 }
179
The keeper reads Cloudflare as it really answers180 /// The account's billable usage, one row per service per day, as
181 /// Cloudflare reports it.
Prices keep themselves current with what g1t pays182 async fn billable_usage(&self, from: &str, to: &str) -> Result<Vec<UsageRow>> {
183 let body = self
The keeper reads Cloudflare as it really answers184 .send(Method::Get, &self.api(&format!("/billable-usage?from={from}&to={to}")), None)
Prices keep themselves current with what g1t pays185 .await?;
186 let rows = body["result"].as_array().cloned().unwrap_or_default();
187 Ok(rows.iter().filter_map(UsageRow::from_value).collect())
188 }
189
The keeper reads Cloudflare as it really answers190 /// What g1t's containers used from `since` to `until` (dates), as
191 /// Cloudflare bills it: memory in byte-seconds, and CPU seconds.
192 async fn container_usage(&self, since: &str, until: &str) -> Result<ContainerUsage> {
193 let query = "query ($account: String!, $since: Date!, $until: Date!) {
Prices keep themselves current with what g1t pays194 viewer { accounts(filter: { accountTag: $account }) {
The keeper reads Cloudflare as it really answers195 containersUsageAdaptiveGroups(limit: 1000, filter: { date_geq: $since, date_leq: $until }) {
196 sum { cpuTimeSec allocatedMemory }
Prices keep themselves current with what g1t pays197 }
198 } }
199 }";
200 let body = self
201 .send(
202 Method::Post,
203 "https://api.cloudflare.com/client/v4/graphql",
204 Some(json!({ "query": query, "variables": { "account": self.account, "since": since, "until": until } })),
205 )
206 .await?;
The keeper reads Cloudflare as it really answers207 let groups = body["data"]["viewer"]["accounts"][0]["containersUsageAdaptiveGroups"]
Prices keep themselves current with what g1t pays208 .as_array()
209 .cloned()
210 .unwrap_or_default();
The keeper reads Cloudflare as it really answers211 Ok(groups.iter().fold(ContainerUsage::default(), |total, g| ContainerUsage {
212 cpu_seconds: total.cpu_seconds + g["sum"]["cpuTimeSec"].as_f64().unwrap_or(0.0),
213 memory_byte_seconds: total.memory_byte_seconds + g["sum"]["allocatedMemory"].as_f64().unwrap_or(0.0),
214 }))
Prices keep themselves current with what g1t pays215 }
216}
217
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises218/// Whether an error from `send_with` is Cloudflare saying no to the token
219/// (401, 403) or that there is no such thing for it (404), rather than
220/// failing.
221pub(crate) fn refused(error: &str) -> bool {
222 ["Cloudflare answered 401", "Cloudflare answered 403", "Cloudflare answered 404"].iter().any(|s| error.contains(s))
223}
224
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily225/// A request to Cloudflare's API with a bearer token; anything but 200 is
226/// an error with what Cloudflare said.
227async fn send_with(token: &str, method: Method, url: &str, body: Option<Value>) -> Result<Value> {
228 let headers = Headers::new();
229 headers.set("authorization", &format!("Bearer {token}"))?;
230 headers.set("content-type", "application/json")?;
231 let mut init = RequestInit::new();
232 init.with_method(method).with_headers(headers);
233 if let Some(body) = body {
234 init.with_body(Some(body.to_string().into()));
235 }
236 let mut response = Fetch::Request(Request::new_with_init(url, &init)?).send().await?;
237 let status = response.status_code();
238 let value: Value = response.json().await.unwrap_or(Value::Null);
239 if status != 200 {
240 return Err(worker::Error::RustError(format!("Cloudflare answered {status}: {value}")));
241 }
242 Ok(value)
243}
244
The keeper reads Cloudflare as it really answers245#[derive(Debug, Default, Clone, Copy)]
246pub(crate) struct ContainerUsage {
247 cpu_seconds: f64,
248 memory_byte_seconds: f64,
249}
250
251/// g1t's sandboxes: Containers' standard-1, half a vCPU, 4 GiB, 8 GB disk.
252const SANDBOX_GIB: f64 = 4.0;
253const SANDBOX_DISK_GB: f64 = 8.0;
254const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look255/// The Durable Object behind each container is billed for as long as the
256/// container runs, at 128 MB.
257const SANDBOX_DO_GB: f64 = 0.125;
The keeper reads Cloudflare as it really answers258
259/// Cloudflare's published Containers rates, in dollars, used for any rate
260/// the bill does not show yet (while usage is inside the included amount).
261const LIST_MEMORY_GIB_SECOND: f64 = 0.000_002_5;
262const LIST_DISK_GB_SECOND: f64 = 0.000_000_07;
263const LIST_VCPU_SECOND: f64 = 0.000_02;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look264/// Durable Objects duration: $12.50 per million GB-seconds.
265const LIST_DO_GB_SECOND: f64 = 0.000_012_5;
The keeper reads Cloudflare as it really answers266
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look267/// What one second of a sandbox costs whatever it does, in millionths of a
268/// dollar: its memory and disk, and the Durable Object behind it, for the
269/// whole second. CPU is billed only while busy, on top.
270pub(crate) fn sandbox_base_micros(memory: f64, disk: f64, durable_object: f64) -> f64 {
271 (SANDBOX_GIB * memory + SANDBOX_DISK_GB * disk + SANDBOX_DO_GB * durable_object) * MICROS_PER_DOLLAR as f64
272}
273
274/// What one second of a sandbox costs on average, in millionths of a
275/// dollar: its base, and the CPU sandboxes actually use per second of
276/// running. Runs that report their own CPU are priced on it instead (see
277/// `run_cost`).
278pub(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 answers279 let instance_seconds = usage.memory_byte_seconds / (SANDBOX_GIB * GIB);
280 if instance_seconds < 3600.0 {
281 return None;
282 }
283 let cpu_share = usage.cpu_seconds / instance_seconds;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look284 Some(sandbox_base_micros(memory, disk, durable_object) + cpu_share * vcpu * MICROS_PER_DOLLAR as f64)
285}
286
Fast pages, required checks on the branch, self-hosted runners, honest incidents287/// How much more a second of a larger machine's memory and disk (and the
288/// Durable Object behind it) costs than the standard sandbox's, at
289/// Cloudflare's list rates: 1 for the standard machine.
290pub(crate) fn base_scale(memory_gib: f64, disk_gb: f64) -> f64 {
291 let base = |memory: f64, disk: f64| memory * LIST_MEMORY_GIB_SECOND + disk * LIST_DISK_GB_SECOND + SANDBOX_DO_GB * LIST_DO_GB_SECOND;
292 base(memory_gib, disk_gb) / base(SANDBOX_GIB, SANDBOX_DISK_GB)
293}
294
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look295/// What a run that reported its own CPU cost g1t: its base for every
296/// second, and its vCPU-seconds at the vCPU rate.
297pub(crate) fn run_cost(seconds: i64, cpu_seconds: f64, base_per_second: f64, per_vcpu_second: f64) -> f64 {
298 seconds.max(0) as f64 * base_per_second + cpu_seconds.max(0.0) * per_vcpu_second
The keeper reads Cloudflare as it really answers299}
300
301/// A unit's marginal rate from the bill: the median, over the days that
302/// were charged, of cost over quantity. None while nothing was charged.
303pub(crate) fn billed_rate(rows: &[&UsageRow]) -> Option<f64> {
304 let mut rates: Vec<f64> = rows
305 .iter()
306 .filter(|r| r.cost > 0.0 && r.quantity > 0.0)
307 .map(|r| r.cost / r.quantity)
308 .collect();
309 if rates.is_empty() {
310 return None;
311 }
312 rates.sort_by(f64::total_cmp);
313 Some(rates[rates.len() / 2])
314}
315
Prices keep themselves current with what g1t pays316/// One line of Cloudflare's billable usage.
317#[derive(Debug, Clone)]
318pub(crate) struct UsageRow {
319 period_start: String,
320 period_end: String,
321 service: String,
322 unit: String,
323 quantity: f64,
324 cost: f64,
325}
326
327impl UsageRow {
328 /// Read leniently: the API is new, and its field names are FOCUS's.
329 fn from_value(row: &Value) -> Option<Self> {
330 let text = |keys: &[&str]| keys.iter().find_map(|k| row[*k].as_str()).unwrap_or_default().to_owned();
331 let number = |keys: &[&str]| {
332 keys.iter()
333 .find_map(|k| row[*k].as_f64().or_else(|| row[*k].as_str().and_then(|s| s.parse().ok())))
334 .unwrap_or(0.0)
335 };
336 let service = text(&["ServiceName", "service_name", "service"]);
337 if service.is_empty() {
338 return None;
339 }
340 let family = text(&["ServiceFamilyName", "service_family_name"]);
341 Some(UsageRow {
342 period_start: text(&["ChargePeriodStart", "charge_period_start"]),
343 period_end: text(&["ChargePeriodEnd", "charge_period_end"]),
344 service: if family.is_empty() { service } else { format!("{family} / {service}") },
The keeper reads Cloudflare as it really answers345 unit: text(&["PricingUnit", "ConsumedUnit", "consumed_unit"]),
Prices keep themselves current with what g1t pays346 quantity: number(&["PricingQuantity", "ConsumedQuantity", "pricing_quantity"]),
The keeper reads Cloudflare as it really answers347 // What g1t pays; list price if nothing was contracted.
348 cost: Some(number(&["ContractedCost", "BilledCost", "contracted_cost"]))
349 .filter(|cost| *cost > 0.0)
350 .unwrap_or_else(|| number(&["ListCost", "list_cost"])),
Prices keep themselves current with what g1t pays351 })
352 }
353}
354
355#[derive(Deserialize)]
356struct PriceRow {
357 meter: String,
358 title: String,
359 unit: String,
360 cost_micros: f64,
361 markup_percent: u32,
362 source: String,
363 checked_at: Option<String>,
364 updated_at: String,
365}
366
367#[derive(Deserialize)]
368struct ChangeRow {
369 meter: String,
370 old_cost_micros: f64,
371 new_cost_micros: f64,
372 markup_percent: u32,
Prices are what g1t pays plus 20%, from the first second373 old_markup_percent: Option<u32>,
Prices keep themselves current with what g1t pays374 reason: String,
375 created_at: String,
376}
377
378#[derive(Deserialize)]
379struct Unsettled {
380 id: String,
381 workspace: String,
382 repo: String,
383 number: u32,
384 task: String,
385 model: String,
386 token_hash: String,
387 billed_to: Option<String>,
388 session_id: String,
389 created_at: String,
390 finished_at: Option<String>,
391}
392
393#[derive(Deserialize)]
394struct Charged {
395 cost_micros: Option<i64>,
396 description: String,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put397 amount_micros: i64,
398}
399
400/// What a settled run's correction comes to, from the charges at the
401/// reported and the gateway's cost and what the workspace was charged at
402/// first. A charge up is drawn down like any charge; a charge down is
403/// given back only up to what the workspace paid, since what a credit or
404/// a pool paid was never the workspace's money.
405pub(crate) fn correction(reported_charge: i64, gateway_charge: i64, first_charged: i64) -> i64 {
406 let delta = gateway_charge - reported_charge;
407 if delta >= 0 { delta } else { delta.max(-first_charged.max(0)) }
Prices keep themselves current with what g1t pays408}
409
Merge branch 'worktree-agent-a633ac0f7f66d419d'410/// A session's logs are read 50 at a time, up to this many pages.
411const MAX_LOG_PAGES: u32 = 40;
412
413/// What AI Gateway's logs say a session cost.
414#[derive(Clone, Debug, Default, PartialEq)]
415pub(crate) struct SessionCost {
416 /// What the gateway priced the requests at, in dollars.
417 pub cost_usd: f64,
418 pub requests: u32,
419 /// Requests that used tokens but that the gateway put no price on: a
420 /// model it has no price for. Their cost is not in `cost_usd`.
421 pub unpriced: u32,
422 /// The models of those, for the statement and the drift.
423 pub unpriced_models: Vec<String>,
424 /// False when there were more logs than were read.
425 pub complete: bool,
426}
427
428impl SessionCost {
429 /// Adds one log, read leniently: `cost` in dollars, `tokens_in` and
430 /// `tokens_out`, `cached` for an answer from the gateway's own cache
431 /// (which costs nothing).
432 pub(crate) fn add(&mut self, log: &Value) {
433 self.requests += 1;
434 let number = |key: &str| log[key].as_f64().or_else(|| log[key].as_str().and_then(|s| s.parse().ok()));
435 let cost = number("cost").filter(|c| c.is_finite() && *c > 0.0);
436 let tokens = number("tokens_in").unwrap_or(0.0) + number("tokens_out").unwrap_or(0.0);
437 let cached = log["cached"].as_bool().unwrap_or(false);
438 match cost {
439 Some(cost) => self.cost_usd += cost,
440 None if tokens > 0.0 && !cached => {
441 self.unpriced += 1;
442 let model = log["model"].as_str().unwrap_or("an unnamed model").to_owned();
443 if !self.unpriced_models.contains(&model) {
444 self.unpriced_models.push(model);
445 }
446 }
447 None => {}
448 }
449 }
450
451 /// Whether the gateway's figure is the whole of what the run cost.
452 pub(crate) fn whole(&self) -> bool {
453 self.complete && self.unpriced == 0
454 }
455}
456
457/// The cost a run is settled at, in millionths: the gateway's figure when
458/// it priced every request; otherwise (a model it has no price for, or
459/// more logs than were read) never less than the sandbox reported, since
460/// the gateway's sum is then short of what the provider bills. With a
461/// reason for the statement and the drift when it is not the gateway's
462/// figure alone.
463pub(crate) fn settled_cost(reported_micros: i64, gateway: &SessionCost) -> (i64, Option<String>) {
464 // Not held to MAX_RUN_COST_USD: the gateway's figure is trusted.
465 let priced = if gateway.cost_usd.is_finite() { (gateway.cost_usd.max(0.0) * MICROS_PER_DOLLAR as f64).ceil() as i64 } else { 0 };
466 if gateway.whole() {
467 return (priced, None);
468 }
469 let mut why = Vec::new();
470 if gateway.unpriced > 0 {
471 why.push(format!(
472 "AI Gateway has no price for {} of its {} requests ({})",
473 gateway.unpriced,
474 gateway.requests,
475 gateway.unpriced_models.join(", ")
476 ));
477 }
478 if !gateway.complete {
479 why.push(format!("more than {} of its requests were logged", gateway.requests));
480 }
481 (priced.max(reported_micros.max(0)), Some(why.join("; ")))
482}
483
Prices keep themselves current with what g1t pays484fn ms(timestamp: &str) -> u64 {
485 // RFC 3339 in UTC, as g1t writes them.
486 worker::js_sys::Date::parse(timestamp) as u64
487}
488
489impl Billing {
490 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 index491 // Three reads at once; the plans are priced from the rows already
492 // read, not one query per meter (status.g1t.sh times this call).
493 let (prices, changes, coming) = futures_util::future::join3(
494 async { self.db.prepare("SELECT * FROM prices ORDER BY rowid").all().await?.results::<PriceRow>() },
495 async {
496 self.db
497 .prepare("SELECT * FROM price_changes ORDER BY created_at DESC LIMIT 20")
498 .all()
499 .await?
500 .results::<ChangeRow>()
501 },
502 // Changes still to come first, so a rise is seen before it is charged.
503 self.coming_changes(),
504 )
505 .await;
506 let (prices, changes, coming) = (prices?, changes?, coming?);
Usage, Billing settings and prepaid AI credit; fixes from the UX audit507 let model_markup = prices.iter().find(|row| row.meter == "agent_models").map_or(self.margin_percent, |row| row.markup_percent);
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 index508 let book: std::collections::BTreeMap<&str, f64> = prices
509 .iter()
510 .map(|row| (row.meter.as_str(), Price::price_for(row.cost_micros, row.markup_percent)))
511 .collect();
Merge Stripe Tax, the card fee on card payments, and one free workspace per person512 // With the card fee on top of each monthly price, as it is charged.
513 let card_fee = self.card_fee().await?;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar514 let plans: Vec<_> = g1t_contracts::billing::Feature::ALL
515 .iter()
Merge Stripe Tax, the card fee on card payments, and one free workspace per person516 .map(|feature| {
517 let mut plan = match feature {
518 g1t_contracts::billing::Feature::Security => crate::features::security_plan_at(&book),
519 _ => self.plan_at(&book),
520 };
521 plan.card_fee_cents = crate::tax::fee_for(i64::from(plan.monthly_cents), &card_fee) as u32;
522 plan
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar523 })
524 .collect();
Prices keep themselves current with what g1t pays525 Ok(PriceBook {
526 prices: prices
527 .into_iter()
528 .map(|row| Price {
529 price_micros: Price::price_for(row.cost_micros, row.markup_percent),
530 meter: row.meter,
531 title: row.title,
532 unit: row.unit,
533 cost_micros: row.cost_micros,
534 markup_percent: row.markup_percent,
535 source: row.source,
536 checked_at: row.checked_at,
537 updated_at: row.updated_at,
538 })
539 .collect(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily540 changes: coming
Prices keep themselves current with what g1t pays541 .into_iter()
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily542 .chain(changes.into_iter().map(|row| PriceChange {
Prices keep themselves current with what g1t pays543 meter: row.meter,
544 old_cost_micros: row.old_cost_micros,
545 new_cost_micros: row.new_cost_micros,
546 markup_percent: row.markup_percent,
Prices are what g1t pays plus 20%, from the first second547 old_markup_percent: row.old_markup_percent,
Prices keep themselves current with what g1t pays548 reason: row.reason,
549 created_at: row.created_at,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily550 effective_at: None,
551 }))
Prices keep themselves current with what g1t pays552 .collect(),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit553 // The markup on models' provider price: the price book's
554 // `agent_models` (none from 2026-10-08).
555 model_margin_percent: model_markup,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily556 plans,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put557 free: Some(g1t_contracts::billing::FreeTier {
558 trial_workspace_micros: if self.trials_on { self.plans.trial_workspace_micros } else { 0 },
559 trial_monthly_pool_micros: if self.trials_on { self.plans.trial_monthly_pool_micros } else { 0 },
560 oss_pool_micros: self.plans.oss_pool_micros,
561 oss_repo_micros: self.plans.oss_repo_micros,
562 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 sudo563 audit_retention_days: self.plans.free_audit_days,
564 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 put565 min_charge_micros: self.plans.min_charge_micros,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look566 git_operations_included: self.plans.git_included,
567 paid_start_ceiling_micros: self.plans.paid_start_micros,
568 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 put569 }),
Prices keep themselves current with what g1t pays570 })
571 }
572
The keeper reads Cloudflare as it really answers573 /// Whether the costs have never been checked against Cloudflare's bill.
574 pub(crate) async fn never_checked(&self) -> Result<bool> {
575 Ok(self
576 .db
577 .prepare("SELECT meter FROM prices WHERE checked_at IS NOT NULL LIMIT 1")
578 .first::<Value>(None)
579 .await?
580 .is_none())
581 }
582
Prices keep themselves current with what g1t pays583 /// A meter's cost and price per unit, from the book.
584 pub(crate) async fn price(&self, meter: &str) -> Result<Option<(f64, f64)>> {
585 #[derive(Deserialize)]
586 struct Row {
587 cost_micros: f64,
588 markup_percent: u32,
589 }
590 Ok(self
591 .db
592 .prepare("SELECT cost_micros, markup_percent FROM prices WHERE meter = ?")
593 .bind(&[meter.into()])?
594 .first::<Row>(None)
595 .await?
596 .map(|row| (row.cost_micros, Price::price_for(row.cost_micros, row.markup_percent))))
597 }
598
599 /// Corrects finished runs to what AI Gateway priced them at, and
600 /// charges runs whose sandbox died before reporting.
601 pub(crate) async fn settle_runs(&self, keeper: &Keeper) -> Result<()> {
602 if keeper.token.is_none() || keeper.gateway.is_empty() {
603 return Ok(());
604 }
605 let now = now_ms();
606 let runs = self
607 .db
608 .prepare(
609 "SELECT id, workspace, repo, number, task, model, token_hash, billed_to, session_id, created_at, finished_at
610 FROM runs
Merge branch 'model-routing'611 WHERE session_id IS NOT NULL AND settled_at IS NULL AND COALESCE(billed_to, 'g1t') = 'g1t'
Prices keep themselves current with what g1t pays612 AND ((finished_at IS NOT NULL AND finished_at < ?1) OR created_at < ?2)
613 ORDER BY created_at LIMIT 10",
614 )
615 .bind(&[rfc3339(now - SETTLE_AFTER_MS).into(), rfc3339(now - ABANDONED_AFTER_MS).into()])?
616 .all()
617 .await?
618 .results::<Unsettled>()?;
619 for run in runs {
Merge branch 'worktree-agent-a633ac0f7f66d419d'620 let gateway = match keeper.session_cost(&run.session_id).await {
Prices keep themselves current with what g1t pays621 Ok(found) => found,
622 Err(error) => {
623 worker::console_error!("could not read gateway logs for {}: {error}", run.id);
624 continue;
625 }
626 };
627 let since = ms(run.finished_at.as_deref().unwrap_or(&run.created_at));
Merge branch 'worktree-agent-a633ac0f7f66d419d'628 if gateway.requests == 0 && now.saturating_sub(since) < GIVE_UP_AFTER_MS {
Prices keep themselves current with what g1t pays629 continue;
630 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'631 self.settle(&run, &gateway).await?;
Prices keep themselves current with what g1t pays632 }
633 Ok(())
634 }
635
Merge branch 'model-routing'636 /// Closes runs on a workspace's own model provider: none is on g1t's
637 /// gateway, so nothing is corrected, but tokens the proxy counted after
638 /// the run reported, or for a sandbox that died before reporting, are
639 /// charged their agent rate now. Needs no gateway token.
640 pub(crate) async fn settle_own_runs(&self) -> Result<()> {
641 #[derive(Deserialize)]
642 struct Own {
643 id: String,
644 workspace: String,
645 repo: String,
646 number: u32,
647 task: String,
648 model: String,
649 token_hash: String,
650 billed_to: Option<String>,
651 }
652 let now = now_ms();
653 let runs = self
654 .db
655 .prepare(
656 "SELECT id, workspace, repo, number, task, model, token_hash, billed_to
657 FROM runs
658 WHERE billed_to = 'workspace' AND session_id IS NOT NULL AND settled_at IS NULL
659 AND ((finished_at IS NOT NULL AND finished_at < ?1) OR created_at < ?2)
660 ORDER BY created_at LIMIT 25",
661 )
662 .bind(&[rfc3339(now - SETTLE_AFTER_MS).into(), rfc3339(now - ABANDONED_AFTER_MS).into()])?
663 .all()
664 .await?
665 .results::<Own>()?;
666 for run in runs {
667 let settled_at = rfc3339(now_ms());
668 let claimed = self
669 .db
670 .prepare(
671 "UPDATE runs SET settled_at = ?1, finished_at = COALESCE(finished_at, ?1)
672 WHERE id = ?2 AND settled_at IS NULL RETURNING id",
673 )
674 .bind(&[settled_at.as_str().into(), run.id.as_str().into()])?
675 .first::<Value>(None)
676 .await?;
677 if claimed.is_none() {
678 continue;
679 }
680 let row = RunRow {
681 workspace: run.workspace,
682 repo: run.repo,
683 number: run.number,
684 task: run.task,
685 model: run.model,
686 token_hash: run.token_hash,
687 billed_to: run.billed_to,
688 };
689 self.charge_agent_rate(&run.id, &row, None).await?;
690 }
691 Ok(())
692 }
693
Merge branch 'worktree-agent-a633ac0f7f66d419d'694 async fn settle(&self, run: &Unsettled, gateway: &SessionCost) -> Result<()> {
695 let requests = gateway.requests;
Prices keep themselves current with what g1t pays696 let row = RunRow {
697 workspace: run.workspace.clone(),
698 repo: run.repo.clone(),
699 number: run.number,
700 task: run.task.clone(),
701 model: run.model.clone(),
702 token_hash: run.token_hash.clone(),
703 billed_to: run.billed_to.clone(),
704 };
705 let charged = self
706 .db
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put707 .prepare("SELECT cost_micros, description, amount_micros FROM ledger WHERE reference = ?")
Prices keep themselves current with what g1t pays708 .bind(&[run.id.as_str().into()])?
709 .first::<Charged>(None)
710 .await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'711 let reported = charged.as_ref().and_then(|c| c.cost_micros).unwrap_or(0);
712 // The gateway's figure; never under what the sandbox reported when
713 // the gateway could not price all of it (see `settled_cost`).
714 let (gateway_micros, short) = settled_cost(reported, gateway);
Billing accounts, terms and enterprises; g1t is no longer free715 let terms = self.terms_of(&run.workspace).await?;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit716 // Models at the price book's markup on the provider's price
717 // (`agent_models`), as `finish_run` charges them.
718 let markup = self.model_markup().await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'719 // A cost's charge on the account's terms, and what a discount gave
Usage, Billing settings and prepaid AI credit; fixes from the UX audit720 // below cost plus the markup (counted as given, see `charged`).
Prices keep themselves current with what g1t pays721 let charge_for = |micros: i64| {
Usage, Billing settings and prepaid AI credit; fixes from the UX audit722 if self.free { (0, 0) } else { terms.discounted(crate::margin_on(micros, markup)) }
Prices keep themselves current with what g1t pays723 };
724 let settled_at = rfc3339(now_ms());
725 // Claim it, so two crons never settle it twice.
726 let claimed = self
727 .db
Merge branch 'worktree-agent-a633ac0f7f66d419d'728 .prepare(
729 "UPDATE runs SET settled_at = ?, gateway_cost_micros = ?, gateway_note = ?, finished_at = COALESCE(finished_at, ?)
730 WHERE id = ? AND settled_at IS NULL RETURNING id",
731 )
Prices keep themselves current with what g1t pays732 .bind(&[
733 settled_at.as_str().into(),
734 (gateway_micros as f64).into(),
Merge branch 'worktree-agent-a633ac0f7f66d419d'735 short.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
Prices keep themselves current with what g1t pays736 settled_at.as_str().into(),
737 run.id.as_str().into(),
738 ])?
739 .first::<Value>(None)
740 .await?;
741 if claimed.is_none() || requests == 0 {
742 return Ok(());
743 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit744 // Tokens counted after the run reported are charged their agent
745 // rate now (ai.rs).
Merge branch 'model-routing'746 self.charge_agent_rate(&run.id, &row, None).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'747 if let Some(why) = &short {
748 worker::console_warn!("run {} settled at no less than reported: {why}", run.id);
749 }
750 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 pays751 let free_note = if self.free { " (free while g1t is being built out)" } else { "" };
752 match charged {
753 // Never reported: charged now, from the gateway's figure.
754 None => {
Merge branch 'worktree-agent-a633ac0f7f66d419d'755 let (charge, discount) = charge_for(gateway_micros);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look756 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 put757 let drawn = self.draw(&run.workspace, charge, &settled_at[..7], &eligible).await?;
Prices keep themselves current with what g1t pays758 let description = format!(
Merge branch 'worktree-agent-a633ac0f7f66d419d'759 "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 put760 run.repo,
761 run.number,
762 drawn.note()
Prices keep themselves current with what g1t pays763 );
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put764 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 pays765 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put766 self.record_drawn(&run.id, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'767 self.record_discount(&run.id, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays768 self.count_spend(&run.workspace, gateway_micros, charge - drawn.total(), &drawn).await;
Prices keep themselves current with what g1t pays769 }
770 Some(charged) => {
771 let delta = gateway_micros - reported;
772 if delta == 0 {
773 return Ok(());
774 }
Merge branch 'worktree-agent-a633ac0f7f66d419d'775 let ((was, was_given), (now, now_given)) = (charge_for(reported), charge_for(gateway_micros));
776 let change = correction(was, now, -charged.amount_micros);
777 // What the discount gives moves with the charge.
778 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 put779 // A charge up is paid for like any other charge.
780 let drawn = if change > 0 {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look781 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 put782 self.draw(&run.workspace, change, &settled_at[..7], &eligible).await?
783 } else {
784 crate::credits::Drawn::default()
785 };
Prices keep themselves current with what g1t pays786 let description = format!(
Merge branch 'worktree-agent-a633ac0f7f66d419d'787 "Correction to “{}”: AI Gateway priced its {requests} model requests at {}, not {}{short_note}{}",
Prices keep themselves current with what g1t pays788 charged.description,
789 crate::features::dollars(gateway_micros),
790 crate::features::dollars(reported),
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put791 drawn.note(),
Prices keep themselves current with what g1t pays792 );
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put793 let reference = format!("{}/settled", run.id);
Prices keep themselves current with what g1t pays794 self.enter(
795 &run.workspace,
796 EntryKind::Usage,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put797 -(change - drawn.total()),
Prices keep themselves current with what g1t pays798 &description,
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put799 &reference,
Prices keep themselves current with what g1t pays800 Some(&row),
801 Some(delta),
802 None,
803 None,
804 )
805 .await?;
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put806 self.record_drawn(&reference, &drawn).await?;
Merge branch 'worktree-agent-a633ac0f7f66d419d'807 self.record_discount(&reference, discount).await?;
Spend caps: a monthly budget for comped workspaces and a daily breaker on what g1t pays808 self.count_spend(&run.workspace, delta, change - drawn.total(), &drawn).await;
Prices keep themselves current with what g1t pays809 }
810 }
811 Ok(())
812 }
813
814 /// Checks each cost against what Cloudflare billed this month, and
815 /// moves the ones that changed.
816 pub(crate) async fn reconcile(&self, keeper: &Keeper) -> Result<()> {
817 if keeper.token.is_none() {
818 return Ok(());
819 }
820 let now = rfc3339(now_ms());
821 let today = &now[..10];
The keeper reads Cloudflare as it really answers822 let since = rfc3339(now_ms() - 30 * 24 * 60 * 60 * 1000);
823 let rows = keeper.billable_usage(&since[..10], today).await?;
Prices keep themselves current with what g1t pays824 for row in &rows {
825 self.db
826 .prepare(
827 "INSERT INTO cloudflare_usage (period_start, period_end, service, unit, quantity, cost_usd, fetched_at)
828 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
829 ON CONFLICT (period_start, service, unit) DO UPDATE SET
830 period_end = ?2, quantity = ?5, cost_usd = ?6, fetched_at = ?7",
831 )
832 .bind(&[
833 row.period_start.as_str().into(),
834 row.period_end.as_str().into(),
835 row.service.as_str().into(),
836 row.unit.as_str().into(),
837 row.quantity.into(),
838 row.cost.into(),
839 now.as_str().into(),
840 ])?
841 .run()
842 .await?;
843 }
844
The keeper reads Cloudflare as it really answers845 let named = |words: &[&str]| -> Vec<&UsageRow> {
Prices keep themselves current with what g1t pays846 rows.iter()
The keeper reads Cloudflare as it really answers847 .filter(|r| {
848 let service = r.service.to_lowercase();
849 words.iter().all(|word| service.contains(word))
850 })
851 .collect()
Prices keep themselves current with what g1t pays852 };
853
The keeper reads Cloudflare as it really answers854 // Containers: each resource at what the bill shows it costs, or
855 // the published rate while the included amount still covers it,
856 // over how much CPU g1t's sandboxes really use per second.
857 let memory = billed_rate(&named(&["container memory"]));
858 let disk = billed_rate(&named(&["container disk"]));
859 let vcpu = billed_rate(&named(&["container vcpu"]));
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look860 let durable_object = billed_rate(&named(&["durable objects", "duration"]));
The keeper reads Cloudflare as it really answers861 let usage = keeper.container_usage(&since[..10], today).await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look862 let rates = (
The keeper reads Cloudflare as it really answers863 memory.unwrap_or(LIST_MEMORY_GIB_SECOND),
864 disk.unwrap_or(LIST_DISK_GB_SECOND),
865 vcpu.unwrap_or(LIST_VCPU_SECOND),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look866 durable_object.unwrap_or(LIST_DO_GB_SECOND),
867 );
868 // The parts, for runs that report their own CPU.
869 let parts_reason = "Cloudflare's Containers and Durable Objects rates, as billed or published";
870 self.measure("sandbox_base_second", sandbox_base_micros(rates.0, rates.1, rates.3), parts_reason).await?;
871 self.measure("sandbox_cpu_second", rates.2 * MICROS_PER_DOLLAR as f64, parts_reason).await?;
872 if let Some(per_second) = sandbox_second_micros(usage, rates.0, rates.1, rates.2, rates.3) {
The keeper reads Cloudflare as it really answers873 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 look874 let billed = [("memory", memory), ("disk", disk), ("vCPU", vcpu), ("Durable Object duration", durable_object)]
The keeper reads Cloudflare as it really answers875 .iter()
876 .filter(|(_, rate)| rate.is_some())
877 .map(|(name, _)| *name)
878 .collect::<Vec<_>>();
879 let reason = format!(
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look880 "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 answers881 usage.cpu_seconds / instance_seconds,
882 instance_seconds / 3600.0,
883 if billed.is_empty() {
884 "rates are Cloudflare's published ones".to_owned()
885 } else {
886 format!("{} at what Cloudflare billed", billed.join(", "))
887 },
888 );
889 for meter in ["sandbox_second", "build_second"] {
890 self.measure(meter, per_second, &reason).await?;
Prices keep themselves current with what g1t pays891 }
892 }
The keeper reads Cloudflare as it really answers893 // Apps run as Workers: per million requests and CPU milliseconds,
894 // 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 put895 // Security scans' CPU follows the same Workers CPU rate.
896 let app_meters: [(&str, &[&str], &str); 3] = [
The keeper reads Cloudflare as it really answers897 ("app_requests", &["workers", "requests"], "requests"),
898 ("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 put899 ("scan_cpu", &["workers cpu"], "CPU ms"),
The keeper reads Cloudflare as it really answers900 ];
901 for (meter, words, unit) in app_meters {
902 if let Some(rate) = billed_rate(&named(words)) {
903 let reason = format!("Cloudflare billed Workers {unit} at ${:.2} per million", rate * 1e6);
904 self.measure(meter, rate * 1e6 * MICROS_PER_DOLLAR as f64, &reason).await?;
Prices keep themselves current with what g1t pays905 }
906 }
907 self.db
908 .prepare("UPDATE prices SET checked_at = ?")
909 .bind(&[now.as_str().into()])?
910 .run()
911 .await?;
912 Ok(())
913 }
914
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily915 /// Proposes moving a meter's cost to a measurement (see `pricing`):
916 /// applied on its own when small, after notice when a rise; left for
917 /// staff when large or suspect.
Prices keep themselves current with what g1t pays918 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 daily919 if let Some(outcome) = self.propose(meter, measured, reason, "keeper").await? {
920 worker::console_log!("{meter}: {outcome}");
Prices keep themselves current with what g1t pays921 }
922 Ok(())
923 }
924}
925
926#[cfg(test)]
927mod tests {
928 use super::*;
929
930 #[test]
Team plan, an open-source pool, monthly trials and honest metering; the sidebar for everyone; a workspace that stays put931 fn a_correction_never_gives_back_what_the_workspace_did_not_pay() {
932 // Up by 2 cents: charged in full (then drawn down like any charge).
933 assert_eq!(correction(100_000, 120_000, 100_000), 20_000);
934 // Down by 2 cents, all of it paid by the workspace: given back.
935 assert_eq!(correction(120_000, 100_000, 120_000), -20_000);
936 // Down, but the open-source pool paid all but a cent: a cent back.
937 assert_eq!(correction(120_000, 100_000, 10_000), -10_000);
938 // Paid entirely by a credit or pool: nothing back.
939 assert_eq!(correction(120_000, 100_000, 0), 0);
Prices keep themselves current with what g1t pays940 }
941
Merge branch 'worktree-agent-a633ac0f7f66d419d'942 fn logs(entries: &[Value]) -> SessionCost {
943 let mut total = SessionCost { complete: true, ..SessionCost::default() };
944 for log in entries {
945 total.add(log);
946 }
947 total
948 }
949
950 #[test]
951 fn a_run_is_settled_at_the_gateways_figure_when_it_priced_every_request() {
952 let gateway = logs(&[
953 json!({ "cost": 0.012, "tokens_in": 4000, "tokens_out": 300, "model": "claude-sonnet-5-5" }),
954 json!({ "cost": "0.003", "tokens_in": 900, "tokens_out": 40, "model": "claude-haiku-4-5" }),
955 // Served from the gateway's own cache: no cost, and none owed.
956 json!({ "cost": 0, "tokens_in": 900, "tokens_out": 40, "cached": true }),
957 // An error with no tokens costs nothing either.
958 json!({ "cost": null, "tokens_in": 0, "tokens_out": 0 }),
959 ]);
960 assert!(gateway.whole());
961 assert_eq!(gateway.requests, 4);
962 // Down from what the sandbox said, or up: the gateway's figure.
963 assert_eq!(settled_cost(20_000, &gateway), (15_000, None));
964 assert_eq!(settled_cost(9_000, &gateway), (15_000, None));
965 }
966
967 #[test]
968 fn a_model_the_gateway_cannot_price_is_never_settled_down_to_nothing() {
969 let gateway = logs(&[
970 json!({ "cost": 0.002, "tokens_in": 100, "tokens_out": 10, "model": "claude-haiku-4-5" }),
971 json!({ "cost": 0, "tokens_in": 50_000, "tokens_out": 2_000, "model": "claude-new-1" }),
972 json!({ "tokens_in": 50_000, "tokens_out": 2_000, "model": "claude-new-1" }),
973 ]);
974 assert!(!gateway.whole());
975 assert_eq!((gateway.unpriced, gateway.unpriced_models.clone()), (2, vec!["claude-new-1".to_owned()]));
976 // The sandbox said $0.90: kept, not cut to the gateway's $0.002.
977 let (cost, why) = settled_cost(900_000, &gateway);
978 assert_eq!(cost, 900_000);
979 assert!(why.unwrap().contains("no price for 2 of its 3 requests (claude-new-1)"));
980 // A sandbox that reported less than the gateway priced: the gateway's.
981 assert_eq!(settled_cost(1_000, &gateway).0, 2_000);
982 }
983
984 #[test]
985 fn more_logs_than_were_read_never_settle_a_run_down() {
986 let mut gateway = logs(&[json!({ "cost": 1.0, "tokens_in": 1, "tokens_out": 1 })]);
987 gateway.complete = false;
988 let (cost, why) = settled_cost(3_000_000, &gateway);
989 assert_eq!(cost, 3_000_000);
990 assert!(why.unwrap().contains("more than 1 of its requests"));
991 }
992
993 #[test]
994 fn a_gateway_figure_over_the_report_cap_is_charged_in_full() {
995 // A sandbox's report is believed up to $100; the gateway's is not capped.
996 let gateway = logs(&[json!({ "cost": 140.0, "tokens_in": 1, "tokens_out": 1 })]);
997 assert_eq!(settled_cost(100_000_000, &gateway).0, 140_000_000);
998 assert_eq!(crate::charge_micros(140.0, 20), 120_000_000);
999 assert_eq!(crate::margin_on(140_000_000, 20), 168_000_000);
1000 // Exactly cost plus the margin, rounded up, in whole micros (dollars
1001 // as floats can come out a micro high), never under it.
1002 for cost in [0_i64, 1, 7, 999, 123_457, 99_999_999] {
1003 let exact = (cost * 120 + 99) / 100;
1004 assert_eq!(crate::margin_on(cost, 20), exact, "{cost}");
1005 assert!(crate::margin_on(cost, 20) * 100 >= cost * 120, "{cost}");
1006 assert!(crate::charge_micros(cost as f64 / 1e6, 20) >= exact, "{cost}");
1007 }
1008 }
1009
Prices keep themselves current with what g1t pays1010 #[test]
The keeper reads Cloudflare as it really answers1011 fn a_sandbox_second_is_its_memory_and_disk_and_the_cpu_it_uses() {
1012 // An hour of sandboxes that kept a fifth of a vCPU busy.
1013 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 look1014 let micros =
1015 sandbox_second_micros(usage, LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_VCPU_SECOND, LIST_DO_GB_SECOND).unwrap();
1016 // 4 x 2.5 + 8 x 0.07 + 0.125 x 12.5 + 0.2 x 20 = 16.1225
1017 assert!((micros - 16.1225).abs() < 1e-9, "{micros}");
1018 // The Durable Object adds about 11% to the second it left out.
1019 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 answers1020 // Too little use to say anything.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1021 assert!(sandbox_second_micros(ContainerUsage { cpu_seconds: 1.0, memory_byte_seconds: GIB }, 1.0, 1.0, 1.0, 1.0).is_none());
1022 }
1023
1024 #[test]
1025 fn a_run_that_reports_its_cpu_is_priced_on_it() {
1026 let base = sandbox_base_micros(LIST_MEMORY_GIB_SECOND, LIST_DISK_GB_SECOND, LIST_DO_GB_SECOND);
1027 let vcpu = LIST_VCPU_SECOND * MICROS_PER_DOLLAR as f64;
1028 // A 10-minute cargo build that kept its half vCPU busy throughout.
1029 let heavy = run_cost(600, 300.0, base, vcpu);
1030 assert!((heavy - (600.0 * 12.1225 + 300.0 * 20.0)).abs() < 1e-6);
1031 // The same ten minutes, mostly idle, costs less.
1032 let light = run_cost(600, 30.0, base, vcpu);
1033 assert!(light < heavy);
1034 // The average would have under-priced the heavy one.
1035 let average = 600.0 * (base + 0.195 * vcpu);
1036 assert!(average < heavy && average > light);
1037 assert_eq!(run_cost(0, -1.0, base, vcpu), 0.0);
Fast pages, required checks on the branch, self-hosted runners, honest incidents1038 // A larger machine's base: its memory and disk, not its CPU.
1039 assert!((base_scale(SANDBOX_GIB, SANDBOX_DISK_GB) - 1.0).abs() < 1e-12);
1040 assert!((base_scale(12.0, 20.0) - 2.72).abs() < 0.01, "{}", base_scale(12.0, 20.0));
1041 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 answers1042 }
1043
1044 #[test]
1045 fn a_billed_rate_is_the_median_of_the_charged_days() {
1046 let row = |quantity: f64, cost: f64| UsageRow {
1047 period_start: String::new(),
1048 period_end: String::new(),
1049 service: "Containers / Container Memory".into(),
1050 unit: "Count".into(),
1051 quantity,
1052 cost,
1053 };
1054 let rows = [row(100.0, 0.0), row(100.0, 0.0002), row(100.0, 0.00025), row(100.0, 0.00025)];
1055 assert_eq!(billed_rate(&rows.iter().collect::<Vec<_>>()), Some(0.000_002_5));
1056 assert_eq!(billed_rate(&[&row(5.0, 0.0)]), None);
1057 }
1058
1059 #[test]
Prices keep themselves current with what g1t pays1060 fn usage_rows_are_read_by_their_focus_names() {
1061 let row = UsageRow::from_value(&json!({
1062 "ServiceFamilyName": "Containers",
1063 "ServiceName": "Memory",
The keeper reads Cloudflare as it really answers1064 "PricingUnit": "GiB-seconds",
Prices keep themselves current with what g1t pays1065 "PricingQuantity": "1200.5",
1066 "ContractedCost": 0.003,
1067 "ChargePeriodStart": "2026-10-01",
1068 }))
1069 .unwrap();
1070 assert_eq!(row.service, "Containers / Memory");
1071 assert_eq!(row.quantity, 1200.5);
1072 assert_eq!(row.cost, 0.003);
1073 assert!(UsageRow::from_value(&json!({ "nothing": 1 })).is_none());
1074 }
1075}

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