Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
2,817 linesCodeBlameRaw
1//! What g1t earns on each thing it sells, measured against what
2//! Cloudflare actually charged for it.
3//!
4//! Once a day, after `costs` has read Cloudflare's bill, the reconciler
5//! puts three figures side by side for every day and each of g1t's
6//! products (a "bucket": sandboxes, deployments, git, repository storage,
7//! …):
8//!
9//! 1. **What Cloudflare charged**: the day's cost lines `cost_map` gives
10//! the bucket.
11//! 2. **What g1t's meters recorded**: the cost on the ledger's entries for
12//! it (the price book's cost at the time) and, where a mapping names
13//! one, g1t's own count of the same units (git operations).
14//! 3. **What customers were charged**: the entries' value at price, before
15//! the plan's included usage, a trial or a pool paid part of it; and of
16//! that, what workspaces paid. Month-end meters (git, storage, scans,
17//! embeddings, the actions cache) come from daily snapshots of what they
18//! had come to (`pending_days`). The plan's price is the `platform`
19//! bucket's: the plan pays for running g1t.
20//!
21//! From those: margin per product (value against cost) and for all of g1t
22//! (money in against every cost); drift (counts or costs that disagree past
23//! a mapping's threshold, and leaks: cost with no revenue, or a Cloudflare
24//! meter no one mapped); each workspace's cost, Cloudflare's figure shared
25//! out by each workspace's own meters; and price proposals when a unit's
26//! real cost has moved (`pricing`). Alerts go to staff by email and as a
27//! banner in sudo.
28
29use std::collections::{BTreeMap, BTreeSet};
30
31use g1t_contracts::billing::*;
32use g1t_contracts::{FailureCode, Outcome, new_id};
33use g1t_contracts::time::rfc3339;
34use g1t_kit::now_ms;
35use serde::{Deserialize, Serialize};
36use worker::wasm_bindgen::JsValue;
37use worker::{Env, Result};
38
39use crate::Billing;
40use crate::costs::{self, ARTIFACTS_OPERATIONS, DAY_MS, Rule, SOURCE_ARTIFACTS, SOURCE_BILLABLE, UNMAPPED};
41
42/// Buckets that are the cost of running g1t, paid by the plan rather than
43/// sold by the unit: never a leak for having no revenue of their own.
44pub(crate) const OVERHEAD: [&str; 1] = ["platform"];
45/// Buckets Cloudflare does not bill: their cost is g1t's own figure.
46pub(crate) const NOT_CLOUDFLARE: [&str; 1] = ["models"];
47/// The key an agent's planning run is reconciled under. Its ledger task
48/// is `plan`, which is also the plan's payments' key (`revenue_map`: the
49/// platform bucket), so read as `plan` its model cost went to running g1t,
50/// where Cloudflare's bill is the cost, and was lost. No `revenue_map`
51/// row: models, like every agent run.
52pub(crate) const PLANNING_KEY: &str = "planning";
53/// The days drift is judged over.
54const DRIFT_DAYS: u64 = 7;
55/// The days a workspace's cost is set against its revenue.
56const ANOMALY_DAYS: u64 = 30;
57/// The days a unit's cost is measured over.
58const MEASURE_DAYS: u64 = 30;
59/// Fewer of g1t's units than this say nothing about cost per unit.
60const MIN_UNITS: f64 = 1_000.0;
61/// An open alert is emailed again after this long.
62const REMIND_MS: u64 = 7 * DAY_MS;
63
64// ---------------------------------------------------------------------
65// The arithmetic, apart from the database so it can be tested.
66// ---------------------------------------------------------------------
67
68/// One of g1t's products on one day.
69#[derive(Clone, Debug, Default, PartialEq)]
70pub(crate) struct ProductDay {
71 pub day: String,
72 pub bucket: String,
73 /// What Cloudflare charged g1t, in millionths of a dollar.
74 pub cf_cost_micros: i64,
75 /// What g1t's meters recorded it cost (the price book's cost).
76 pub own_cost_micros: i64,
77 /// What customers were charged for it at price, before what paid.
78 pub value_micros: i64,
79 /// Of that, what workspaces paid themselves.
80 pub cash_micros: i64,
81 /// Units Cloudflare counted and units g1t counted, where a mapping
82 /// says they are the same units.
83 pub cf_quantity: f64,
84 pub own_quantity: f64,
85 /// Of `cost()`, what went on usage g1t gave away (the workspaces'
86 /// `WorkspaceDay::given`, added up).
87 pub given: Given,
88}
89
90impl ProductDay {
91 /// What it cost: Cloudflare's figure where Cloudflare bills it, else
92 /// g1t's own (models are billed by their providers, through the gateway).
93 pub fn cost(&self) -> i64 {
94 if NOT_CLOUDFLARE.contains(&self.bucket.as_str()) { self.own_cost_micros } else { self.cf_cost_micros }
95 }
96}
97
98/// A line of Cloudflare's bill, as stored.
99#[derive(Clone, Debug, Deserialize)]
100pub(crate) struct LineRow {
101 pub day: String,
102 pub source: String,
103 pub product: String,
104 pub meter: String,
105 pub quantity: f64,
106 pub cost_usd: f64,
107}
108
109/// A count of g1t's own, as stored.
110#[derive(Clone, Debug, Deserialize)]
111pub(crate) struct OwnRow {
112 pub day: String,
113 pub meter: String,
114 pub workspace: String,
115 pub quantity: f64,
116}
117
118/// What g1t gave away, by why: its own comped workspaces, free use (a
119/// free period, free allowances, overruns g1t covered), the trial, and the
120/// open-source pool, and discounts on an account's terms (what they took
121/// below cost plus the margin, `ledger.discount_micros`), and credits g1t
122/// staff gave, promotional and goodwill, when spent (`grants`), and usage a
123/// testing reset wiped (`reset_costs`): g1t paid for it and nobody will;
124/// and what was charged while payments were not live (Stripe's test mode),
125/// which brought in no real money (`without_real_money`).
126/// The Team plan's included usage is paid for by the plan's price, so it is
127/// sold, not given; so is what a refund pays for.
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub(crate) struct Given {
130 pub comped: i64,
131 pub free: i64,
132 pub trial: i64,
133 pub pool: i64,
134 pub discount: i64,
135 pub credit_promotional: i64,
136 pub credit_goodwill: i64,
137 pub reset: i64,
138 pub unpaid: i64,
139}
140
141impl Given {
142 pub fn total(&self) -> i64 {
143 self.comped + self.free + self.trial + self.pool + self.discount + self.credit() + self.reset + self.unpaid
144 }
145
146 /// Credits from g1t, both kinds.
147 pub fn credit(&self) -> i64 {
148 self.credit_promotional + self.credit_goodwill
149 }
150
151 fn add(&mut self, other: &Given) {
152 self.comped += other.comped;
153 self.free += other.free;
154 self.trial += other.trial;
155 self.pool += other.pool;
156 self.discount += other.discount;
157 self.credit_promotional += other.credit_promotional;
158 self.credit_goodwill += other.credit_goodwill;
159 self.reset += other.reset;
160 self.unpaid += other.unpaid;
161 }
162
163 /// The same shares of `cost` as these are of `value`, at most all of it.
164 fn of(&self, cost: i64, value: i64) -> Given {
165 let total = self.total();
166 if value <= 0 || cost <= 0 || total <= 0 {
167 return Given::default();
168 }
169 let given = cost as i128 * total.min(value) as i128 / value as i128;
170 let part = |x: i64| (given * x.max(0) as i128 / total as i128) as i64;
171 Given {
172 comped: part(self.comped),
173 free: part(self.free),
174 trial: part(self.trial),
175 pool: part(self.pool),
176 discount: part(self.discount),
177 credit_promotional: part(self.credit_promotional),
178 credit_goodwill: part(self.credit_goodwill),
179 reset: part(self.reset),
180 unpaid: part(self.unpaid),
181 }
182 }
183}
184
185/// Credits from g1t in the reconciliation (`grants`): usage paid for with
186/// promotional or goodwill credit is given, not money in; a refund comes
187/// off money in on the day it refunds, shared over that day's paid usage.
188/// What credit paid for that is not among `rows` (month-end meters, or
189/// what was owed from before) is a row of its own on its day.
190pub(crate) fn apply_credits(rows: &mut Vec<UsageRow>, draws: &[(String, crate::grants::Draw)], refunds: &[crate::grants::Refunded]) {
191 let mut paid: BTreeMap<(String, String, String), Given> = BTreeMap::new();
192 for (workspace, draw) in draws {
193 let given = paid
194 .entry((draw.at[..10].to_owned(), workspace.clone(), crate::grants::usage_key(draw.task.as_deref(), &draw.reference)))
195 .or_default();
196 match draw.kind {
197 CreditKind::Promotional => given.credit_promotional += draw.micros,
198 CreditKind::Goodwill => given.credit_goodwill += draw.micros,
199 // Money already paid: what it pays for is paid for.
200 CreditKind::Refund | CreditKind::Purchased => {}
201 }
202 }
203 for ((day, workspace, key), given) in paid {
204 if given.credit() == 0 {
205 continue;
206 }
207 match rows.iter_mut().find(|r| r.day == day && r.workspace == workspace && r.key == key) {
208 Some(row) => {
209 row.cash -= given.credit();
210 row.given.add(&given);
211 }
212 None => rows.push(UsageRow { day, workspace, key, bucket: None, value: 0, cash: -given.credit(), cost: 0, given }),
213 }
214 }
215 for refund in refunds {
216 let weights: Vec<(String, f64)> = rows
217 .iter()
218 .enumerate()
219 .filter(|(_, r)| r.day == refund.day && r.workspace == refund.workspace && r.cash > 0)
220 .map(|(i, r)| (format!("{i:08}"), r.cash as f64))
221 .collect();
222 let shares = attribute(refund.micros, &weights);
223 if shares.is_empty() {
224 rows.push(UsageRow {
225 day: refund.day.clone(),
226 workspace: refund.workspace.clone(),
227 key: "other".into(),
228 cash: -refund.micros,
229 ..UsageRow::default()
230 });
231 }
232 for (index, micros) in shares {
233 if let Ok(i) = index.parse::<usize>() {
234 rows[i].cash -= micros;
235 }
236 }
237 }
238}
239
240/// Money in only where it is real. Charges made while payments were not
241/// live (Stripe's test mode) brought in nothing: a row's cash from before
242/// `live_since` (all of it while payments are not live, `None`) is taken
243/// out of cash and counted as given away (`unpaid`), so it is never money
244/// in, never margin, and never what a workspace paid.
245pub(crate) fn without_real_money(rows: &mut [UsageRow], live_since: Option<&str>) {
246 for row in rows {
247 if live_since.is_some_and(|since| row.day.as_str() >= since) || row.cash == 0 {
248 continue;
249 }
250 // What else gave it away already (a 100% discount) stays that.
251 row.given.unpaid += row.cash.min(row.value - row.given.total()).max(0);
252 row.cash = 0;
253 }
254}
255
256/// The day payments went live, from `cost_settings` (`payments_live_since`)
257/// as a value read there: None while they are not live, the day kept when
258/// they are, else `today` (the first time they are seen live).
259pub(crate) fn live_since(live: bool, kept: Option<&str>, today: &str) -> Option<String> {
260 if !live {
261 return None;
262 }
263 Some(kept.filter(|d| d.len() >= 10).map_or_else(|| today.to_owned(), |d| d[..10].to_owned()))
264}
265
266/// What a workspace was charged for one key on one day.
267#[derive(Clone, Debug, Default, PartialEq)]
268pub(crate) struct UsageRow {
269 pub day: String,
270 pub workspace: String,
271 /// A ledger task (or `builds`), a month-end source, or `plan`.
272 pub key: String,
273 /// The bucket, where it is known already (what a testing reset kept,
274 /// `reset_costs`); else `key`'s, from `revenue_map`.
275 pub bucket: Option<String>,
276 pub value: i64,
277 pub cash: i64,
278 pub cost: i64,
279 /// Of `value`, what g1t gave away: all of it for g1t's own (comped)
280 /// workspaces and in a free period, else what the trial and the pool
281 /// paid and the overruns g1t covered.
282 pub given: Given,
283}
284
285/// One workspace's share of a product's cost on one day.
286#[derive(Clone, Debug, PartialEq)]
287pub(crate) struct WorkspaceDay {
288 pub day: String,
289 pub workspace: String,
290 pub bucket: String,
291 pub cost: i64,
292 /// What the workspace paid in cash.
293 pub revenue: i64,
294 /// What its usage was priced at, whoever paid for it.
295 pub value: i64,
296 /// Of `cost`, the part g1t gave away: all of it for a comped workspace
297 /// or one with nothing priced that day (free use), else the cost times
298 /// the shares of its usage that day that g1t paid for.
299 pub given: Given,
300}
301
302fn micros(dollars: f64) -> i64 {
303 (dollars * 1_000_000.0).round() as i64
304}
305
306/// Puts the day's bill, g1t's counts and what customers were charged side
307/// by side, a row per day and bucket, and shares each bucket's cost out
308/// to workspaces.
309pub(crate) fn fold(
310 rules: &[Rule],
311 revenue_map: &BTreeMap<String, String>,
312 lines: &[LineRow],
313 own: &[OwnRow],
314 usage: &[UsageRow],
315 internal: &BTreeSet<String>,
316) -> (Vec<ProductDay>, Vec<WorkspaceDay>) {
317 let mut days: BTreeMap<(String, String), ProductDay> = BTreeMap::new();
318 let entry = |day: &str, bucket: &str| -> ProductDay {
319 ProductDay { day: day.to_owned(), bucket: bucket.to_owned(), ..ProductDay::default() }
320 };
321 // Which of g1t's own meters count each bucket's units.
322 let mut own_meters: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
323 for rule in rules {
324 if let Some(meter) = &rule.own_meter {
325 own_meters.entry(rule.bucket.as_str()).or_default().insert(meter.as_str());
326 }
327 }
328 let mut events: BTreeMap<(String, String), f64> = BTreeMap::new();
329 for line in lines {
330 let rule = costs::classify(rules, &line.product, &line.meter);
331 let bucket = rule.map_or(UNMAPPED, |r| r.bucket.as_str());
332 let key = (line.day.clone(), bucket.to_owned());
333 if line.source == SOURCE_ARTIFACTS {
334 // What Artifacts counted: operations only, and only where the
335 // bill does not count them itself.
336 if ARTIFACTS_OPERATIONS.contains(&line.meter.as_str()) {
337 *events.entry(key).or_default() += line.quantity;
338 }
339 continue;
340 }
341 let row = days.entry(key.clone()).or_insert_with(|| entry(&key.0, &key.1));
342 row.cf_cost_micros += micros(line.cost_usd);
343 if line.source == SOURCE_BILLABLE && rule.is_some_and(|r| r.own_meter.is_some()) {
344 row.cf_quantity += line.quantity;
345 }
346 }
347 for (key, quantity) in events {
348 let row = days.entry(key.clone()).or_insert_with(|| entry(&key.0, &key.1));
349 if row.cf_quantity == 0.0 {
350 row.cf_quantity = quantity;
351 }
352 }
353 // g1t's own counts of the same units, by bucket and by workspace.
354 let mut own_by: BTreeMap<(String, String), Vec<(String, f64)>> = BTreeMap::new();
355 // Cloudflare's own count by workspace, where it gives one
356 // (`cloudflare_<bucket>`): the best way to share its cost.
357 let mut cf_by: BTreeMap<(String, String), Vec<(String, f64)>> = BTreeMap::new();
358 for count in own {
359 if let Some(bucket) = count.meter.strip_prefix("cloudflare_") {
360 cf_by.entry((count.day.clone(), bucket.to_owned())).or_default().push((count.workspace.clone(), count.quantity));
361 continue;
362 }
363 for (bucket, meters) in &own_meters {
364 if meters.contains(count.meter.as_str()) {
365 let key = (count.day.clone(), (*bucket).to_owned());
366 days.entry(key.clone()).or_insert_with(|| entry(&key.0, &key.1)).own_quantity += count.quantity;
367 own_by.entry(key).or_default().push((count.workspace.clone(), count.quantity));
368 }
369 }
370 }
371 // What customers were charged.
372 let bucket_of = |key: &str| revenue_map.get(key).cloned().unwrap_or_else(|| "models".to_owned());
373 let mut value_by: BTreeMap<(String, String), Vec<(String, f64)>> = BTreeMap::new();
374 let mut cost_by: BTreeMap<(String, String), Vec<(String, f64)>> = BTreeMap::new();
375 let mut revenue: BTreeMap<(String, String, String), i64> = BTreeMap::new();
376 let mut valued: BTreeMap<(String, String, String), i64> = BTreeMap::new();
377 let mut active: BTreeMap<String, Vec<(String, f64)>> = BTreeMap::new();
378 let mut gave: BTreeMap<(String, String), (Given, i64)> = BTreeMap::new();
379 for u in usage {
380 let g = gave.entry((u.day.clone(), u.workspace.clone())).or_default();
381 g.0.add(&u.given);
382 g.1 += u.value;
383 let bucket = u.bucket.clone().unwrap_or_else(|| bucket_of(&u.key));
384 let key = (u.day.clone(), bucket.clone());
385 let row = days.entry(key.clone()).or_insert_with(|| entry(&key.0, &key.1));
386 row.own_cost_micros += u.cost;
387 row.value_micros += u.value;
388 row.cash_micros += u.cash;
389 value_by.entry(key.clone()).or_default().push((u.workspace.clone(), u.value as f64));
390 cost_by.entry(key).or_default().push((u.workspace.clone(), u.cost as f64));
391 *revenue.entry((u.day.clone(), u.workspace.clone(), bucket.clone())).or_default() += u.cash;
392 *valued.entry((u.day.clone(), u.workspace.clone(), bucket)).or_default() += u.value;
393 active.entry(u.day.clone()).or_default().push((u.workspace.clone(), u.value.max(u.cost) as f64));
394 }
395 // Each bucket's cost shared out: by Cloudflare's own count per
396 // workspace, else by g1t's own count of its units, else by what its
397 // usage cost (so free use carries its own cost), else by what it was
398 // charged; running g1t, and what no one mapped, by each workspace's
399 // share of all usage that day.
400 let mut shares: BTreeMap<(String, String, String), i64> = BTreeMap::new();
401 for ((day, bucket), row) in &days {
402 let key = (day.clone(), bucket.clone());
403 let weigh = |m: &BTreeMap<(String, String), Vec<(String, f64)>>| m.get(&key).filter(|w| w.iter().any(|(_, v)| *v > 0.0)).cloned();
404 let weights = if OVERHEAD.contains(&bucket.as_str()) || bucket == UNMAPPED {
405 active.get(day).cloned()
406 } else {
407 weigh(&cf_by).or_else(|| weigh(&own_by)).or_else(|| weigh(&cost_by)).or_else(|| weigh(&value_by)).or_else(|| active.get(day).cloned())
408 };
409 for (workspace, micros) in attribute(row.cost(), &weights.unwrap_or_default()) {
410 *shares.entry((day.clone(), workspace, bucket.clone())).or_default() += micros;
411 }
412 }
413 let keys: BTreeSet<(String, String, String)> = shares.keys().chain(revenue.keys()).cloned().collect();
414 let workspaces: Vec<WorkspaceDay> = keys
415 .into_iter()
416 .map(|(day, workspace, bucket)| {
417 let cost = shares.get(&(day.clone(), workspace.clone(), bucket.clone())).copied().unwrap_or(0);
418 // The day's shares given away apply to every bucket, so a
419 // comped workspace's part of running g1t is given too. A
420 // workspace with nothing priced that day used g1t for free.
421 let given = if internal.contains(&workspace) {
422 Given { comped: cost, ..Given::default() }
423 } else {
424 match gave.get(&(day.clone(), workspace.clone())) {
425 Some((given, value)) if *value > 0 => given.of(cost, *value),
426 _ => Given { free: cost.max(0), ..Given::default() },
427 }
428 };
429 WorkspaceDay {
430 cost,
431 revenue: revenue.get(&(day.clone(), workspace.clone(), bucket.clone())).copied().unwrap_or(0),
432 value: valued.get(&(day.clone(), workspace.clone(), bucket.clone())).copied().unwrap_or(0),
433 given,
434 day,
435 workspace,
436 bucket,
437 }
438 })
439 .collect();
440 for w in &workspaces {
441 if let Some(row) = days.get_mut(&(w.day.clone(), w.bucket.clone())) {
442 row.given.add(&w.given);
443 }
444 }
445 (days.into_values().collect(), workspaces)
446}
447
448/// A month-end source's day, from the snapshots of what it had come to:
449/// each day's figure less the day before's in the same month (the first
450/// day of a month, or the first snapshot, is its own).
451pub(crate) fn pending_deltas(snapshots: &[(String, String, String, i64, i64)]) -> Vec<UsageRow> {
452 // (day, workspace, source, cost, charge), any order.
453 let mut sorted = snapshots.to_vec();
454 sorted.sort_by(|a, b| (&a.1, &a.2, &a.0).cmp(&(&b.1, &b.2, &b.0)));
455 let mut out = Vec::new();
456 let mut previous: Option<&(String, String, String, i64, i64)> = None;
457 for snap in &sorted {
458 let (day, workspace, source, cost, charge) = snap;
459 let (before_cost, before_charge) = match previous {
460 Some(p) if p.1 == *workspace && p.2 == *source && p.0[..7] == day[..7] => (p.3, p.4),
461 _ => (0, 0),
462 };
463 let (cost, charge) = ((cost - before_cost).max(0), (charge - before_charge).max(0));
464 if cost > 0 || charge > 0 {
465 out.push(UsageRow { day: day.clone(), workspace: workspace.clone(), key: source.clone(), bucket: None, value: charge, cash: charge, cost, given: Given::default() });
466 }
467 previous = Some(snap);
468 }
469 out
470}
471
472/// A month-end meter's day on a 100%-discount workspace: all of it given
473/// (comped) and none of it money in. The snapshot holds what the month
474/// would charge before the discount, which the month's close takes off in
475/// full; counted as paid, flagon-io's cache, embeddings and scans read as
476/// money in ($0.0023 on 2026-10-08).
477pub(crate) fn comped_meter(mut u: UsageRow) -> UsageRow {
478 u.given = Given { comped: u.value, ..Given::default() };
479 u.cash = 0;
480 u
481}
482
483/// A complimentary workspace's month-end meter: its allowance (or g1t,
484/// past it) paid, so it is given away as promotional, never money in.
485pub(crate) fn gifted_meter(mut u: UsageRow) -> UsageRow {
486 u.given = Given { credit_promotional: u.value, ..Given::default() };
487 u.cash = 0;
488 u
489}
490
491/// Margin as a share of what was charged, in percent; None when nothing was.
492pub(crate) fn margin_percent(revenue_micros: i64, cost_micros: i64) -> Option<f64> {
493 (revenue_micros > 0).then(|| (revenue_micros - cost_micros) as f64 * 100.0 / revenue_micros as f64)
494}
495
496/// How far `ours` is from `theirs`, in percent of theirs; None when theirs
497/// is nothing.
498pub(crate) fn delta_percent(ours: f64, theirs: f64) -> Option<f64> {
499 (theirs > 0.0).then(|| (ours - theirs) * 100.0 / theirs)
500}
501
502#[derive(Clone, Copy, Debug, PartialEq, Eq)]
503pub(crate) enum DriftKind {
504 /// g1t counted a different number of units than Cloudflare did.
505 Count,
506 /// The price book's cost of a bucket's usage differs from what the
507 /// same usage comes to at Cloudflare's list prices, before the included
508 /// amounts (a price may be stale).
509 Cost,
510 /// Cloudflare charged for something nothing charges customers for.
511 Leak,
512}
513
514impl DriftKind {
515 pub fn as_str(self) -> &'static str {
516 match self {
517 DriftKind::Count => "count",
518 DriftKind::Cost => "cost",
519 DriftKind::Leak => "leak",
520 }
521 }
522}
523
524#[derive(Clone, Debug, PartialEq)]
525pub(crate) struct Drift {
526 pub bucket: String,
527 pub kind: DriftKind,
528 pub ours: f64,
529 pub cloudflare: f64,
530 pub delta_percent: Option<f64>,
531}
532
533/// Drift over a window for one bucket: counts more than `threshold`
534/// percent apart, the price book's cost of the usage that far from what the
535/// same usage comes to at Cloudflare's list prices (`list_micros`, from
536/// `list_costs`), and cost with nothing charged for it. Under
537/// `min_cost_micros` in all, cost says nothing.
538///
539/// The price book is set against the list cost, never against what
540/// Cloudflare billed: the bill is net of the included amounts and the price
541/// book's cost is of every unit, so a bucket whose usage mostly fits in
542/// them would read as a stale price when nothing changed. Without a list
543/// cost (a meter in the bucket with no list price) the price book is not
544/// checked. A leak is still what Cloudflare billed: money spent.
545pub(crate) fn drifts(bucket: &str, days: &[ProductDay], threshold: f64, counted: bool, min_cost_micros: i64, list_micros: Option<f64>) -> Vec<Drift> {
546 // Models: g1t no longer runs agents or sells model access. What their
547 // usage cost before is the ledger's own figure, with nothing to set it
548 // against.
549 if NOT_CLOUDFLARE.contains(&bucket) {
550 return Vec::new();
551 }
552 let overhead = OVERHEAD.contains(&bucket);
553 let sum = |f: &dyn Fn(&ProductDay) -> f64| days.iter().map(f).sum::<f64>();
554 let cf_cost = sum(&|d| d.cf_cost_micros as f64);
555 let own_cost = sum(&|d| d.own_cost_micros as f64);
556 let value = sum(&|d| d.value_micros as f64);
557 // Counts are compared from the first day g1t counted: before its meter
558 // was deployed there is only Cloudflare's side. A meter that never
559 // counted anything is compared over every day, so it still shows.
560 let first_counted = days.iter().filter(|d| d.own_quantity > 0.0).map(|d| d.day.as_str()).min();
561 let compared = |d: &&ProductDay| first_counted.is_none_or(|from| d.day.as_str() >= from);
562 let (cf_quantity, own_quantity) = days.iter().filter(compared).fold((0.0, 0.0), |(cf, own), d| (cf + d.cf_quantity, own + d.own_quantity));
563 let mut out = Vec::new();
564 if counted && cf_quantity > 0.0 {
565 let delta = delta_percent(own_quantity, cf_quantity);
566 if delta.is_some_and(|d| d.abs() > threshold) {
567 out.push(Drift { bucket: bucket.into(), kind: DriftKind::Count, ours: own_quantity, cloudflare: cf_quantity, delta_percent: delta });
568 }
569 }
570 // Its usage at Cloudflare's list prices, before the included amounts.
571 let theirs = list_micros.unwrap_or(0.0);
572 let enough = theirs.max(own_cost) >= min_cost_micros as f64;
573 if enough && !overhead && theirs > 0.0 && own_cost > 0.0 {
574 let delta = delta_percent(own_cost, theirs);
575 if delta.is_some_and(|d| d.abs() > threshold) {
576 out.push(Drift { bucket: bucket.into(), kind: DriftKind::Cost, ours: own_cost, cloudflare: theirs, delta_percent: delta });
577 }
578 }
579 if !overhead && cf_cost >= min_cost_micros as f64 && value <= 0.0 {
580 out.push(Drift { bucket: bucket.into(), kind: DriftKind::Leak, ours: value, cloudflare: cf_cost, delta_percent: None });
581 }
582 out
583}
584
585/// What each bucket's billable usage over a window comes to at
586/// Cloudflare's list prices, before the included amounts (`cycle::list_cost`
587/// line by line, in micros): what the price book's cost of the same usage
588/// is checked against. None for a bucket with usage on a meter that has no
589/// list price: its usage cannot be priced like for like, so it is not
590/// checked. Other sources (Artifacts events, AI Gateway) are left out.
591pub(crate) fn list_costs(rules: &[Rule], lines: &[LineRow]) -> BTreeMap<String, Option<f64>> {
592 let mut out: BTreeMap<String, Option<f64>> = BTreeMap::new();
593 for line in lines.iter().filter(|l| l.source == SOURCE_BILLABLE) {
594 let bucket = costs::classify(rules, &line.product, &line.meter).map_or(UNMAPPED, |r| r.bucket.as_str());
595 let entry = out.entry(bucket.to_owned()).or_insert(Some(0.0));
596 if line.quantity <= 0.0 {
597 continue;
598 }
599 *entry = match (*entry, crate::cycle::list_cost(&line.product, &line.meter, line.quantity)) {
600 (Some(sum), Some(cost)) => Some(sum + cost * 1_000_000.0),
601 _ => None,
602 };
603 }
604 out
605}
606
607/// Where a testing reset's history starts: all of a workspace's ledger.
608pub(crate) const RESET_HISTORY_FROM: &str = "2000-01-01";
609
610/// What a testing reset wiped that g1t paid for, on one day for one
611/// bucket (`reset_costs`).
612#[derive(Clone, Debug, PartialEq)]
613pub(crate) struct Wiped {
614 pub day: String,
615 pub bucket: String,
616 pub cost: i64,
617 pub value: i64,
618}
619
620/// A workspace's usage rows, about to be wiped, as what g1t paid for: the
621/// rows with a cost, by day and bucket, valued as the reconciliation
622/// valued them (at price where nothing paid). Plan payments, credits and
623/// a workspace's own model provider cost g1t nothing and are left out.
624pub(crate) fn wiped(rows: &[UsageRow], revenue_map: &BTreeMap<String, String>, margin_percent: u32) -> Vec<Wiped> {
625 let mut by: BTreeMap<(String, String), (i64, i64)> = BTreeMap::new();
626 for u in rows.iter().filter(|u| u.cost > 0) {
627 let bucket = u.bucket.clone().unwrap_or_else(|| revenue_map.get(&u.key).cloned().unwrap_or_else(|| NOT_CLOUDFLARE[0].to_owned()));
628 let sums = by.entry((u.day.clone(), bucket)).or_default();
629 sums.0 += u.cost;
630 sums.1 += u.value.max(0);
631 }
632 by.into_iter()
633 .map(|((day, bucket), (cost, value))| Wiped {
634 day,
635 bucket,
636 cost,
637 value: if value > 0 { value } else { crate::credits::with_margin(cost, margin_percent) },
638 })
639 .collect()
640}
641
642/// What testing resets kept, each (day, workspace, bucket, cost, value),
643/// as usage rows: valued as before, nothing paid, all of it given away
644/// (why "testing resets"). A reset's own row (bucket '') is not usage.
645pub(crate) fn reset_usage(kept: &[(String, String, String, i64, i64)]) -> Vec<UsageRow> {
646 kept.iter()
647 .filter(|(_, _, bucket, cost, value)| !bucket.is_empty() && (*cost != 0 || *value != 0))
648 .map(|(day, workspace, bucket, cost, value)| UsageRow {
649 day: day.clone(),
650 workspace: workspace.clone(),
651 key: "reset".into(),
652 bucket: Some(bucket.clone()),
653 value: *value,
654 cash: 0,
655 cost: *cost,
656 given: Given { reset: *value, ..Given::default() },
657 })
658 .collect()
659}
660
661/// When the last `days` in a row (each with enough cost to say something)
662/// were all under the floor: the first of them and the worst margin.
663/// Each item is a day's (day, revenue, cost).
664pub(crate) fn breach(series: &[(String, i64, i64)], floor_percent: f64, days: usize, min_cost_micros: i64) -> Option<(String, f64)> {
665 if days == 0 || series.len() < days {
666 return None;
667 }
668 let tail = &series[series.len() - days..];
669 let mut worst = f64::INFINITY;
670 for (_, revenue, cost) in tail {
671 if *cost < min_cost_micros {
672 return None;
673 }
674 let margin = margin_percent(*revenue, *cost).unwrap_or(-100.0);
675 if margin >= floor_percent {
676 return None;
677 }
678 worst = worst.min(margin);
679 }
680 Some((tail[0].0.clone(), worst))
681}
682
683/// `total` shared out in proportion to `weights`, in whole millionths that
684/// add up to it exactly (largest remainder first). Nothing to share, or no
685/// weight, shares nothing.
686pub(crate) fn attribute(total: i64, weights: &[(String, f64)]) -> Vec<(String, i64)> {
687 let mut merged: BTreeMap<String, f64> = BTreeMap::new();
688 for (key, w) in weights {
689 *merged.entry(key.clone()).or_default() += w.max(0.0);
690 }
691 let sum: f64 = merged.values().sum();
692 if total <= 0 || sum <= 0.0 {
693 return Vec::new();
694 }
695 let mut shares: Vec<(String, i64, f64)> = merged
696 .into_iter()
697 .map(|(key, w)| {
698 let exact = total as f64 * w / sum;
699 (key, exact.floor() as i64, exact - exact.floor())
700 })
701 .collect();
702 let mut left = total - shares.iter().map(|s| s.1).sum::<i64>();
703 let mut order: Vec<usize> = (0..shares.len()).collect();
704 order.sort_by(|a, b| shares[*b].2.total_cmp(&shares[*a].2).then(shares[*a].0.cmp(&shares[*b].0)));
705 for index in order {
706 if left <= 0 {
707 break;
708 }
709 shares[index].1 += 1;
710 left -= 1;
711 }
712 shares.into_iter().filter(|s| s.1 > 0).map(|(key, micros, _)| (key, micros)).collect()
713}
714
715/// Workspaces that cost g1t more than `factor` times what they paid, with
716/// at least `floor_micros` of cost: each (workspace, cost, revenue), the
717/// biggest gap first.
718/// What a day's usage was worth at price. g1t's own workspaces are valued
719/// at price. So is usage nothing paid for, neither charged nor drawn from
720/// the plan, a trial, a pool or a gift (a free period): it was given away at
721/// its price, not sold for nothing. Anything paid keeps what it was paid, so
722/// a discount still shows as one.
723pub(crate) fn usage_value(internal: bool, cost: i64, paid: i64, margin_percent: u32) -> i64 {
724 if internal || (paid == 0 && cost > 0) {
725 return crate::credits::with_margin(cost, margin_percent);
726 }
727 paid
728}
729
730/// What the overall alert says: the money as money, and a percentage only
731/// while there is enough coming in for one to mean something (a few cents
732/// against dollars of cost reads as -8000%).
733pub(crate) fn overall_detail(took: i64, spent: i64, days: usize, floor: f64, worst: f64) -> String {
734 if took < 1_000_000 * days as i64 {
735 return format!(
736 "All of g1t, comped workspaces left out: took in {} against {} of Cloudflare's bill over {days} days.",
737 dollars(took),
738 dollars(spent)
739 );
740 }
741 format!("All of g1t, comped workspaces left out: money in against Cloudflare's bill under {floor:.0}% for {days} days running, as low as {worst:.1}%.")
742}
743
744pub(crate) fn anomalies(rows: &[(String, i64, i64)], factor: f64, floor_micros: i64) -> Vec<(String, i64, i64)> {
745 let mut out: Vec<(String, i64, i64)> = rows
746 .iter()
747 .filter(|(_, cost, revenue)| *cost >= floor_micros && *cost as f64 > *revenue as f64 * factor)
748 .cloned()
749 .collect();
750 out.sort_by(|a, b| (b.1 - b.2).cmp(&(a.1 - a.2)).then(a.0.cmp(&b.0)));
751 out
752}
753
754/// Cloudflare's rate for one of its units: the median over the costed
755/// days of cost over quantity, in dollars. None while nothing is costed.
756/// Each item is a day's (quantity, cost), from `rate_line`.
757pub(crate) fn billed_rate(days: &[(f64, f64)]) -> Option<f64> {
758 let mut rates: Vec<f64> = days.iter().filter(|(q, c)| *q > 0.0 && *c > 0.0).map(|(q, c)| c / q).collect();
759 if rates.is_empty() {
760 return None;
761 }
762 rates.sort_by(f64::total_cmp);
763 Some(rates[rates.len() / 2])
764}
765
766/// A line's (quantity, cost) for `billed_rate`: at its list price for all
767/// of the quantity where the meter has one, never what the cycle billed,
768/// which is net of the included amounts (nothing until the cycle passes
769/// them, part of a day's usage on the day it does, then whole millions) and
770/// so says nothing about the price of each unit. A meter with no list
771/// price has only what Cloudflare billed; the median over the charged days
772/// leaves out the day its included amount ran out.
773pub(crate) fn rate_line(product: &str, meter: &str, quantity: f64, cost_usd: f64) -> (f64, f64) {
774 (quantity, crate::cycle::list_cost(product, meter, quantity).unwrap_or(cost_usd))
775}
776
777/// What one of g1t's units costs, from Cloudflare's rate per its own unit
778/// and how many of Cloudflare's units each of g1t's took: if Cloudflare
779/// counts three operations for every git operation g1t counts, a git
780/// operation costs three of Cloudflare's. None without enough of g1t's
781/// units to say.
782pub(crate) fn derived_unit_cost(rate_per_cf_unit: f64, cf_units: f64, own_units: f64) -> Option<f64> {
783 (own_units >= MIN_UNITS && cf_units > 0.0 && rate_per_cf_unit > 0.0).then(|| rate_per_cf_unit * cf_units / own_units)
784}
785
786/// How many units a price is per: `1,000 operations` → 1,000, `million
787/// requests` → 1,000,000, `second` → 1.
788pub(crate) fn unit_size(unit: &str) -> f64 {
789 let first = unit.split_whitespace().next().unwrap_or_default().replace(',', "");
790 match first.as_str() {
791 "million" => 1_000_000.0,
792 "thousand" => 1_000.0,
793 n => n.parse().unwrap_or(1.0),
794 }
795}
796
797fn day_before(day: &str, days: u64) -> String {
798 let ms = g1t_contracts::time::parse_rfc3339(&format!("{day}T00:00:00Z")).unwrap_or(0);
799 rfc3339(ms.saturating_sub(days * DAY_MS))[..10].to_owned()
800}
801
802/// Dollars to the cent from a dollar up, finer below: `$17.02`, `$0.063`.
803fn dollars(micros: i64) -> String {
804 if micros.abs() >= 1_000_000 {
805 let cents = (micros as f64 / 10_000.0).round() as i64;
806 format!("{}${}.{:02}", if cents < 0 { "-" } else { "" }, cents.abs() / 100, cents.abs() % 100)
807 } else {
808 crate::features::dollars(micros)
809 }
810}
811
812/// The days a plan payment is spread over.
813const PLAN_DAYS: u64 = 30;
814
815/// `micros` paid on `day` spread evenly over `days` days from it, in
816/// whole micros that add up to it (the first days take the remainder).
817pub(crate) fn spread(day: &str, micros: i64, days: u64) -> Vec<(String, i64)> {
818 if micros <= 0 || days == 0 {
819 return Vec::new();
820 }
821 let start = g1t_contracts::time::parse_rfc3339(&format!("{}T00:00:00Z", &day[..10.min(day.len())])).unwrap_or(0);
822 let each = micros / days as i64;
823 let rest = micros % days as i64;
824 (0..days)
825 .map(|n| (rfc3339(start + n * DAY_MS)[..10].to_owned(), each + i64::from((n as i64) < rest)))
826 .collect()
827}
828
829// ---------------------------------------------------------------------
830// The daily run, and what sudo reads.
831// ---------------------------------------------------------------------
832
833#[derive(Serialize)]
834struct Mail<'a> {
835 to: &'a str,
836 from: &'a str,
837 subject: &'a str,
838 text: String,
839 html: String,
840}
841
842fn escape(text: &str) -> String {
843 text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
844}
845
846/// Emails staff through Cloudflare Email Sending, the `EMAIL` binding.
847pub(crate) async fn email_staff(env: &Env, to: &str, subject: &str, lines: &[String]) -> Result<()> {
848 email_staff_page(env, to, subject, lines, ("Costs & margin", "https://sudo.g1t.sh/costs"), "g1t-billing's margin guard").await
849}
850
851/// Emails staff, linking to a page of sudo (`page`: its name and address)
852/// and saying what sent it.
853pub(crate) async fn email_staff_page(env: &Env, to: &str, subject: &str, lines: &[String], page: (&str, &str), sender: &str) -> Result<()> {
854 let (name, link) = page;
855 let text = format!("{}\n\n{name}: {link}\n\nSent by {sender} (COSTS_ALERT_EMAIL).\n", lines.join("\n\n"));
856 let mut html = String::from("<div style=\"font-family:system-ui,sans-serif;max-width:560px;margin:0 auto;padding:24px 16px;color:#16150f\">");
857 for line in lines {
858 html.push_str(&format!("<p style=\"font-size:15px;line-height:1.6\">{}</p>", escape(line)));
859 }
860 html.push_str(&format!(
861 "<p><a href=\"{link}\">Open {} in sudo</a></p><p style=\"font-size:13px;color:#6e6a5e\">Sent by {} (COSTS_ALERT_EMAIL).</p></div>",
862 escape(name),
863 escape(sender)
864 ));
865 let mail = Mail { to, from: "g1t <noreply@g1t.sh>", subject, text, html };
866 let binding = g1t_kit::js::binding(env, "EMAIL")?;
867 g1t_kit::js::call(&binding, "send", &[g1t_kit::js::to_js(&mail)?]).await?;
868 Ok(())
869}
870
871#[derive(Deserialize)]
872struct AlertRow {
873 id: String,
874 kind: String,
875 subject: String,
876 detail: String,
877 since: String,
878 opened_at: String,
879 emailed_at: Option<String>,
880}
881
882impl From<AlertRow> for MarginAlert {
883 fn from(r: AlertRow) -> Self {
884 MarginAlert { id: r.id, kind: r.kind, subject: r.subject, detail: r.detail, since: r.since, opened_at: r.opened_at, emailed_at: r.emailed_at }
885 }
886}
887
888#[derive(Deserialize)]
889struct MarginRow {
890 day: String,
891 bucket: String,
892 cf_cost_micros: i64,
893 own_cost_micros: i64,
894 value_micros: i64,
895 cash_micros: i64,
896 cf_quantity: f64,
897 own_quantity: f64,
898 #[serde(default)]
899 given_comped_micros: Option<i64>,
900 #[serde(default)]
901 given_free_micros: Option<i64>,
902 #[serde(default)]
903 given_trial_micros: Option<i64>,
904 #[serde(default)]
905 given_pool_micros: Option<i64>,
906 #[serde(default)]
907 given_discount_micros: Option<i64>,
908 #[serde(default)]
909 given_credit_promotional_micros: Option<i64>,
910 #[serde(default)]
911 given_credit_goodwill_micros: Option<i64>,
912 #[serde(default)]
913 given_reset_micros: Option<i64>,
914 #[serde(default)]
915 given_unpaid_micros: Option<i64>,
916}
917
918impl From<MarginRow> for ProductDay {
919 fn from(r: MarginRow) -> Self {
920 ProductDay {
921 day: r.day,
922 bucket: r.bucket,
923 cf_cost_micros: r.cf_cost_micros,
924 own_cost_micros: r.own_cost_micros,
925 value_micros: r.value_micros,
926 cash_micros: r.cash_micros,
927 cf_quantity: r.cf_quantity,
928 own_quantity: r.own_quantity,
929 given: Given {
930 comped: r.given_comped_micros.unwrap_or(0),
931 free: r.given_free_micros.unwrap_or(0),
932 trial: r.given_trial_micros.unwrap_or(0),
933 pool: r.given_pool_micros.unwrap_or(0),
934 discount: r.given_discount_micros.unwrap_or(0),
935 credit_promotional: r.given_credit_promotional_micros.unwrap_or(0),
936 credit_goodwill: r.given_credit_goodwill_micros.unwrap_or(0),
937 reset: r.given_reset_micros.unwrap_or(0),
938 unpaid: r.given_unpaid_micros.unwrap_or(0),
939 },
940 }
941 }
942}
943
944impl Billing {
945 /// The day's work: read Cloudflare's bill and g1t's own counts,
946 /// reconcile, look for drift, measure unit costs, apply prices whose
947 /// day has come, and raise or clear alerts.
948 pub(crate) async fn costs_daily(&self, env: &Env, keeper: &crate::keeper::Keeper) -> Result<CostsRun> {
949 let mut run = CostsRun::default();
950 // The subscriptions first: they say when the billing cycle starts,
951 // which the bill is priced by. Not a problem for the run: the last
952 // read, or the estimate, stays.
953 if keeper.can_read_bill()
954 && let Err(error) = self.read_subscriptions(keeper).await
955 {
956 worker::console_error!("Cloudflare's subscriptions were not read: {error}");
957 }
958 let (since, until, bill_since) = match self.read_cloudflare(keeper, &mut run.problems).await? {
959 Some((since, until, lines, bill_since)) => {
960 run.lines = lines;
961 (since, until, Some(bill_since))
962 }
963 // Without the bill, still reconcile what g1t knows itself, over
964 // the same days the bill would be read for.
965 None => {
966 #[derive(Deserialize)]
967 struct Last {
968 day: Option<String>,
969 }
970 let last = self.db.prepare("SELECT MAX(day) AS day FROM margin_days").first::<Last>(None).await?.and_then(|l| l.day);
971 let (since, until) = costs::window(last.as_deref(), now_ms());
972 (since, until, None)
973 }
974 };
975 if let Err(error) = self.count_own(&since, &until).await {
976 run.problems.push(format!("g1t's own counts could not be read: {error}"));
977 }
978 self.snapshot_pending(&until).await?;
979 // Reconciled over the whole window sudo shows, not only the days the
980 // bill was read for: it reads only what is already kept, so a change
981 // in how a day is valued reaches every day shown at the next run.
982 let window = day_before(&until, costs::BACKFILL_DAYS - 1);
983 let reconcile_from = [Some(window), Some(since.clone()), bill_since].into_iter().flatten().min().unwrap_or_default();
984 run.days = self.reconcile_range(&reconcile_from, &until).await?;
985 let drift = self.find_drift(&until).await?;
986 run.proposals = self.measure_units(&until).await?;
987 self.apply_due_versions().await?;
988 run.alerts = self.raise_alerts(env, &until, &drift).await?;
989 if let Some(identity) = &self.identity
990 && let Err(error) = self.tell_owners_of_rises(identity).await
991 {
992 run.problems.push(format!("owners could not be told of a price rise: {error}"));
993 }
994 for problem in &run.problems {
995 worker::console_warn!("costs: {problem}");
996 }
997 Ok(run)
998 }
999
1000 /// What each month-end source had come to by the end of `day`.
1001 async fn snapshot_pending(&self, day: &str) -> Result<()> {
1002 self.db
1003 .prepare(
1004 "INSERT INTO pending_days (day, workspace, source, cost_micros, charge_micros)
1005 SELECT ?1, workspace, source, COALESCE(cost_micros, 0), COALESCE(charge_micros, 0) FROM pending_usage WHERE month = ?2
1006 ON CONFLICT (day, workspace, source) DO UPDATE SET cost_micros = excluded.cost_micros, charge_micros = excluded.charge_micros",
1007 )
1008 .bind(&[day.into(), day[..7].into()])?
1009 .run()
1010 .await?;
1011 Ok(())
1012 }
1013
1014 /// What customers were charged on the days, by workspace and key: every
1015 /// workspace's, or only `only`'s.
1016 async fn usage_rows(&self, since: &str, until: &str, only: Option<&str>) -> Result<Vec<UsageRow>> {
1017 let only_sql = only.unwrap_or("");
1018 #[derive(Deserialize)]
1019 struct Row {
1020 day: String,
1021 workspace: String,
1022 key: String,
1023 internal: i64,
1024 own_provider: i64,
1025 cash: Option<i64>,
1026 drawn: Option<i64>,
1027 gift: Option<i64>,
1028 trial: Option<i64>,
1029 oss: Option<i64>,
1030 covered: Option<i64>,
1031 discount: Option<i64>,
1032 cost: Option<i64>,
1033 }
1034 let charged_here = crate::storage::CHARGED_HERE.iter().map(|s| format!("'{s}'")).collect::<Vec<_>>().join(", ");
1035 let end = format!("{until}T23:59:59.999Z");
1036 let rows = self
1037 .db
1038 .prepare(format!(
1039 "SELECT substr(created_at, 1, 10) AS day, workspace,
1040 CASE WHEN task = 'deployments' AND reference LIKE 'deploy/%' THEN 'builds'
1041 WHEN task = 'plan' THEN '{planning}' ELSE COALESCE(task, 'other') END AS key,
1042 CASE WHEN workspace IN ({internal}) THEN 1 ELSE 0 END AS internal,
1043 CASE WHEN billed_to = 'workspace' THEN 1 ELSE 0 END AS own_provider,
1044 -SUM(amount_micros) AS cash,
1045 SUM(COALESCE(credit_micros, 0) + COALESCE(gift_micros, 0) + COALESCE(trial_micros, 0) + COALESCE(oss_micros, 0) + COALESCE(given_micros, 0)) AS drawn,
1046 SUM(COALESCE(gift_micros, 0)) AS gift,
1047 SUM(COALESCE(trial_micros, 0)) AS trial,
1048 SUM(COALESCE(oss_micros, 0)) AS oss,
1049 SUM(COALESCE(given_micros, 0)) AS covered,
1050 SUM(COALESCE(discount_micros, 0)) AS discount,
1051 SUM(COALESCE(cost_micros, 0)) AS cost
1052 FROM ledger
1053 WHERE kind = 'usage' AND created_at >= ?1 AND created_at <= ?2 AND COALESCE(task, '') NOT IN ({charged_here})
1054 AND (?3 = '' OR workspace = ?3)
1055 GROUP BY 1, 2, 3, 4, 5",
1056 internal = crate::sales::INTERNAL_SQL,
1057 planning = PLANNING_KEY
1058 ))
1059 .bind(&[since.into(), end.as_str().into(), only_sql.into()])?
1060 .all()
1061 .await?
1062 .results::<Row>()?;
1063 let mut internal = BTreeSet::new();
1064 let mut out: Vec<UsageRow> = rows
1065 .into_iter()
1066 .map(|r| {
1067 // A workspace's own model provider was paid there: no cost
1068 // to g1t. g1t's own workspaces are valued at price.
1069 let cost = if r.own_provider == 1 { 0 } else { r.cost.unwrap_or(0) };
1070 let cash = r.cash.unwrap_or(0);
1071 // A discount took its part below cost plus the margin: it is
1072 // valued at price and that part counted as given, so a
1073 // discounted sale never reads as margin lost.
1074 let discount = r.discount.unwrap_or(0).max(0);
1075 let paid = cash + r.drawn.unwrap_or(0) + discount;
1076 let value = usage_value(r.internal == 1, cost, paid, self.margin_percent);
1077 let given = if r.internal == 1 {
1078 Given { comped: value, ..Given::default() }
1079 } else if paid == 0 && cost > 0 {
1080 Given { free: value, ..Given::default() }
1081 } else {
1082 // A complimentary allowance is promotional: given, never money in.
1083 Given { free: r.covered.unwrap_or(0), trial: r.trial.unwrap_or(0), pool: r.oss.unwrap_or(0), discount, credit_promotional: r.gift.unwrap_or(0), ..Given::default() }
1084 };
1085 if r.internal == 1 {
1086 internal.insert(r.workspace.clone());
1087 }
1088 UsageRow { day: r.day, workspace: r.workspace, key: r.key, bucket: None, value, cash, cost, given }
1089 })
1090 .collect();
1091 // Credits from g1t: what promotional and goodwill credit paid for
1092 // is given, not money in; a refund gives money back on its day.
1093 let (mut draws, mut refunds) = self.credit_effects(since, until).await?;
1094 if let Some(only) = only {
1095 draws.retain(|(workspace, _)| workspace == only);
1096 refunds.retain(|r| r.workspace == only);
1097 }
1098 apply_credits(&mut out, &draws, &refunds);
1099 // Month-end sources, from their daily snapshots.
1100 #[derive(Deserialize)]
1101 struct Snap {
1102 day: String,
1103 workspace: String,
1104 source: String,
1105 cost_micros: i64,
1106 charge_micros: i64,
1107 }
1108 let snaps = self
1109 .db
1110 .prepare("SELECT day, workspace, source, cost_micros, charge_micros FROM pending_days WHERE day >= ?1 AND day <= ?2 AND (?3 = '' OR workspace = ?3)")
1111 .bind(&[day_before(since, 1).into(), until.into(), only_sql.into()])?
1112 .all()
1113 .await?
1114 .results::<Snap>()?
1115 .into_iter()
1116 .filter(|s| crate::storage::CHARGED_HERE.contains(&s.source.as_str()) || s.source == "domains")
1117 .map(|s| (s.day, s.workspace, s.source, s.cost_micros, s.charge_micros))
1118 .collect::<Vec<_>>();
1119 // Complimentary enrollments' days: their month-end meters were paid
1120 // by the allowance (or covered past it), never money in.
1121 #[derive(Deserialize)]
1122 struct Enrolled {
1123 workspace: String,
1124 starts_at: String,
1125 ends_at: Option<String>,
1126 }
1127 let enrolled = self
1128 .db
1129 .prepare("SELECT workspace, starts_at, ends_at FROM complimentary_periods WHERE starts_at <= ?2 AND (ends_at IS NULL OR ends_at >= ?1)")
1130 .bind(&[since.into(), end.as_str().into()])?
1131 .all()
1132 .await?
1133 .results::<Enrolled>()?;
1134 let gifted_on = |workspace: &str, day: &str| {
1135 enrolled.iter().any(|p| {
1136 p.workspace == workspace && &p.starts_at[..10.min(p.starts_at.len())] <= day && p.ends_at.as_deref().is_none_or(|e| &e[..10.min(e.len())] >= day)
1137 })
1138 };
1139 out.extend(
1140 pending_deltas(&snaps)
1141 .into_iter()
1142 .filter(|u| u.day.as_str() >= since)
1143 .map(|u| {
1144 if internal.contains(&u.workspace) {
1145 comped_meter(u)
1146 } else if gifted_on(&u.workspace, &u.day) {
1147 gifted_meter(u)
1148 } else {
1149 u
1150 }
1151 }),
1152 );
1153 // The plan's price, spread over the 30 days it pays for, so a month's
1154 // payment does not read as one very good day and 29 bad ones.
1155 #[derive(Deserialize)]
1156 struct Plan {
1157 day: String,
1158 workspace: String,
1159 micros: Option<i64>,
1160 }
1161 let plans = self
1162 .db
1163 .prepare(
1164 "SELECT substr(paid_at, 1, 10) AS day, workspace, SUM(amount_micros) AS micros FROM plan_payments
1165 WHERE paid_at >= ?1 AND paid_at <= ?2 AND (?3 = '' OR workspace = ?3) GROUP BY 1, 2",
1166 )
1167 .bind(&[day_before(since, PLAN_DAYS - 1).into(), end.as_str().into(), only_sql.into()])?
1168 .all()
1169 .await?
1170 .results::<Plan>()?;
1171 for p in plans {
1172 for (day, micros) in spread(&p.day, p.micros.unwrap_or(0), PLAN_DAYS) {
1173 if day.as_str() >= since && day.as_str() <= until {
1174 out.push(UsageRow { day, workspace: p.workspace.clone(), key: "plan".into(), bucket: None, value: micros, cash: micros, cost: 0, given: Given::default() });
1175 }
1176 }
1177 }
1178 // Charges without real money behind them are not money in.
1179 without_real_money(&mut out, self.payments_live_since().await?.as_deref());
1180 Ok(out)
1181 }
1182
1183 /// The day payments went live (`live_since`): kept in `cost_settings`
1184 /// the first time they are seen live, so charges from before it stay
1185 /// test money after the switch.
1186 pub(crate) async fn payments_live_since(&self) -> Result<Option<String>> {
1187 #[derive(Deserialize)]
1188 struct Row {
1189 value: String,
1190 }
1191 let live = self.stripe.as_ref().is_some_and(crate::stripe::Stripe::live);
1192 let kept = self
1193 .db
1194 .prepare("SELECT value FROM cost_settings WHERE key = 'payments_live_since'")
1195 .first::<Row>(None)
1196 .await?
1197 .map(|r| r.value)
1198 .filter(|v| v.len() >= 10);
1199 let today = rfc3339(now_ms())[..10].to_owned();
1200 let since = live_since(live, kept.as_deref(), &today);
1201 if let Some(day) = since.as_deref().filter(|_| kept.is_none()) {
1202 self.db
1203 .prepare(
1204 "INSERT INTO cost_settings (key, value, updated_at, updated_by) VALUES ('payments_live_since', ?1, ?2, 'billing')
1205 ON CONFLICT (key) DO UPDATE SET value = ?1, updated_at = ?2, updated_by = 'billing'",
1206 )
1207 .bind(&[day.into(), rfc3339(now_ms()).into()])?
1208 .run()
1209 .await?;
1210 }
1211 Ok(since)
1212 }
1213
1214 /// Which bucket each ledger key (and month-end source) is revenue of.
1215 async fn revenue_map(&self) -> Result<BTreeMap<String, String>> {
1216 #[derive(Deserialize)]
1217 struct Map {
1218 key: String,
1219 bucket: String,
1220 }
1221 Ok(self
1222 .db
1223 .prepare("SELECT key, bucket FROM revenue_map")
1224 .all()
1225 .await?
1226 .results::<Map>()?
1227 .into_iter()
1228 .map(|m| (m.key, m.bucket))
1229 .collect())
1230 }
1231
1232 /// What a testing reset of `workspace` is about to wipe that g1t paid
1233 /// for, a row per day and bucket: its whole ledger and month-end
1234 /// snapshots, valued as the reconciliation values them.
1235 pub(crate) async fn wiped_by_reset(&self, workspace: &str) -> Result<Vec<Wiped>> {
1236 let today = rfc3339(now_ms())[..10].to_owned();
1237 let rows = self.usage_rows(RESET_HISTORY_FROM, &today, Some(workspace)).await?;
1238 Ok(wiped(&rows, &self.revenue_map().await?, self.margin_percent))
1239 }
1240
1241 /// What testing resets kept for the days, as usage rows.
1242 async fn reset_rows(&self, since: &str, until: &str) -> Result<Vec<UsageRow>> {
1243 #[derive(Deserialize)]
1244 struct Kept {
1245 day: String,
1246 workspace: String,
1247 bucket: String,
1248 cost: Option<i64>,
1249 value: Option<i64>,
1250 }
1251 let kept = self
1252 .db
1253 .prepare(
1254 "SELECT day, workspace, bucket, SUM(cost_micros) AS cost, SUM(value_micros) AS value FROM reset_costs
1255 WHERE day >= ?1 AND day <= ?2 AND bucket <> '' GROUP BY day, workspace, bucket",
1256 )
1257 .bind(&[since.into(), until.into()])?
1258 .all()
1259 .await?
1260 .results::<Kept>()?;
1261 Ok(reset_usage(
1262 &kept.into_iter().map(|k| (k.day, k.workspace, k.bucket, k.cost.unwrap_or(0), k.value.unwrap_or(0))).collect::<Vec<_>>(),
1263 ))
1264 }
1265
1266 /// Reconciles the days and writes `margin_days` and `workspace_costs`.
1267 async fn reconcile_range(&self, since: &str, until: &str) -> Result<u32> {
1268 let rules = self.rules().await?;
1269 let revenue_map = self.revenue_map().await?;
1270 let lines = self
1271 .db
1272 .prepare("SELECT day, source, product, meter, quantity, cost_usd FROM cost_lines WHERE day >= ?1 AND day <= ?2")
1273 .bind(&[since.into(), until.into()])?
1274 .all()
1275 .await?
1276 .results::<LineRow>()?;
1277 let own = self
1278 .db
1279 .prepare("SELECT day, meter, workspace, quantity FROM own_counts WHERE day >= ?1 AND day <= ?2")
1280 .bind(&[since.into(), until.into()])?
1281 .all()
1282 .await?
1283 .results::<OwnRow>()?;
1284 let mut usage = self.usage_rows(since, until, None).await?;
1285 // What testing resets wiped: still paid for, now given away.
1286 usage.extend(self.reset_rows(since, until).await?);
1287 #[derive(Deserialize)]
1288 struct Internal {
1289 workspace: String,
1290 }
1291 let internal: BTreeSet<String> = self
1292 .db
1293 .prepare(format!("WITH i(workspace) AS ({}) SELECT DISTINCT workspace FROM i", crate::sales::INTERNAL_SQL))
1294 .all()
1295 .await?
1296 .results::<Internal>()?
1297 .into_iter()
1298 .map(|i| i.workspace)
1299 .collect();
1300 let (days, workspaces) = fold(&rules, &revenue_map, &lines, &own, &usage, &internal);
1301 let now = rfc3339(now_ms());
1302 self.db
1303 .batch(vec![
1304 self.db.prepare("DELETE FROM margin_days WHERE day >= ?1 AND day <= ?2").bind(&[since.into(), until.into()])?,
1305 self.db.prepare("DELETE FROM workspace_costs WHERE day >= ?1 AND day <= ?2").bind(&[since.into(), until.into()])?,
1306 ])
1307 .await?;
1308 for chunk in days.chunks(50) {
1309 let mut statements = Vec::with_capacity(chunk.len());
1310 for d in chunk {
1311 statements.push(
1312 self.db
1313 .prepare(
1314 "INSERT OR REPLACE INTO margin_days (day, bucket, cf_cost_micros, own_cost_micros, value_micros, cash_micros, cf_quantity, own_quantity, given_micros, given_comped_micros, given_free_micros, given_trial_micros, given_pool_micros, given_discount_micros, given_credit_promotional_micros, given_credit_goodwill_micros, given_reset_micros, given_unpaid_micros, computed_at)
1315 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1316 )
1317 .bind(&[
1318 d.day.as_str().into(),
1319 d.bucket.as_str().into(),
1320 (d.cf_cost_micros as f64).into(),
1321 (d.own_cost_micros as f64).into(),
1322 (d.value_micros as f64).into(),
1323 (d.cash_micros as f64).into(),
1324 d.cf_quantity.into(),
1325 d.own_quantity.into(),
1326 (d.given.total() as f64).into(),
1327 (d.given.comped as f64).into(),
1328 (d.given.free as f64).into(),
1329 (d.given.trial as f64).into(),
1330 (d.given.pool as f64).into(),
1331 (d.given.discount as f64).into(),
1332 (d.given.credit_promotional as f64).into(),
1333 (d.given.credit_goodwill as f64).into(),
1334 (d.given.reset as f64).into(),
1335 (d.given.unpaid as f64).into(),
1336 now.as_str().into(),
1337 ])?,
1338 );
1339 }
1340 self.db.batch(statements).await?;
1341 }
1342 for chunk in workspaces.chunks(50) {
1343 let mut statements = Vec::with_capacity(chunk.len());
1344 for w in chunk {
1345 statements.push(
1346 self.db
1347 .prepare("INSERT OR REPLACE INTO workspace_costs (day, workspace, bucket, cost_micros, revenue_micros, value_micros, given_micros) VALUES (?, ?, ?, ?, ?, ?, ?)")
1348 .bind(&[
1349 w.day.as_str().into(),
1350 w.workspace.as_str().into(),
1351 w.bucket.as_str().into(),
1352 (w.cost as f64).into(),
1353 (w.revenue as f64).into(),
1354 (w.value as f64).into(),
1355 (w.given.total() as f64).into(),
1356 ])?,
1357 );
1358 }
1359 self.db.batch(statements).await?;
1360 }
1361 Ok(costs::days_between(since, until).len() as u32)
1362 }
1363
1364 async fn margin_days(&self, since: &str, until: &str) -> Result<Vec<ProductDay>> {
1365 Ok(self
1366 .db
1367 .prepare("SELECT * FROM margin_days WHERE day >= ?1 AND day <= ?2 ORDER BY day, bucket")
1368 .bind(&[since.into(), until.into()])?
1369 .all()
1370 .await?
1371 .results::<MarginRow>()?
1372 .into_iter()
1373 .map(ProductDay::from)
1374 .collect())
1375 }
1376
1377 /// Drift over the last week, written to `cost_drift` (replacing the
1378 /// last run's), with unmapped Cloudflare meters as leaks.
1379 async fn find_drift(&self, until: &str) -> Result<Vec<(Drift, String)>> {
1380 let since = day_before(until, DRIFT_DAYS - 1);
1381 let settings = self.cost_settings().await?;
1382 let rules = self.rules().await?;
1383 let days = self.margin_days(&since, until).await?;
1384 let mut by: BTreeMap<String, Vec<ProductDay>> = BTreeMap::new();
1385 for d in days {
1386 by.entry(d.bucket.clone()).or_default().push(d);
1387 }
1388 // The same days' usage at list prices, before the included amounts:
1389 // what the price book is checked against (never the bill, which is
1390 // net of them).
1391 let lines = self
1392 .db
1393 .prepare("SELECT day, source, product, meter, quantity, cost_usd FROM cost_lines WHERE source = ?1 AND day >= ?2 AND day <= ?3")
1394 .bind(&[SOURCE_BILLABLE.into(), since.as_str().into(), until.into()])?
1395 .all()
1396 .await?
1397 .results::<LineRow>()?;
1398 let list = list_costs(&rules, &lines);
1399 let mut found = Vec::new();
1400 for (bucket, days) in &by {
1401 let bucket_rules: Vec<&Rule> = rules.iter().filter(|r| &r.bucket == bucket).collect();
1402 let threshold = bucket_rules.iter().map(|r| r.drift_percent).fold(f64::INFINITY, f64::min);
1403 let threshold = if threshold.is_finite() { threshold } else { 10.0 };
1404 let counted = bucket_rules.iter().any(|r| r.own_meter.is_some());
1405 let list_micros = list.get(bucket).copied().flatten();
1406 for drift in drifts(bucket, days, threshold, counted, settings.min_daily_cost_micros, list_micros) {
1407 let title = costs::bucket_title(bucket);
1408 let detail = match drift.kind {
1409 DriftKind::Count => format!(
1410 "{title}: g1t counted {}, Cloudflare {} over the last {DRIFT_DAYS} days ({:+.1}%). Customers are charged for what g1t counts; check what Cloudflare counts as a unit and change the repos service's operation_mapping (set_operation_mapping).",
1411 crate::features::thousands(drift.ours.max(0.0).round() as u64),
1412 crate::features::thousands(drift.cloudflare.max(0.0).round() as u64),
1413 drift.delta_percent.unwrap_or(0.0)
1414 ),
1415 DriftKind::Cost => format!(
1416 "{title}: the last {DRIFT_DAYS} days' usage comes to {} at Cloudflare's list prices, before the included amounts; the price book's cost of the same usage is {} ({:+.1}%). A price may be stale: see the proposals.",
1417 dollars(drift.cloudflare as i64),
1418 dollars(drift.ours as i64),
1419 drift.delta_percent.unwrap_or(0.0)
1420 ),
1421 DriftKind::Leak if bucket == UNMAPPED => {
1422 format!("Cloudflare charged {} for meters no mapping claims. Map them on Costs & margin.", dollars(drift.cloudflare as i64))
1423 }
1424 DriftKind::Leak => format!(
1425 "{title}: Cloudflare charged {} over the last {DRIFT_DAYS} days and customers were charged nothing for it.",
1426 dollars(drift.cloudflare as i64)
1427 ),
1428 };
1429 found.push((drift, detail));
1430 }
1431 }
1432 let now = rfc3339(now_ms());
1433 let mut statements = vec![self.db.prepare("DELETE FROM cost_drift")];
1434 for (drift, detail) in &found {
1435 statements.push(
1436 self.db
1437 .prepare("INSERT OR REPLACE INTO cost_drift (bucket, kind, ours, cloudflare, delta_percent, detail, found_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
1438 .bind(&[
1439 drift.bucket.as_str().into(),
1440 drift.kind.as_str().into(),
1441 drift.ours.into(),
1442 drift.cloudflare.into(),
1443 drift.delta_percent.map_or(JsValue::NULL, JsValue::from),
1444 detail.as_str().into(),
1445 now.as_str().into(),
1446 ])?,
1447 );
1448 }
1449 self.db.batch(statements).await?;
1450 Ok(found)
1451 }
1452
1453 /// Unit costs from the bill for mappings that scale to g1t's own count
1454 /// (git operations), proposed to the price book.
1455 async fn measure_units(&self, until: &str) -> Result<u32> {
1456 #[derive(Deserialize)]
1457 struct Scaled {
1458 product: String,
1459 meter: String,
1460 price_meter: String,
1461 own_meter: String,
1462 unit: Option<String>,
1463 }
1464 let scaled = self
1465 .db
1466 .prepare(
1467 "SELECT m.product, m.meter, m.price_meter, m.own_meter, p.unit FROM cost_map m LEFT JOIN prices p ON p.meter = m.price_meter
1468 WHERE m.scale_to_own = 1 AND m.price_meter IS NOT NULL AND m.own_meter IS NOT NULL",
1469 )
1470 .all()
1471 .await?
1472 .results::<Scaled>()?;
1473 let since = day_before(until, MEASURE_DAYS - 1);
1474 let rules = self.rules().await?;
1475 let mut proposed = 0;
1476 for s in scaled {
1477 #[derive(Deserialize)]
1478 struct Day {
1479 product: String,
1480 meter: String,
1481 quantity: f64,
1482 cost_usd: f64,
1483 }
1484 let lines = self
1485 .db
1486 .prepare("SELECT product, meter, quantity, cost_usd FROM cost_lines WHERE source = ?1 AND product = ?2 AND day >= ?3 AND day <= ?4")
1487 .bind(&[SOURCE_BILLABLE.into(), s.product.as_str().into(), since.as_str().into(), until.into()])?
1488 .all()
1489 .await?
1490 .results::<Day>()?;
1491 // Only the lines this very mapping claims.
1492 let mine: Vec<(f64, f64)> = lines
1493 .iter()
1494 .filter(|l| costs::classify(&rules, &l.product, &l.meter).is_some_and(|r| r.product == s.product && r.meter == s.meter))
1495 .map(|l| rate_line(&l.product, &l.meter, l.quantity, l.cost_usd))
1496 .collect();
1497 let Some(rate) = billed_rate(&mine) else { continue };
1498 let cf_units: f64 = mine.iter().map(|(q, _)| q).sum();
1499 #[derive(Deserialize)]
1500 struct Own {
1501 total: Option<f64>,
1502 }
1503 let own_units = self
1504 .db
1505 .prepare("SELECT SUM(quantity) AS total FROM own_counts WHERE meter = ?1 AND day >= ?2 AND day <= ?3")
1506 .bind(&[s.own_meter.as_str().into(), since.as_str().into(), until.into()])?
1507 .first::<Own>(None)
1508 .await?
1509 .and_then(|o| o.total)
1510 .unwrap_or(0.0);
1511 let Some(per_unit) = derived_unit_cost(rate, cf_units, own_units) else { continue };
1512 let size = unit_size(s.unit.as_deref().unwrap_or("1"));
1513 let measured = per_unit * size * 1_000_000.0;
1514 let reason = format!(
1515 "Cloudflare billed ${:.4} per 1,000 of its units and counted {:.2} of them for each one g1t counted over the last {MEASURE_DAYS} days ({} against {})",
1516 rate * 1000.0,
1517 cf_units / own_units,
1518 crate::features::thousands(cf_units.round() as u64),
1519 crate::features::thousands(own_units.round() as u64)
1520 );
1521 if self.propose(&s.price_meter, measured, &reason, "reconciler").await?.is_some() {
1522 proposed += 1;
1523 }
1524 }
1525 Ok(proposed)
1526 }
1527
1528 /// Opens, updates and closes margin alerts, and emails staff about new
1529 /// ones (and open ones each week).
1530 async fn raise_alerts(&self, env: &Env, until: &str, drift: &[(Drift, String)]) -> Result<u32> {
1531 let settings = self.cost_settings().await?;
1532 let since = day_before(until, u64::from(settings.alert_days.max(1)) - 1);
1533 let days = self.margin_days(&since, until).await?;
1534 let mut conditions: Vec<(String, String, String, String)> = Vec::new();
1535 // Each product under the floor.
1536 let mut by: BTreeMap<String, Vec<(String, i64, i64)>> = BTreeMap::new();
1537 let mut all: BTreeMap<String, (i64, i64)> = BTreeMap::new();
1538 for d in &days {
1539 let overall = all.entry(d.day.clone()).or_default();
1540 // What g1t gave away (comped workspaces, free periods, the
1541 // trial and the pools) is a budget it chose to spend, watched on
1542 // its own (budget.rs): not part of whether what is sold pays.
1543 overall.0 += d.cash_micros;
1544 overall.1 += (d.cost() - d.given.total()).max(0);
1545 if !OVERHEAD.contains(&d.bucket.as_str()) && d.bucket != UNMAPPED {
1546 by.entry(d.bucket.clone()).or_default().push((d.day.clone(), d.value_micros, d.cost()));
1547 }
1548 }
1549 let floor = settings.margin_floor_percent;
1550 let n = settings.alert_days as usize;
1551 for (bucket, series) in &by {
1552 if let Some((from, worst)) = breach(series, floor, n, settings.min_daily_cost_micros) {
1553 conditions.push((
1554 "margin".into(),
1555 bucket.clone(),
1556 format!("{}: margin under {floor:.0}% for {n} days running, as low as {worst:.1}%.", costs::bucket_title(bucket)),
1557 from,
1558 ));
1559 }
1560 }
1561 let series: Vec<(String, i64, i64)> = all.into_iter().map(|(day, (revenue, cost))| (day, revenue, cost)).collect();
1562 if let Some((from, worst)) = breach(&series, floor, n, settings.min_daily_cost_micros) {
1563 let tail = &series[series.len().saturating_sub(n)..];
1564 let (took, spent) = tail.iter().fold((0i64, 0i64), |(r, c), (_, revenue, cost)| (r + revenue, c + cost));
1565 conditions.push(("overall".into(), "g1t".into(), overall_detail(took, spent, n, floor, worst), from));
1566 }
1567 for (d, detail) in drift {
1568 let kind = if d.kind == DriftKind::Leak { "leak" } else { "drift" };
1569 conditions.push((kind.into(), format!("{}:{}", d.bucket, d.kind.as_str()), detail.clone(), until.to_owned()));
1570 }
1571 // Workspaces costing more than they pay.
1572 for (workspace, cost, revenue) in self.workspace_anomalies(until, &settings).await? {
1573 conditions.push((
1574 "workspace".into(),
1575 workspace.clone(),
1576 format!(
1577 "{workspace} cost g1t {} on Cloudflare over {ANOMALY_DAYS} days, and its usage was priced at {}: its prices are below cost.",
1578 dollars(cost),
1579 dollars(revenue)
1580 ),
1581 day_before(until, ANOMALY_DAYS - 1),
1582 ));
1583 }
1584
1585 let open = self
1586 .db
1587 .prepare("SELECT * FROM margin_alerts WHERE resolved_at IS NULL")
1588 .all()
1589 .await?
1590 .results::<AlertRow>()?;
1591 let now = now_ms();
1592 let stamp = rfc3339(now);
1593 let mut to_email: Vec<String> = Vec::new();
1594 let mut kept: BTreeSet<String> = BTreeSet::new();
1595 for (kind, subject, detail, from) in &conditions {
1596 match open.iter().find(|a| &a.kind == kind && &a.subject == subject) {
1597 Some(alert) => {
1598 kept.insert(alert.id.clone());
1599 self.db
1600 .prepare("UPDATE margin_alerts SET detail = ? WHERE id = ?")
1601 .bind(&[detail.as_str().into(), alert.id.as_str().into()])?
1602 .run()
1603 .await?;
1604 let stale = alert
1605 .emailed_at
1606 .as_deref()
1607 .and_then(g1t_contracts::time::parse_rfc3339)
1608 .is_none_or(|at| now.saturating_sub(at) >= REMIND_MS);
1609 if stale && kind != "workspace" {
1610 to_email.push(format!("Still open: {detail}"));
1611 kept.insert(format!("email:{}", alert.id));
1612 }
1613 }
1614 None => {
1615 let id = new_id("mal", now);
1616 self.db
1617 .prepare("INSERT INTO margin_alerts (id, kind, subject, detail, since, opened_at) VALUES (?, ?, ?, ?, ?, ?)")
1618 .bind(&[id.as_str().into(), kind.as_str().into(), subject.as_str().into(), detail.as_str().into(), from.as_str().into(), stamp.as_str().into()])?
1619 .run()
1620 .await?;
1621 kept.insert(id.clone());
1622 // A workspace's is for Reach out, not the inbox.
1623 if kind != "workspace" {
1624 to_email.push(detail.clone());
1625 }
1626 kept.insert(format!("email:{id}"));
1627 }
1628 }
1629 }
1630 for alert in &open {
1631 if !kept.contains(&alert.id) {
1632 self.db
1633 .prepare("UPDATE margin_alerts SET resolved_at = ? WHERE id = ?")
1634 .bind(&[stamp.as_str().into(), alert.id.as_str().into()])?
1635 .run()
1636 .await?;
1637 }
1638 }
1639 let to = env.var("COSTS_ALERT_EMAIL").map(|v| v.to_string()).unwrap_or_default();
1640 if !to_email.is_empty() && !to.trim().is_empty() {
1641 let subject = format!("[g1t costs] {} margin alert{}", to_email.len(), if to_email.len() == 1 { "" } else { "s" });
1642 match email_staff(env, to.trim(), &subject, &to_email).await {
1643 Ok(()) => {
1644 for marker in kept.iter().filter_map(|k| k.strip_prefix("email:")) {
1645 self.db
1646 .prepare("UPDATE margin_alerts SET emailed_at = ? WHERE id = ?")
1647 .bind(&[stamp.as_str().into(), marker.into()])?
1648 .run()
1649 .await?;
1650 }
1651 }
1652 Err(error) => worker::console_error!("could not email the margin alerts: {error}"),
1653 }
1654 }
1655 Ok(conditions.len() as u32)
1656 }
1657
1658 /// Workspaces costing g1t more than they pay over 30 days, not g1t's own.
1659 /// Each day's cost shared out to comped workspaces.
1660 async fn workspace_anomalies(&self, until: &str, settings: &CostSettings) -> Result<Vec<(String, i64, i64)>> {
1661 #[derive(Deserialize)]
1662 struct Row {
1663 workspace: String,
1664 cost: Option<i64>,
1665 revenue: Option<i64>,
1666 }
1667 let rows = self
1668 .db
1669 .prepare(format!(
1670 // Against what its usage was priced at, not the cash it
1671 // paid: a trial or a gift paying for usage is not a price
1672 // below cost.
1673 // Days from before value_micros was kept have none: only days
1674 // since the first one that does are compared.
1675 "SELECT workspace, SUM(cost_micros) AS cost, SUM(value_micros) AS revenue FROM workspace_costs
1676 WHERE day >= ?1 AND day <= ?2 AND workspace NOT IN ({})
1677 AND day >= (SELECT MIN(day) FROM workspace_costs WHERE value_micros > 0)
1678 GROUP BY workspace",
1679 crate::sales::INTERNAL_SQL
1680 ))
1681 .bind(&[day_before(until, ANOMALY_DAYS - 1).into(), until.into()])?
1682 .all()
1683 .await?
1684 .results::<Row>()?;
1685 let rows: Vec<(String, i64, i64)> = rows.into_iter().map(|r| (r.workspace, r.cost.unwrap_or(0), r.revenue.unwrap_or(0))).collect();
1686 Ok(anomalies(&rows, settings.anomaly_factor, settings.anomaly_floor_micros))
1687 }
1688
1689 /// For Reach out: workspaces with an open cost-over-revenue alert,
1690 /// each with its detail and cost.
1691 pub(crate) async fn costing_more_than_they_pay(&self) -> Result<Vec<(String, String, i64)>> {
1692 let alerts = self
1693 .db
1694 .prepare("SELECT * FROM margin_alerts WHERE resolved_at IS NULL AND kind = 'workspace' ORDER BY opened_at DESC LIMIT 50")
1695 .all()
1696 .await?
1697 .results::<AlertRow>()?;
1698 let mut out = Vec::new();
1699 for alert in alerts {
1700 #[derive(Deserialize)]
1701 struct Cost {
1702 cost: Option<i64>,
1703 }
1704 let cost = self
1705 .db
1706 .prepare("SELECT SUM(cost_micros) AS cost FROM workspace_costs WHERE workspace = ? AND day >= ?")
1707 .bind(&[alert.subject.as_str().into(), alert.since.as_str().into()])?
1708 .first::<Cost>(None)
1709 .await?
1710 .and_then(|c| c.cost)
1711 .unwrap_or(0);
1712 out.push((alert.subject, alert.detail, cost));
1713 }
1714 Ok(out)
1715 }
1716
1717 /// `admin_cost_alerts`: what sudo's banner says.
1718 pub(crate) async fn admin_cost_alerts(&self, _: AdminCostAlertsArgs) -> Result<Vec<MarginAlert>> {
1719 Ok(self
1720 .db
1721 .prepare("SELECT * FROM margin_alerts WHERE resolved_at IS NULL ORDER BY opened_at DESC LIMIT 50")
1722 .all()
1723 .await?
1724 .results::<AlertRow>()?
1725 .into_iter()
1726 .map(MarginAlert::from)
1727 .collect())
1728 }
1729
1730 /// `admin_run_costs`: the daily run, now.
1731 pub(crate) async fn admin_run_costs(&self, env: &Env, a: AdminRunCostsArgs) -> Result<Outcome<CostsRun>> {
1732 let keeper = crate::keeper::Keeper::from_env(env);
1733 let run = self.costs_daily(env, &keeper).await?;
1734 if !a.by.is_empty() {
1735 self.audit(
1736 "costs",
1737 "costs_run",
1738 &format!("{} lines, {} days, {} proposals, {} alerts", run.lines, run.days, run.proposals, run.alerts),
1739 &a.by,
1740 )
1741 .await?;
1742 }
1743 Ok(Outcome::Ok(run))
1744 }
1745
1746 /// `admin_set_cost_mapping`.
1747 pub(crate) async fn admin_set_cost_mapping(&self, a: AdminSetCostMappingArgs) -> Result<Outcome<CostMapping>> {
1748 let product = costs::slug(&a.product);
1749 let meter = if a.meter.trim() == "*" { "*".to_owned() } else { costs::slug(&a.meter) };
1750 if product.is_empty() || meter.is_empty() {
1751 return Ok(Outcome::fail(FailureCode::Invalid, "Name Cloudflare's product and a meter (or * for all of it)."));
1752 }
1753 let now = rfc3339(now_ms());
1754 if a.remove {
1755 self.db
1756 .prepare("DELETE FROM cost_map WHERE product = ? AND meter = ?")
1757 .bind(&[product.as_str().into(), meter.as_str().into()])?
1758 .run()
1759 .await?;
1760 self.audit("costs", "cost_mapping_removed", &format!("{product}/{meter}"), &a.by).await?;
1761 return Ok(Outcome::Ok(CostMapping {
1762 product,
1763 meter,
1764 bucket: String::new(),
1765 price_meter: None,
1766 own_meter: None,
1767 scale_to_own: false,
1768 drift_percent: 0.0,
1769 note: String::new(),
1770 updated_at: now,
1771 updated_by: a.by,
1772 }));
1773 }
1774 let bucket = costs::slug(&a.bucket);
1775 if bucket.is_empty() {
1776 return Ok(Outcome::fail(FailureCode::Invalid, "Say which of g1t's products it is a cost of."));
1777 }
1778 let clean = |v: Option<String>| v.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty());
1779 let (price_meter, own_meter) = (clean(a.price_meter), clean(a.own_meter));
1780 let drift = a.drift_percent.filter(|d| d.is_finite() && *d > 0.0).unwrap_or(10.0);
1781 self.db
1782 .prepare(
1783 "INSERT INTO cost_map (product, meter, bucket, price_meter, own_meter, scale_to_own, drift_percent, note, updated_at, updated_by)
1784 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
1785 ON CONFLICT (product, meter) DO UPDATE SET bucket = ?3, price_meter = ?4, own_meter = ?5, scale_to_own = ?6,
1786 drift_percent = ?7, note = ?8, updated_at = ?9, updated_by = ?10",
1787 )
1788 .bind(&[
1789 product.as_str().into(),
1790 meter.as_str().into(),
1791 bucket.as_str().into(),
1792 crate::optional(price_meter.as_deref()),
1793 crate::optional(own_meter.as_deref()),
1794 i32::from(a.scale_to_own).into(),
1795 drift.into(),
1796 a.note.trim().into(),
1797 now.as_str().into(),
1798 a.by.as_str().into(),
1799 ])?
1800 .run()
1801 .await?;
1802 self.audit("costs", "cost_mapping", &format!("{product}/{meter} → {bucket}"), &a.by).await?;
1803 Ok(Outcome::Ok(CostMapping {
1804 product,
1805 meter,
1806 bucket,
1807 price_meter,
1808 own_meter,
1809 scale_to_own: a.scale_to_own,
1810 drift_percent: drift,
1811 note: a.note.trim().to_owned(),
1812 updated_at: now,
1813 updated_by: a.by,
1814 }))
1815 }
1816
1817 /// `admin_costs`: the Costs & margin page.
1818 pub(crate) async fn admin_costs(&self, a: AdminCostsArgs, configured: bool) -> Result<CostsReport> {
1819 let until = rfc3339(now_ms())[..10].to_owned();
1820 let span = u64::from(a.days.unwrap_or(30).clamp(7, 90));
1821 let since = day_before(&until, span - 1);
1822 let days = self.margin_days(&since, &until).await?;
1823 let rules = self.rules().await?;
1824
1825 let mut products: BTreeMap<String, ProductMargin> = BTreeMap::new();
1826 let mut overall = OverallMargin::default();
1827 for d in &days {
1828 let p = products.entry(d.bucket.clone()).or_insert_with(|| ProductMargin {
1829 bucket: d.bucket.clone(),
1830 title: costs::bucket_title(&d.bucket),
1831 cost_source: if NOT_CLOUDFLARE.contains(&d.bucket.as_str()) { "ledger" } else { "cloudflare" }.into(),
1832 overhead: OVERHEAD.contains(&d.bucket.as_str()),
1833 ..ProductMargin::default()
1834 });
1835 p.cf_cost_micros += d.cf_cost_micros;
1836 p.own_cost_micros += d.own_cost_micros;
1837 p.value_micros += d.value_micros;
1838 p.cost_micros += d.cost();
1839 overall.cost_micros += d.cost();
1840 overall.given_micros += d.given.total();
1841 if NOT_CLOUDFLARE.contains(&d.bucket.as_str()) {
1842 overall.models_cost_micros += d.cost();
1843 } else {
1844 overall.cloudflare_cost_micros += d.cost();
1845 }
1846 overall.given_comped_micros += d.given.comped;
1847 overall.given_free_micros += d.given.free;
1848 overall.given_trial_micros += d.given.trial;
1849 overall.given_pool_micros += d.given.pool;
1850 overall.given_discount_micros += d.given.discount;
1851 overall.given_credit_promotional_micros += d.given.credit_promotional;
1852 overall.given_credit_goodwill_micros += d.given.credit_goodwill;
1853 overall.given_reset_micros += d.given.reset;
1854 overall.given_unpaid_micros += d.given.unpaid;
1855 let sold = (d.cost() - d.given.total()).max(0);
1856 if OVERHEAD.contains(&d.bucket.as_str()) {
1857 overall.plans_micros += d.cash_micros;
1858 overall.running_cost_micros += sold;
1859 } else if d.bucket == UNMAPPED {
1860 overall.usage_micros += d.cash_micros;
1861 overall.unmapped_cost_micros += sold;
1862 } else {
1863 overall.usage_micros += d.cash_micros;
1864 overall.usage_cost_micros += sold;
1865 }
1866 }
1867 for p in products.values_mut() {
1868 p.margin_micros = p.value_micros - p.cost_micros;
1869 p.margin_percent = margin_percent(p.value_micros, p.cost_micros);
1870 }
1871 let revenue = overall.usage_micros + overall.plans_micros;
1872 overall.margin_micros = revenue - overall.cost_micros;
1873 overall.margin_percent = margin_percent(revenue, overall.cost_micros);
1874 let sold = (overall.cost_micros - overall.given_micros).max(0);
1875 overall.sold_margin_micros = revenue - sold;
1876 overall.sold_margin_percent = margin_percent(revenue, sold);
1877 // The plan's included usage was paid for by the plan's price: it is
1878 // money in for the usage it covered, and out of what the plans
1879 // leave for running g1t.
1880 #[derive(Deserialize)]
1881 struct Included {
1882 micros: Option<i64>,
1883 }
1884 // Only what a plan paid for with real money (`without_real_money`).
1885 let live_since = self.payments_live_since().await?;
1886 overall.included_micros = match &live_since {
1887 None => 0,
1888 Some(live) => self
1889 .db
1890 .prepare(format!(
1891 "SELECT SUM(COALESCE(credit_micros, 0)) AS micros FROM ledger
1892 WHERE kind = 'usage' AND created_at >= ?1 AND created_at <= ?2 AND workspace NOT IN ({})",
1893 crate::sales::INTERNAL_SQL
1894 ))
1895 .bind(&[std::cmp::max(since.clone(), live.clone()).into(), format!("{until}T23:59:59.999Z").into()])?
1896 .first::<Included>(None)
1897 .await?
1898 .and_then(|r| r.micros)
1899 .unwrap_or(0),
1900 };
1901 let usage_in = overall.usage_micros + overall.included_micros;
1902 overall.usage_margin_micros = usage_in - overall.usage_cost_micros;
1903 overall.usage_margin_percent = margin_percent(usage_in, overall.usage_cost_micros);
1904 // Credits from g1t over the range: given, spent, and refunds' money
1905 // given back.
1906 overall.credits_given_micros = self
1907 .db
1908 .prepare("SELECT SUM(amount_micros) AS micros FROM credit_grants WHERE created_at >= ?1 AND created_at <= ?2")
1909 .bind(&[since.as_str().into(), format!("{until}T23:59:59.999Z").into()])?
1910 .first::<Included>(None)
1911 .await?
1912 .and_then(|r| r.micros)
1913 .unwrap_or(0);
1914 let (draws, refunds) = self.credit_effects(&since, &until).await?;
1915 overall.credits_used_micros = draws.iter().map(|(_, d)| d.micros).sum();
1916 overall.credits_refunded_micros = refunds.iter().map(|r| r.micros).sum();
1917 // Tax and card fees came in with payments but are neither cash nor
1918 // revenue: balances and plan payments are credited without them
1919 // (tax.rs), so cash above never holds them. Shown apart.
1920 (overall.tax_collected_micros, overall.card_fees_micros) = self.extras_between(&since, &until).await?;
1921 let mut products: Vec<ProductMargin> = products.into_values().collect();
1922 products.sort_by_key(|p| std::cmp::Reverse(p.cost_micros.max(p.value_micros)));
1923
1924 #[derive(Deserialize)]
1925 struct DriftRow {
1926 bucket: String,
1927 kind: String,
1928 ours: f64,
1929 cloudflare: f64,
1930 delta_percent: Option<f64>,
1931 detail: String,
1932 found_at: String,
1933 }
1934 let drift = self
1935 .db
1936 .prepare("SELECT * FROM cost_drift ORDER BY kind, bucket")
1937 .all()
1938 .await?
1939 .results::<DriftRow>()?
1940 .into_iter()
1941 .map(|r| CostDrift {
1942 title: costs::bucket_title(&r.bucket),
1943 bucket: r.bucket,
1944 kind: r.kind,
1945 ours: r.ours,
1946 cloudflare: r.cloudflare,
1947 delta_percent: r.delta_percent,
1948 detail: r.detail,
1949 found_at: r.found_at,
1950 })
1951 .collect();
1952
1953 #[derive(Deserialize)]
1954 struct Top {
1955 workspace: String,
1956 cost: Option<i64>,
1957 revenue: Option<i64>,
1958 given: Option<i64>,
1959 internal: i64,
1960 }
1961 let top_workspaces = self
1962 .db
1963 .prepare(format!(
1964 "SELECT workspace, SUM(cost_micros) AS cost, SUM(revenue_micros) AS revenue, SUM(given_micros) AS given,
1965 CASE WHEN workspace IN ({}) THEN 1 ELSE 0 END AS internal
1966 FROM workspace_costs WHERE day >= ?1 AND day <= ?2 GROUP BY workspace ORDER BY cost DESC LIMIT 15",
1967 crate::sales::INTERNAL_SQL
1968 ))
1969 .bind(&[since.as_str().into(), until.as_str().into()])?
1970 .all()
1971 .await?
1972 .results::<Top>()?
1973 .into_iter()
1974 .map(|t| WorkspaceCost { workspace: t.workspace, cost_micros: t.cost.unwrap_or(0), revenue_micros: t.revenue.unwrap_or(0), given_micros: t.given.unwrap_or(0), internal: t.internal == 1 })
1975 .collect();
1976
1977 #[derive(Deserialize)]
1978 struct Summary {
1979 source: String,
1980 product: String,
1981 meter: String,
1982 raw_name: String,
1983 unit: String,
1984 quantity: f64,
1985 cost_usd: f64,
1986 }
1987 let lines = self
1988 .db
1989 .prepare(
1990 "SELECT source, product, meter, MAX(raw_name) AS raw_name, MAX(unit) AS unit, SUM(quantity) AS quantity, SUM(cost_usd) AS cost_usd
1991 FROM cost_lines WHERE day >= ?1 AND day <= ?2 GROUP BY source, product, meter ORDER BY cost_usd DESC, product, meter LIMIT 200",
1992 )
1993 .bind(&[since.as_str().into(), until.as_str().into()])?
1994 .all()
1995 .await?
1996 .results::<Summary>()?
1997 .into_iter()
1998 .map(|l| CostLineSummary {
1999 bucket: costs::classify(&rules, &l.product, &l.meter).map(|r| r.bucket.clone()),
2000 product: l.product,
2001 meter: l.meter,
2002 raw_name: l.raw_name,
2003 unit: l.unit,
2004 source: l.source,
2005 quantity: l.quantity,
2006 cost_micros: micros(l.cost_usd),
2007 })
2008 .collect();
2009
2010 #[derive(Deserialize)]
2011 struct MapRow {
2012 product: String,
2013 meter: String,
2014 bucket: String,
2015 price_meter: Option<String>,
2016 own_meter: Option<String>,
2017 scale_to_own: i64,
2018 drift_percent: f64,
2019 note: String,
2020 updated_at: String,
2021 updated_by: String,
2022 }
2023 let mappings = self
2024 .db
2025 .prepare("SELECT * FROM cost_map ORDER BY product, meter")
2026 .all()
2027 .await?
2028 .results::<MapRow>()?
2029 .into_iter()
2030 .map(|m| CostMapping {
2031 product: m.product,
2032 meter: m.meter,
2033 bucket: m.bucket,
2034 price_meter: m.price_meter,
2035 own_meter: m.own_meter,
2036 scale_to_own: m.scale_to_own == 1,
2037 drift_percent: m.drift_percent,
2038 note: m.note,
2039 updated_at: m.updated_at,
2040 updated_by: m.updated_by,
2041 })
2042 .collect();
2043
2044 #[derive(Deserialize)]
2045 struct Fetched {
2046 at: Option<String>,
2047 }
2048 let fetched_at = self.db.prepare("SELECT MAX(fetched_at) AS at FROM cost_lines").first::<Fetched>(None).await?.and_then(|f| f.at);
2049
2050 // Cloudflare's subscriptions over the range, day by day as each
2051 // day's share of its billing cycle; and the cycle itself.
2052 let anchor = self.cycle_anchor().await?;
2053 let fixed = self.fixed_monthly(self.caps.fixed_monthly).await?;
2054 overall.subscriptions_micros = crate::cycle::accrued(fixed.monthly_micros, &since, &until, anchor);
2055 let cycle = self.cloudflare_cycle(&until, anchor, fixed.monthly_micros).await?;
2056 let bill_read = self.bill_read().await?;
2057 // What AI Gateway priced g1t's own provider traffic at, beside the
2058 // ledger's model cost (Cloudflare-billed requests are Cloudflare's).
2059 overall.gateway_cost_micros = self
2060 .db
2061 .prepare("SELECT SUM(cost_usd) AS cost FROM cost_lines WHERE source = ?1 AND day >= ?2 AND day <= ?3 AND substr(meter, 1, 11) <> ?4")
2062 .bind(&[costs::SOURCE_GATEWAY.into(), since.as_str().into(), until.as_str().into(), costs::GATEWAY_WHOLESALE.into()])?
2063 .first::<CostSum>(None)
2064 .await?
2065 .and_then(|c| c.cost)
2066 .map_or(0, micros);
2067 // The workspaces' shares of the cost, and what no one's usage carried.
2068 #[derive(Deserialize)]
2069 struct Shared {
2070 micros: Option<i64>,
2071 }
2072 let shared = self
2073 .db
2074 .prepare("SELECT SUM(cost_micros) AS micros FROM workspace_costs WHERE day >= ?1 AND day <= ?2")
2075 .bind(&[since.as_str().into(), until.as_str().into()])?
2076 .first::<Shared>(None)
2077 .await?
2078 .and_then(|s| s.micros)
2079 .unwrap_or(0);
2080 let unattributed_micros = unattributed(overall.cost_micros, shared);
2081
2082 Ok(CostsReport {
2083 configured,
2084 fetched_at,
2085 days: days
2086 .iter()
2087 .map(|d| CostDay {
2088 day: d.day.clone(),
2089 bucket: d.bucket.clone(),
2090 cf_cost_micros: d.cf_cost_micros,
2091 own_cost_micros: d.own_cost_micros,
2092 value_micros: d.value_micros,
2093 cash_micros: d.cash_micros,
2094 })
2095 .collect(),
2096 since,
2097 until,
2098 products,
2099 overall,
2100 drift,
2101 alerts: self.admin_cost_alerts(AdminCostAlertsArgs {}).await?,
2102 proposals: self.proposals().await?,
2103 versions: self.versions().await?,
2104 top_workspaces,
2105 lines,
2106 mappings,
2107 settings: self.cost_settings().await?,
2108 caps: self.spend_caps().await?,
2109 cycle,
2110 bill_read,
2111 unattributed_micros,
2112 })
2113 }
2114
2115 /// Cloudflare's billing cycle that `today` is in: its usage cost so far,
2116 /// by meter, with the included amounts, and where it is heading. None
2117 /// while nothing of it has been read.
2118 async fn cloudflare_cycle(&self, today: &str, anchor: u32, monthly_micros: i64) -> Result<Option<CloudflareCycle>> {
2119 #[derive(Deserialize)]
2120 struct Row {
2121 product: String,
2122 meter: String,
2123 raw_name: String,
2124 unit: String,
2125 quantity: f64,
2126 billable_quantity: Option<f64>,
2127 cost_usd: f64,
2128 basis: Option<String>,
2129 }
2130 let cycle = crate::cycle::cycle_of(today, anchor);
2131 let rows = self
2132 .db
2133 .prepare(
2134 "SELECT product, meter, MAX(raw_name) AS raw_name, MAX(unit) AS unit, SUM(quantity) AS quantity,
2135 SUM(billable_quantity) AS billable_quantity, SUM(cost_usd) AS cost_usd, MAX(basis) AS basis
2136 FROM cost_lines WHERE source = ?1 AND day >= ?2 AND day <= ?3 GROUP BY product, meter",
2137 )
2138 .bind(&[SOURCE_BILLABLE.into(), cycle.start.as_str().into(), today.into()])?
2139 .all()
2140 .await?
2141 .results::<Row>()?;
2142 if rows.is_empty() {
2143 return Ok(None);
2144 }
2145 let elapsed = cycle.days_elapsed(today);
2146 let meters = rows
2147 .into_iter()
2148 .map(|r| {
2149 let list = crate::cycle::list_price(&r.product, &r.meter);
2150 CycleMeter {
2151 included: list.map(|p| if p.daily { p.included * elapsed as f64 } else { p.included }),
2152 billable_quantity: r.billable_quantity.unwrap_or(0.0),
2153 cost_micros: micros(r.cost_usd),
2154 basis: r.basis.filter(|b| !b.is_empty()).unwrap_or_else(|| crate::cycle::BASIS_NONE.to_owned()),
2155 product: r.product,
2156 meter: r.meter,
2157 raw_name: r.raw_name,
2158 unit: r.unit,
2159 quantity: r.quantity,
2160 }
2161 })
2162 .collect();
2163 Ok(Some(cycle_report(&cycle, elapsed, meters, monthly_micros)))
2164 }
2165
2166 /// The last read of billable usage (`cost_reads`).
2167 async fn bill_read(&self) -> Result<Option<BillRead>> {
2168 #[derive(Deserialize)]
2169 struct Row {
2170 read_at: String,
2171 since: String,
2172 until: String,
2173 rows: u32,
2174 pages: u32,
2175 consumed_rows: u32,
2176 pricing_only_rows: u32,
2177 costed_rows: u32,
2178 }
2179 Ok(self
2180 .db
2181 .prepare("SELECT * FROM cost_reads WHERE source = ?1")
2182 .bind(&[SOURCE_BILLABLE.into()])?
2183 .first::<Row>(None)
2184 .await?
2185 .map(|r| BillRead {
2186 read_at: r.read_at,
2187 since: r.since,
2188 until: r.until,
2189 rows: r.rows,
2190 pages: r.pages,
2191 consumed_rows: r.consumed_rows,
2192 pricing_only_rows: r.pricing_only_rows,
2193 costed_rows: r.costed_rows,
2194 }))
2195 }
2196}
2197
2198#[derive(Deserialize)]
2199struct CostSum {
2200 cost: Option<f64>,
2201}
2202
2203/// Of `total` cost, what the workspaces' shares did not carry: running g1t
2204/// on days no workspace used anything. Never below zero.
2205pub(crate) fn unattributed(total: i64, shared: i64) -> i64 {
2206 (total - shared).max(0)
2207}
2208
2209/// The cycle as sudo shows it: the meters, most costly first, their total,
2210/// the average day and Cloudflare's projection.
2211pub(crate) fn cycle_report(cycle: &crate::cycle::Cycle, elapsed: u32, mut meters: Vec<CycleMeter>, monthly_micros: i64) -> CloudflareCycle {
2212 meters.sort_by(|a, b| b.cost_micros.cmp(&a.cost_micros).then(b.quantity.total_cmp(&a.quantity)).then(a.meter.cmp(&b.meter)));
2213 let usage: i64 = meters.iter().map(|m| m.cost_micros).sum();
2214 let days = cycle.days();
2215 CloudflareCycle {
2216 start: cycle.start.clone(),
2217 end: cycle.end.clone(),
2218 days,
2219 days_elapsed: elapsed,
2220 usage_micros: usage,
2221 projected_micros: crate::cycle::project(usage, elapsed, days),
2222 average_daily_micros: if elapsed > 0 { usage / elapsed as i64 } else { usage },
2223 subscriptions_micros: monthly_micros,
2224 meters,
2225 }
2226}
2227
2228#[cfg(test)]
2229mod tests {
2230 use super::*;
2231
2232 #[test]
2233 fn usage_nothing_paid_for_is_valued_at_price_and_paid_usage_at_what_was_paid() {
2234 // A free period: charged nothing, drawn from nothing.
2235 assert_eq!(usage_value(false, 1_000_000, 0, 20), 1_200_000);
2236 // Charged, or drawn from a trial: what was paid.
2237 assert_eq!(usage_value(false, 1_000_000, 1_200_000, 20), 1_200_000);
2238 assert_eq!(usage_value(false, 1_000_000, 900_000, 20), 900_000);
2239 // g1t's own: at price.
2240 assert_eq!(usage_value(true, 1_000_000, 0, 20), 1_200_000);
2241 // No cost, nothing paid: nothing.
2242 assert_eq!(usage_value(false, 0, 0, 20), 0);
2243 }
2244
2245 #[test]
2246 fn the_overall_alert_says_dollars_while_little_comes_in() {
2247 let small = overall_detail(90_000, 7_500_000, 3, 10.0, -8239.7);
2248 assert!(small.contains("took in $0.09 against $7.50"), "{small}");
2249 assert!(!small.contains('%'), "{small}");
2250 let real = overall_detail(30_000_000, 40_000_000, 3, 10.0, -33.3);
2251 assert!(real.contains("as low as -33.3%"), "{real}");
2252 }
2253
2254 fn rule(product: &str, meter: &str, bucket: &str, own: Option<&str>) -> Rule {
2255 Rule { product: product.into(), meter: meter.into(), bucket: bucket.into(), price_meter: None, own_meter: own.map(Into::into), drift_percent: 10.0 }
2256 }
2257
2258 fn rules() -> Vec<Rule> {
2259 vec![
2260 rule("containers", "*", "sandboxes", None),
2261 rule("workers", "*", "platform", None),
2262 rule("artifacts", "*", "git", Some("git_operations")),
2263 rule("artifacts", "events_", "git", Some("git_operations")),
2264 ]
2265 }
2266
2267 fn revenue_map() -> BTreeMap<String, String> {
2268 [("sandbox", "sandboxes"), ("git", "git"), ("plan", "platform")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
2269 }
2270
2271 fn line(day: &str, source: &str, product: &str, meter: &str, quantity: f64, cost: f64) -> LineRow {
2272 LineRow { day: day.into(), source: source.into(), product: product.into(), meter: meter.into(), quantity, cost_usd: cost }
2273 }
2274
2275 fn usage(day: &str, workspace: &str, key: &str, value: i64, cash: i64, cost: i64) -> UsageRow {
2276 UsageRow { day: day.into(), workspace: workspace.into(), key: key.into(), bucket: None, value, cash, cost, given: Given::default() }
2277 }
2278
2279 #[test]
2280 fn a_day_puts_the_bill_g1ts_counts_and_charges_side_by_side() {
2281 let lines = vec![
2282 line("2026-10-15", SOURCE_BILLABLE, "containers", "container_memory", 1000.0, 2.00),
2283 line("2026-10-15", SOURCE_BILLABLE, "artifacts", "artifacts_operations", 30_000.0, 3.00),
2284 // Artifacts' own events: not used while the bill has a count.
2285 line("2026-10-15", SOURCE_ARTIFACTS, "artifacts", "events_pull", 29_000.0, 0.0),
2286 line("2026-10-15", SOURCE_BILLABLE, "workers", "workers_cpu_ms", 1.0, 0.50),
2287 line("2026-10-15", SOURCE_BILLABLE, "browser_rendering", "browser_hours", 2.0, 0.25),
2288 ];
2289 let own = vec![
2290 OwnRow { day: "2026-10-15".into(), meter: "git_operations".into(), workspace: "acme".into(), quantity: 7_500.0 },
2291 OwnRow { day: "2026-10-15".into(), meter: "git_operations".into(), workspace: "beta".into(), quantity: 2_500.0 },
2292 ];
2293 let usage = vec![
2294 usage("2026-10-15", "acme", "sandbox", 2_400_000, 1_000_000, 2_000_000),
2295 usage("2026-10-15", "beta", "sandbox", 1_200_000, 1_200_000, 1_000_000),
2296 usage("2026-10-15", "acme", "git", 600_000, 600_000, 500_000),
2297 usage("2026-10-15", "acme", "implement", 120_000, 120_000, 100_000),
2298 usage("2026-10-15", "beta", "plan", 20_000_000, 20_000_000, 0),
2299 ];
2300 let (days, workspaces) = fold(&rules(), &revenue_map(), &lines, &own, &usage, &BTreeSet::new());
2301 let get = |bucket: &str| days.iter().find(|d| d.bucket == bucket).unwrap();
2302 let sandboxes = get("sandboxes");
2303 assert_eq!((sandboxes.cf_cost_micros, sandboxes.own_cost_micros, sandboxes.value_micros, sandboxes.cash_micros), (2_000_000, 3_000_000, 3_600_000, 2_200_000));
2304 let git = get("git");
2305 assert_eq!(git.cf_cost_micros, 3_000_000);
2306 assert_eq!((git.cf_quantity, git.own_quantity), (30_000.0, 10_000.0));
2307 assert_eq!(get("platform").value_micros, 20_000_000);
2308 // Not mapped: a leak until someone maps it.
2309 assert_eq!(get(UNMAPPED).cf_cost_micros, 250_000);
2310 // Models: no Cloudflare line, their cost is g1t's own.
2311 assert_eq!(get("models").cost(), 100_000);
2312 // Git's cost shared by g1t's own counts (Cloudflare gave none per
2313 // workspace here): three quarters to acme.
2314 let share = |ws: &str, bucket: &str| workspaces.iter().find(|w| w.workspace == ws && w.bucket == bucket).map(|w| (w.cost, w.revenue));
2315 assert_eq!(share("acme", "git"), Some((2_250_000, 600_000)));
2316 assert_eq!(share("beta", "git"), Some((750_000, 0)));
2317 // Every bucket's cost is shared out exactly.
2318 for d in &days {
2319 let shared: i64 = workspaces.iter().filter(|w| w.bucket == d.bucket).map(|w| w.cost).sum();
2320 assert_eq!(shared, d.cost(), "{}", d.bucket);
2321 }
2322 }
2323
2324 #[test]
2325 fn a_planning_run_is_model_cost_not_running_g1t() {
2326 // flagon-io's planning run on 2026-10-07 cost $0.0748 of model
2327 // calls; read under the ledger's task, `plan`, it went to running
2328 // g1t, where Cloudflare's bill is the cost, and the model cost was
2329 // lost from the statement and the drift.
2330 let usage = vec![
2331 usage("2026-10-07", "flagon-io", PLANNING_KEY, 89_741, 0, 74_784),
2332 usage("2026-10-07", "acme", "plan", 666_666, 666_666, 0),
2333 ];
2334 let (days, _) = fold(&rules(), &revenue_map(), &[], &[], &usage, &BTreeSet::new());
2335 let get = |bucket: &str| days.iter().find(|d| d.bucket == bucket).unwrap();
2336 assert_eq!((get("models").cost(), get("models").value_micros), (74_784, 89_741));
2337 assert_eq!((get("platform").own_cost_micros, get("platform").cash_micros), (0, 666_666));
2338 assert!(!revenue_map().contains_key(PLANNING_KEY));
2339 }
2340
2341 #[test]
2342 fn a_comped_workspaces_month_end_meters_are_given_never_money_in() {
2343 let snap = |day: &str, cost: i64, charge: i64| (day.to_string(), "flagon-io".to_string(), "cache".to_string(), cost, charge);
2344 let rows: Vec<UsageRow> = pending_deltas(&[snap("2026-10-07", 1, 2), snap("2026-10-08", 473, 568)]).into_iter().map(comped_meter).collect();
2345 assert_eq!(rows.iter().map(|r| (r.cash, r.value, r.given.comped)).collect::<Vec<_>>(), vec![(0, 2, 2), (0, 566, 566)]);
2346 let internal: BTreeSet<String> = ["flagon-io".to_string()].into();
2347 let (days, workspaces) = fold(&rules(), &revenue_map(), &[], &[], &rows, &internal);
2348 assert!(days.iter().all(|d| d.cash_micros == 0));
2349 assert!(workspaces.iter().all(|w| w.revenue == 0));
2350 }
2351
2352 #[test]
2353 fn artifacts_events_count_when_the_bill_does_not() {
2354 let lines = vec![
2355 line("2026-10-05", SOURCE_ARTIFACTS, "artifacts", "events_pull", 120.0, 0.0),
2356 line("2026-10-05", SOURCE_ARTIFACTS, "artifacts", "events_push", 30.0, 0.0),
2357 line("2026-10-05", SOURCE_ARTIFACTS, "artifacts", "events_ratelimited", 9.0, 0.0),
2358 ];
2359 let (days, _) = fold(&rules(), &revenue_map(), &lines, &[], &[], &BTreeSet::new());
2360 assert_eq!(days[0].cf_quantity, 150.0);
2361 assert_eq!(days[0].cf_cost_micros, 0);
2362 }
2363
2364 #[test]
2365 fn month_end_meters_are_told_by_the_day_from_snapshots() {
2366 let snap = |day: &str, cost: i64, charge: i64| (day.to_string(), "acme".to_string(), "git".to_string(), cost, charge);
2367 let rows = pending_deltas(&[snap("2026-10-30", 100, 120), snap("2026-10-31", 250, 300), snap("2026-11-01", 40, 48), snap("2026-11-02", 40, 48)]);
2368 assert_eq!(
2369 rows.iter().map(|r| (r.day.as_str(), r.cost, r.value)).collect::<Vec<_>>(),
2370 vec![("2026-10-30", 100, 120), ("2026-10-31", 150, 180), ("2026-11-01", 40, 48)]
2371 );
2372 }
2373
2374 #[test]
2375 fn a_plan_payment_is_spread_over_the_month_it_pays_for() {
2376 let days = spread("2026-10-01T00:00:00.000Z", 20_000_000, 30);
2377 assert_eq!(days.len(), 30);
2378 assert_eq!(days[0], ("2026-10-01".to_string(), 666_667));
2379 assert_eq!(days[29], ("2026-10-30".to_string(), 666_666));
2380 assert_eq!(days.iter().map(|d| d.1).sum::<i64>(), 20_000_000);
2381 assert!(spread("2026-10-01", 0, 30).is_empty());
2382 assert_eq!(dollars(17_024_000), "$17.02");
2383 assert_eq!(dollars(-27_668_620), "-$27.67");
2384 assert_eq!(dollars(63_000), "$0.063");
2385 }
2386
2387 #[test]
2388 fn margins_and_deltas() {
2389 assert_eq!(margin_percent(1_200_000, 1_000_000).map(|m| (m * 100.0).round() / 100.0), Some(16.67));
2390 assert_eq!(margin_percent(0, 5), None);
2391 assert_eq!(delta_percent(110.0, 100.0), Some(10.0));
2392 assert_eq!(delta_percent(1.0, 0.0), None);
2393 }
2394
2395 fn day(bucket: &str, cf: i64, own: i64, value: i64, cfq: f64, ownq: f64) -> ProductDay {
2396 ProductDay { day: "2026-10-15".into(), bucket: bucket.into(), cf_cost_micros: cf, own_cost_micros: own, value_micros: value, cash_micros: value, cf_quantity: cfq, own_quantity: ownq, given: Given::default() }
2397 }
2398
2399 #[test]
2400 fn counts_more_than_the_threshold_apart_are_drift() {
2401 // Cloudflare counted 30,000 operations where g1t counted 10,000:
2402 // binding reads, perhaps. -66.7%.
2403 let drift = drifts("git", &[day("git", 3_000_000, 1_500_000, 1_800_000, 30_000.0, 10_000.0)], 10.0, true, 100_000, Some(3_000_000.0));
2404 assert_eq!(drift.iter().map(|d| d.kind).collect::<Vec<_>>(), vec![DriftKind::Count, DriftKind::Cost]);
2405 assert!((drift[0].delta_percent.unwrap() + 66.666).abs() < 0.01);
2406 // 9% apart: within 10%.
2407 assert!(drifts("git", &[day("git", 1_000_000, 1_000_000, 1_200_000, 10_000.0, 10_900.0)], 10.0, true, 100_000, Some(1_000_000.0)).is_empty());
2408 // Uncounted products have no count drift.
2409 assert!(drifts("sandboxes", &[day("sandboxes", 1_000_000, 1_050_000, 1_200_000, 5.0, 0.0)], 10.0, false, 100_000, Some(1_000_000.0)).is_empty());
2410 }
2411
2412 #[test]
2413 fn cost_with_no_revenue_is_a_leak_but_not_for_running_g1t() {
2414 let leak = drifts("actions_cache", &[day("actions_cache", 400_000, 0, 0, 0.0, 0.0)], 10.0, false, 100_000, None);
2415 assert_eq!(leak.len(), 1);
2416 assert_eq!(leak[0].kind, DriftKind::Leak);
2417 assert!(drifts("platform", &[day("platform", 5_000_000, 0, 0, 0.0, 0.0)], 10.0, false, 100_000, None).is_empty());
2418 // Pennies say nothing.
2419 assert!(drifts("actions_cache", &[day("actions_cache", 50_000, 0, 0, 0.0, 0.0)], 10.0, false, 100_000, None).is_empty());
2420 assert!(drifts(UNMAPPED, &[day(UNMAPPED, 250_000, 0, 0, 0.0, 0.0)], 10.0, false, 100_000, None)[0].kind == DriftKind::Leak);
2421 }
2422
2423 /// A week of sandboxes mostly inside the cycle's included amounts:
2424 /// Cloudflare billed $0.0922 (the memory past 25 GiB-hours), and the
2425 /// same usage is $1.70 at list prices.
2426 fn sandbox_week() -> (Vec<Rule>, Vec<LineRow>) {
2427 let mut rules = rules();
2428 rules.push(rule("durable_objects", "durable_objects_compute_duration", "sandboxes", None));
2429 let lines = vec![
2430 line("2026-10-07", SOURCE_BILLABLE, "containers", "container_memory_per_gib_second", 126_870.0, 0.092_175),
2431 line("2026-10-07", SOURCE_BILLABLE, "containers", "container_vcpu", 12_000.0, 0.0),
2432 line("2026-10-07", SOURCE_BILLABLE, "containers", "container_disk_per_gb_second", 253_740.0, 0.0),
2433 line("2026-10-07", SOURCE_BILLABLE, "durable_objects", "durable_objects_compute_duration", 90_000.0, 0.0),
2434 // Not billable usage: no part of the list cost.
2435 line("2026-10-07", SOURCE_ARTIFACTS, "artifacts", "events_push", 40.0, 0.0),
2436 ];
2437 (rules, lines)
2438 }
2439
2440 #[test]
2441 fn usage_inside_the_included_amounts_is_not_a_stale_price() {
2442 let (rules, lines) = sandbox_week();
2443 let list = list_costs(&rules, &lines);
2444 let sandboxes = list["sandboxes"].unwrap();
2445 assert!((sandboxes - 1_699_936.8).abs() < 1.0, "{sandboxes}");
2446 // The price book's cost of the same usage is $1.69: within 1% of
2447 // the list, though Cloudflare billed $0.0922 after the included
2448 // amounts. Before, that read as +1733.6%.
2449 let week = day("sandboxes", 92_175, 1_690_000, 2_028_000, 0.0, 0.0);
2450 assert!(drifts("sandboxes", std::slice::from_ref(&week), 10.0, false, 100_000, Some(sandboxes)).is_empty());
2451 let net = drifts("sandboxes", &[week], 10.0, false, 100_000, Some(92_175.0));
2452 assert_eq!(net[0].kind, DriftKind::Cost, "billed against the price book was the false alarm");
2453 }
2454
2455 #[test]
2456 fn a_stale_price_is_still_drift() {
2457 let (rules, lines) = sandbox_week();
2458 let sandboxes = list_costs(&rules, &lines)["sandboxes"].unwrap();
2459 // The price book still costs the same usage at $1.20: a list price
2460 // rose and the book did not follow.
2461 let found = drifts("sandboxes", &[day("sandboxes", 92_175, 1_200_000, 1_440_000, 0.0, 0.0)], 10.0, false, 100_000, Some(sandboxes));
2462 assert_eq!(found.len(), 1);
2463 assert_eq!((found[0].kind, found[0].ours, found[0].cloudflare.round()), (DriftKind::Cost, 1_200_000.0, 1_699_937.0));
2464 assert!((found[0].delta_percent.unwrap() + 29.4).abs() < 0.1);
2465 // Nothing billed at all (the whole week inside the included
2466 // amounts) is checked all the same.
2467 assert_eq!(drifts("sandboxes", &[day("sandboxes", 0, 1_200_000, 1_440_000, 0.0, 0.0)], 10.0, false, 100_000, Some(sandboxes)).len(), 1);
2468 }
2469
2470 #[test]
2471 fn a_bucket_with_a_meter_with_no_list_price_is_not_checked() {
2472 let (rules, mut lines) = sandbox_week();
2473 lines.push(line("2026-10-07", SOURCE_BILLABLE, "artifacts", "storage", 3.0, 0.4));
2474 lines.push(line("2026-10-07", SOURCE_BILLABLE, "artifacts", "operations", 0.0, 0.0));
2475 let list = list_costs(&rules, &lines);
2476 assert_eq!(list["git"], None);
2477 assert!(list["sandboxes"].is_some());
2478 // No list cost: no cost drift, but a leak is still what was billed.
2479 assert!(drifts("git", &[day("git", 3_000_000, 1_000_000, 1_200_000, 0.0, 0.0)], 10.0, false, 100_000, None).is_empty());
2480 assert_eq!(drifts("git", &[day("git", 3_000_000, 0, 0, 0.0, 0.0)], 10.0, false, 100_000, None)[0].kind, DriftKind::Leak);
2481 }
2482
2483 #[test]
2484 fn a_unit_rate_is_the_list_price_where_there_is_one() {
2485 // Billed $0.20 for 11.16M CPU ms (9.16M past the included 30M, in
2486 // whole millions): $0.02 a million at list, whatever was billed.
2487 let (q, c) = rate_line("workers", "workers_cpu_ms", 11_160_000.0, 0.20);
2488 assert!((billed_rate(&[(q, c)]).unwrap() * 1e6 - 0.02).abs() < 1e-12);
2489 // No list price: what Cloudflare billed.
2490 assert_eq!(rate_line("artifacts", "operations", 1_000.0, 0.5), (1_000.0, 0.5));
2491 }
2492
2493 #[test]
2494 fn a_margin_alert_needs_n_days_in_a_row_under_the_floor() {
2495 let s = |d: &str, revenue: i64, cost: i64| (d.to_string(), revenue, cost);
2496 // 5%, 0%, -20%: three days under 10%.
2497 let series = vec![s("10-13", 1_200_000, 1_000_000), s("10-14", 1_050_000, 1_000_000), s("10-15", 1_000_000, 1_000_000), s("10-16", 1_000_000, 1_200_000)];
2498 let (from, worst) = breach(&series, 10.0, 3, 100_000).unwrap();
2499 assert_eq!(from, "10-14");
2500 assert!((worst + 20.0).abs() < 1e-9);
2501 // A good day in the window clears it.
2502 let mended = vec![s("10-14", 1_050_000, 1_000_000), s("10-15", 1_300_000, 1_000_000), s("10-16", 1_000_000, 1_200_000)];
2503 assert!(breach(&mended, 10.0, 3, 100_000).is_none());
2504 // Cost with no revenue at all is the worst margin there is.
2505 assert_eq!(breach(&[s("10-16", 0, 500_000)], 10.0, 1, 100_000).unwrap().1, -100.0);
2506 // Too little cost to judge.
2507 assert!(breach(&[s("10-16", 0, 5_000)], 10.0, 1, 100_000).is_none());
2508 assert!(breach(&series, 10.0, 9, 100_000).is_none());
2509 }
2510
2511 #[test]
2512 fn shared_costs_add_up_to_the_bill() {
2513 let w = |k: &str, v: f64| (k.to_string(), v);
2514 assert_eq!(attribute(100, &[w("a", 1.0), w("b", 1.0), w("c", 1.0)]), vec![("a".into(), 34), ("b".into(), 33), ("c".into(), 33)]);
2515 assert_eq!(attribute(10, &[w("a", 3.0), w("b", 1.0), w("a", 0.0)]), vec![("a".into(), 8), ("b".into(), 2)]);
2516 assert!(attribute(10, &[w("a", 0.0)]).is_empty());
2517 assert!(attribute(0, &[w("a", 1.0)]).is_empty());
2518 }
2519
2520 #[test]
2521 fn counts_are_compared_from_the_day_g1t_started_counting() {
2522 let on = |day: &str, cf: f64, own: f64| ProductDay { day: day.into(), bucket: "git".into(), cf_quantity: cf, own_quantity: own, ..ProductDay::default() };
2523 // Five days of Cloudflare's count before g1t's meter, then two that match.
2524 let days = vec![on("2026-10-01", 500.0, 0.0), on("2026-10-05", 300.0, 0.0), on("2026-10-06", 210.0, 231.0), on("2026-10-07", 450.0, 458.0)];
2525 assert!(drifts("git", &days, 10.0, true, 0, None).iter().all(|d| d.kind != DriftKind::Count));
2526 // A real gap on the days both counted still shows.
2527 let days = vec![on("2026-10-01", 500.0, 0.0), on("2026-10-06", 400.0, 231.0), on("2026-10-07", 600.0, 300.0)];
2528 let found = drifts("git", &days, 10.0, true, 0, None);
2529 let count = found.iter().find(|d| d.kind == DriftKind::Count).unwrap();
2530 assert_eq!((count.ours, count.cloudflare), (531.0, 1000.0));
2531 // A meter that never counted is compared over every day.
2532 let days = vec![on("2026-10-06", 400.0, 0.0)];
2533 assert!(drifts("git", &days, 10.0, true, 0, None).iter().any(|d| d.kind == DriftKind::Count));
2534 }
2535
2536 #[test]
2537 fn what_g1t_gives_away_is_kept_apart_from_what_it_sells() {
2538 let map = BTreeMap::new();
2539 // A comped workspace (all of it given), one in its trial (half paid
2540 // by the trial) and one paying in cash, all on models.
2541 let comped = usage("2026-10-15", "flagon", "agent", 1_200_000, 0, 1_000_000);
2542 let mut trial = usage("2026-10-15", "acme", "agent", 1_200_000, 600_000, 1_000_000);
2543 trial.given = Given { trial: 600_000, ..Given::default() };
2544 let paying = usage("2026-10-15", "beta", "agent", 1_200_000, 1_200_000, 1_000_000);
2545 // Nothing priced that day: free use.
2546 let free = usage("2026-10-15", "gamma", "agent", 0, 0, 1_000_000);
2547 let internal = BTreeSet::from(["flagon".to_string()]);
2548 let (days, workspaces) = fold(&[], &map, &[], &[], &[comped, trial, paying, free], &internal);
2549 let models = days.iter().find(|d| d.bucket == "models").unwrap();
2550 assert_eq!(models.cost(), 4_000_000);
2551 assert_eq!(models.given, Given { comped: 1_000_000, free: 1_000_000, trial: 500_000, ..Given::default() });
2552 let given = |w: &str| workspaces.iter().find(|x| x.workspace == w).unwrap().given.total();
2553 assert_eq!((given("flagon"), given("acme"), given("beta"), given("gamma")), (1_000_000, 500_000, 0, 1_000_000));
2554 }
2555
2556 #[test]
2557 fn a_discounted_sale_keeps_its_margin_and_counts_the_discount_as_given() {
2558 // $1 of model cost at 20%, sold to an account with 30% off: charged
2559 // $0.84, and $0.36 below cost plus the margin given (as usage_rows
2560 // reads the ledger: value at price, the discount part given).
2561 let mut sale = usage("2026-10-15", "acme", "agent", 1_200_000, 840_000, 1_000_000);
2562 sale.given = Given { discount: 360_000, ..Given::default() };
2563 let (days, _) = fold(&[], &BTreeMap::new(), &[], &[], &[sale], &BTreeSet::new());
2564 let models = days.iter().find(|d| d.bucket == "models").unwrap();
2565 assert_eq!(models.value_micros, 1_200_000);
2566 assert_eq!(models.given, Given { discount: 300_000, ..Given::default() });
2567 // What was sold (cost less given) still makes the margin.
2568 let sold = models.cost() - models.given.total();
2569 assert_eq!(margin_percent(models.cash_micros, sold).map(|m| m.round()), Some(17.0));
2570 }
2571
2572 fn draw(kind: CreditKind, reference: &str, task: Option<&str>, at: &str, micros: i64) -> (String, crate::grants::Draw) {
2573 let draw = crate::grants::Draw { grant: "crd_a".into(), kind, reference: reference.into(), task: task.map(Into::into), at: at.into(), micros };
2574 ("acme".to_owned(), draw)
2575 }
2576
2577 #[test]
2578 fn usage_paid_for_with_credit_is_given_not_money_in() {
2579 // $1.20 of usage on $1 of cost, all of it paid with promotional credit.
2580 let mut rows = vec![usage("2026-10-15", "acme", "implement", 1_200_000, 1_200_000, 1_000_000)];
2581 apply_credits(&mut rows, &[draw(CreditKind::Promotional, "run_1", Some("implement"), "2026-10-15T10:00:00Z", 1_200_000)], &[]);
2582 assert_eq!(rows[0].cash, 0);
2583 assert_eq!(rows[0].given, Given { credit_promotional: 1_200_000, ..Given::default() });
2584 let (days, workspaces) = fold(&[], &BTreeMap::new(), &[], &[], &rows, &BTreeSet::new());
2585 let models = days.iter().find(|d| d.bucket == "models").unwrap();
2586 // Valued at its price, none of it money in, all of its cost given:
2587 // the margin on what was sold is untouched by it.
2588 assert_eq!((models.value_micros, models.cash_micros), (1_200_000, 0));
2589 assert_eq!(models.given, Given { credit_promotional: 1_000_000, ..Given::default() });
2590 assert_eq!(models.cost() - models.given.total(), 0);
2591 assert_eq!(workspaces[0].given.total(), 1_000_000);
2592 // Half paid with goodwill credit: half the cost given, half sold.
2593 let mut rows = vec![usage("2026-10-15", "acme", "implement", 1_200_000, 1_200_000, 1_000_000)];
2594 apply_credits(&mut rows, &[draw(CreditKind::Goodwill, "run_1", Some("implement"), "2026-10-15T10:00:00Z", 600_000)], &[]);
2595 let (days, _) = fold(&[], &BTreeMap::new(), &[], &[], &rows, &BTreeSet::new());
2596 let models = days.iter().find(|d| d.bucket == "models").unwrap();
2597 assert_eq!(models.cash_micros, 600_000);
2598 assert_eq!(models.given, Given { credit_goodwill: 500_000, ..Given::default() });
2599 let sold = models.cost() - models.given.total();
2600 assert_eq!(margin_percent(models.cash_micros, sold).map(|m| m.round()), Some(17.0));
2601 }
2602
2603 #[test]
2604 fn what_a_refund_pays_for_is_paid_for_and_the_refund_comes_off_its_day() {
2605 // A refund's credit pays for usage: still money in, nothing given.
2606 let mut rows = vec![usage("2026-10-15", "acme", "implement", 1_200_000, 1_200_000, 1_000_000)];
2607 apply_credits(&mut rows, &[draw(CreditKind::Refund, "run_9", Some("implement"), "2026-10-15T10:00:00Z", 1_200_000)], &[]);
2608 assert_eq!((rows[0].cash, rows[0].given), (1_200_000, Given::default()));
2609 // The $3 refunded for Oct 2 comes off that day's money in, shared
2610 // over what was paid that day.
2611 let mut rows = vec![
2612 usage("2026-10-02", "acme", "implement", 4_000_000, 4_000_000, 3_000_000),
2613 usage("2026-10-02", "acme", "sandbox", 2_000_000, 2_000_000, 1_500_000),
2614 usage("2026-10-02", "beta", "implement", 9_000_000, 9_000_000, 7_000_000),
2615 ];
2616 let refund = crate::grants::Refunded { workspace: "acme".into(), day: "2026-10-02".into(), micros: 3_000_000 };
2617 apply_credits(&mut rows, &[], std::slice::from_ref(&refund));
2618 assert_eq!((rows[0].cash, rows[1].cash, rows[2].cash), (2_000_000, 1_000_000, 9_000_000));
2619 assert!(rows.iter().all(|r| r.given == Given::default()));
2620 // Nothing paid that day: a line of its own, money in less than nothing.
2621 let mut rows = vec![];
2622 apply_credits(&mut rows, &[], &[refund]);
2623 assert_eq!((rows[0].key.as_str(), rows[0].cash, rows[0].value), ("other", -3_000_000, 0));
2624 }
2625
2626 #[test]
2627 fn credit_spent_on_month_end_meters_is_a_line_of_its_own() {
2628 // Storage is reconciled from snapshots, not its ledger line: what
2629 // credit paid of it is its own row on the day it was charged.
2630 let mut rows = vec![usage("2026-10-01", "acme", "implement", 1_000, 1_000, 800)];
2631 apply_credits(&mut rows, &[draw(CreditKind::Goodwill, "storage/2026-09", Some("storage"), "2026-10-01T00:05:00Z", 2_000_000)], &[]);
2632 assert_eq!(rows.len(), 2);
2633 assert_eq!((rows[1].key.as_str(), rows[1].cash, rows[1].value), ("storage", -2_000_000, 0));
2634 assert_eq!(rows[1].given.credit_goodwill, 2_000_000);
2635 assert_eq!(rows[0].cash, 1_000);
2636 }
2637
2638 #[test]
2639 fn a_workspace_that_costs_more_than_it_pays_is_flagged() {
2640 let rows = vec![("acme".to_string(), 5_000_000, 1_000_000), ("beta".to_string(), 900_000, 0), ("gamma".to_string(), 2_000_000, 3_000_000)];
2641 let found = anomalies(&rows, 1.0, 1_000_000);
2642 assert_eq!(found, vec![("acme".to_string(), 5_000_000, 1_000_000)]);
2643 // At twice its revenue as the threshold, $5 against $3 is fine.
2644 assert!(anomalies(&[("acme".to_string(), 5_000_000, 3_000_000)], 2.0, 1_000_000).is_empty());
2645 }
2646
2647 #[test]
2648 fn a_git_operation_costs_what_cloudflare_counts_for_it() {
2649 // $0.15 per 1,000 of Cloudflare's operations, on the charged days.
2650 let rate = billed_rate(&[(10_000.0, 0.0), (20_000.0, 3.0), (30_000.0, 4.5), (5_000.0, 0.75)]).unwrap();
2651 assert!((rate - 0.000_15).abs() < 1e-12);
2652 // Cloudflare counted 3 for every 1 g1t did: binding reads count.
2653 let per_op = derived_unit_cost(rate, 300_000.0, 100_000.0).unwrap();
2654 let per_thousand_micros = per_op * unit_size("1,000 operations") * 1e6;
2655 assert!((per_thousand_micros - 450_000.0).abs() < 1e-6, "{per_thousand_micros}");
2656 // Too few of g1t's units to say.
2657 assert!(derived_unit_cost(rate, 3_000.0, 500.0).is_none());
2658 assert!(billed_rate(&[(10_000.0, 0.0)]).is_none());
2659 assert_eq!(unit_size("million requests"), 1e6);
2660 assert_eq!(unit_size("second"), 1.0);
2661 }
2662
2663 /// The case that started it: syntaqx's ~$8.62 of model usage was wiped
2664 /// by a testing reset, AI Gateway still priced all $11.11, and the
2665 /// ledger had $2.49 left.
2666 fn gateway_and_ledger(kept: bool) -> (Vec<ProductDay>, Vec<WorkspaceDay>) {
2667 let rules = vec![rule("ai_gateway_requests", "*", "models", None), rule("containers", "*", "sandboxes", None)];
2668 let lines = vec![
2669 line("2026-10-05", costs::SOURCE_GATEWAY, "ai_gateway_requests", "anthropic_claude_opus_5_5", 1.0, 11.11),
2670 line("2026-10-05", SOURCE_BILLABLE, "containers", "container_memory", 10.0, 0.30),
2671 ];
2672 let mut usage = vec![usage("2026-10-05", "acme", "implement", 2_988_000, 2_988_000, 2_490_000), usage("2026-10-05", "acme", "sandbox", 120_000, 120_000, 100_000)];
2673 if kept {
2674 // What the reset kept (reset_costs), read back for the day.
2675 usage.extend(reset_usage(&[
2676 ("2026-10-05".into(), "syntaqx".into(), "models".into(), 8_620_000, 10_344_000),
2677 ("2026-10-05".into(), "syntaqx".into(), "sandboxes".into(), 100_000, 120_000),
2678 // The reset's own row is not usage.
2679 ("2026-10-07".into(), "syntaqx".into(), String::new(), 0, 0),
2680 ]));
2681 }
2682 fold(&rules, &revenue_map(), &lines, &[], &usage, &BTreeSet::new())
2683 }
2684
2685 #[test]
2686 fn what_a_reset_kept_is_on_the_ledgers_side_of_model_cost() {
2687 let models = |days: &[ProductDay]| days.iter().find(|d| d.bucket == "models").cloned().unwrap();
2688 // Without it: the ledger's $2.49 of model cost.
2689 let (days, _) = gateway_and_ledger(false);
2690 assert_eq!(models(&days).own_cost_micros, 2_490_000);
2691 // With it: the ledger's model cost and the reset's add up to what
2692 // AI Gateway priced.
2693 let (days, _) = gateway_and_ledger(true);
2694 let m = models(&days);
2695 assert_eq!(m.own_cost_micros, 11_110_000);
2696 // Models are no longer compared with anything: no drift either way.
2697 assert!(drifts("models", &[m], 10.0, false, 100_000, None).is_empty());
2698 assert!(drifts("models", &[models(&gateway_and_ledger(false).0)], 10.0, false, 100_000, None).is_empty());
2699 // The reset's own row makes no bucket of its own.
2700 assert!(!days.iter().any(|d| d.bucket.is_empty()));
2701 }
2702
2703 #[test]
2704 fn what_a_reset_kept_is_given_away_as_testing_resets() {
2705 let (days, workspaces) = gateway_and_ledger(true);
2706 let models = days.iter().find(|d| d.bucket == "models").unwrap();
2707 // All of syntaqx's model cost is given, none of it money in.
2708 assert_eq!(models.given, Given { reset: 8_620_000, ..Given::default() });
2709 assert_eq!(models.cash_micros, 2_988_000);
2710 // Cloudflare's sandbox cost is shared by what each workspace's usage
2711 // cost: syntaqx's half is given too.
2712 let sandboxes = days.iter().find(|d| d.bucket == "sandboxes").unwrap();
2713 assert_eq!((sandboxes.cost(), sandboxes.given.reset), (300_000, 150_000));
2714 // Who g1t paid: syntaqx is still on it, all of its cost given.
2715 let syntaqx: Vec<&WorkspaceDay> = workspaces.iter().filter(|w| w.workspace == "syntaqx").collect();
2716 assert_eq!(syntaqx.iter().map(|w| w.cost).sum::<i64>(), 8_770_000);
2717 assert!(syntaqx.iter().all(|w| w.given.reset == w.cost && w.given.total() == w.cost && w.revenue == 0));
2718 // The statement reads it back from margin_days by why.
2719 let row = MarginRow {
2720 day: models.day.clone(),
2721 bucket: models.bucket.clone(),
2722 cf_cost_micros: models.cf_cost_micros,
2723 own_cost_micros: models.own_cost_micros,
2724 value_micros: models.value_micros,
2725 cash_micros: models.cash_micros,
2726 cf_quantity: 0.0,
2727 own_quantity: 0.0,
2728 given_comped_micros: Some(0),
2729 given_free_micros: Some(0),
2730 given_trial_micros: Some(0),
2731 given_pool_micros: Some(0),
2732 given_discount_micros: Some(0),
2733 given_credit_promotional_micros: Some(0),
2734 given_credit_goodwill_micros: Some(0),
2735 given_reset_micros: Some(models.given.reset),
2736 given_unpaid_micros: Some(0),
2737 };
2738 assert_eq!(ProductDay::from(row).given, models.given);
2739 }
2740
2741 #[test]
2742 fn test_mode_charges_are_never_money_in() {
2743 // A $12 sandbox charge and the $20 plan, both while payments were in
2744 // Stripe's test mode: valued as before, given as unpaid, no cash.
2745 let mut rows = vec![
2746 usage("2026-10-06", "acme", "sandbox", 12_000_000, 12_000_000, 10_000_000),
2747 UsageRow { day: "2026-10-06".into(), workspace: "acme".into(), key: "plan".into(), value: 666_667, cash: 666_667, ..UsageRow::default() },
2748 ];
2749 without_real_money(&mut rows, None);
2750 assert!(rows.iter().all(|r| r.cash == 0));
2751 // A comped workspace's charge is given once, as comped.
2752 let mut comped = vec![UsageRow { given: Given { comped: 500, ..Given::default() }, ..usage("2026-10-06", "flagon-io", "sandbox", 500, 500, 400) }];
2753 without_real_money(&mut comped, None);
2754 assert_eq!((comped[0].cash, comped[0].given.total()), (0, 500));
2755 assert_eq!(rows[0].given.unpaid, 12_000_000);
2756 assert_eq!(rows[0].value, 12_000_000);
2757 assert_eq!(rows[1].given.unpaid, 666_667);
2758 let (days, workspaces) = fold(&rules(), &revenue_map(), &[], &[], &rows, &BTreeSet::new());
2759 assert_eq!(days.iter().map(|d| d.cash_micros).sum::<i64>(), 0);
2760 let sandboxes = days.iter().find(|d| d.bucket == "sandboxes").unwrap();
2761 assert_eq!(sandboxes.given.unpaid, sandboxes.cost());
2762 assert!(workspaces.iter().all(|w| w.revenue == 0));
2763 // Once live: from that day on, it is money.
2764 let mut rows = vec![
2765 usage("2026-10-06", "acme", "sandbox", 1_000_000, 1_000_000, 800_000),
2766 usage("2026-10-07", "acme", "sandbox", 1_000_000, 1_000_000, 800_000),
2767 ];
2768 without_real_money(&mut rows, Some("2026-10-07"));
2769 assert_eq!((rows[0].cash, rows[0].given.unpaid), (0, 1_000_000));
2770 assert_eq!((rows[1].cash, rows[1].given.unpaid), (1_000_000, 0));
2771 // When payments went live is kept from the first time it is seen.
2772 assert_eq!(live_since(false, Some("2026-10-07"), "2026-10-09"), None);
2773 assert_eq!(live_since(true, None, "2026-10-09").as_deref(), Some("2026-10-09"));
2774 assert_eq!(live_since(true, Some("2026-10-07"), "2026-10-09").as_deref(), Some("2026-10-07"));
2775 }
2776
2777 #[test]
2778 fn workspaces_and_running_g1t_add_up_to_the_bill() {
2779 // Running g1t on a day with usage is shared; on a day with none it
2780 // is no one's, and the report says so.
2781 let lines = vec![
2782 line("2026-10-06", SOURCE_BILLABLE, "workers", "workers_cpu_ms", 1.0, 0.10),
2783 line("2026-10-07", SOURCE_BILLABLE, "workers", "workers_cpu_ms", 1.0, 0.20),
2784 line("2026-10-07", SOURCE_BILLABLE, "containers", "container_memory_per_gib_second", 1.0, 0.09),
2785 ];
2786 let usage = vec![usage("2026-10-07", "acme", "sandbox", 100, 100, 80), usage("2026-10-07", "beta", "sandbox", 300, 300, 240)];
2787 let (days, workspaces) = fold(&rules(), &revenue_map(), &lines, &[], &usage, &BTreeSet::new());
2788 let total: i64 = days.iter().map(ProductDay::cost).sum();
2789 let shared: i64 = workspaces.iter().map(|w| w.cost).sum();
2790 assert_eq!(total, 390_000);
2791 assert_eq!(unattributed(total, shared), 100_000);
2792 assert_eq!(shared + unattributed(total, shared), total);
2793 }
2794
2795 #[test]
2796 fn the_cycle_report_projects_as_cloudflare_does() {
2797 let cycle = crate::cycle::cycle_of("2026-10-09", 28);
2798 let meter = |meter: &str, cost: i64, quantity: f64| CycleMeter { meter: meter.into(), cost_micros: cost, quantity, ..CycleMeter::default() };
2799 let report = cycle_report(&cycle, 12, vec![meter("container_memory", 92_175, 126_870.0), meter("workers_cpu_ms", 200_000, 39_160_000.0), meter("d1_rows_read", 0, 61_820_000.0)], 30_000_000);
2800 assert_eq!((report.start.as_str(), report.end.as_str(), report.days, report.days_elapsed), ("2026-09-28", "2026-10-27", 30, 12));
2801 assert_eq!(report.usage_micros, 292_175);
2802 assert_eq!(report.projected_micros, 730_438);
2803 assert_eq!(report.average_daily_micros, 24_347);
2804 assert_eq!(report.meters[0].meter, "workers_cpu_ms");
2805 assert_eq!(report.meters[2].meter, "d1_rows_read");
2806 }
2807
2808 #[test]
2809 fn reconciling_again_gives_the_same_answer() {
2810 assert_eq!(gateway_and_ledger(true), gateway_and_ledger(true));
2811 // A reset's kept rows are read back exactly as kept: running it
2812 // again cannot count them twice.
2813 let kept = [("2026-10-05".to_string(), "syntaqx".to_string(), "models".to_string(), 8_620_000, 10_344_000)];
2814 assert_eq!(reset_usage(&kept), reset_usage(&kept));
2815 assert_eq!(reset_usage(&kept).len(), 1);
2816 }
2817}