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
874 linesCodeBlameRaw

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

Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request1//! The price book as versions, and how it changes.
2//!
3//! A price is its cost plus the markup, and costs move: Cloudflare's
4//! rates, how much CPU sandboxes use, what Artifacts turns out to count as
5//! an operation. So prices must move too, without surprising anyone and
6//! without g1t selling at a loss.
7//!
8//! - **Versions.** Every price is a row in `price_versions`, never changed
9//! once written. `prices` holds the version in force; a version waiting
10//! for its date is applied by the daily run, and recorded in
11//! `price_changes` (the public record on the pricing page). A charge
12//! records the version it was made at (`ledger.price_version`), so what a
13//! past statement says is always explained by the prices of then.
14//! - **Proposals.** The keeper and the reconciler measure costs; what they
15//! find is proposed (`price_proposals`). A move under 2% is noise. One
16//! within the guardrail (`auto_apply_percent`, 25%) is applied on its own
17//! when `auto_apply` is on. Anything larger, or more than four times off
18//! (suspect), waits for staff to approve or reject in sudo.
19//! - **Notice.** A fall applies at once: customers only gain. A rise
20//! applies `notice_days` (14) after it is decided, and a monthly meter's
21//! at the start of the month after that, so no month is charged at two
22//! prices. Owners of workspaces on the plan are emailed once per rise.
23//! Cost-plus means the rise does come: margin protection is for new usage
24//! after the notice, never retroactive.
25
26use g1t_contracts::billing::*;
27use g1t_contracts::time::{parse_rfc3339, rfc3339};
28use g1t_contracts::{FailureCode, Outcome, new_id};
29use g1t_kit::now_ms;
30use serde::Deserialize;
31use serde_json::Value;
32use worker::Result;
33
34use crate::Billing;
35
36/// Smaller moves are noise.
37pub(crate) const MIN_CHANGE: f64 = 0.02;
38/// A measurement outside this factor of the current cost is suspect: it
39/// is proposed for a person to look at, never applied on its own.
40pub(crate) const MAX_FACTOR: f64 = 4.0;
41
Billing, integrations, security and identity no longer serve g1t's own agents. Billing stops metering agent runs, model tokens and AI Gateway requests, drops its model catalogue and price-keeper model prices, and stops selling AI credit, which only ever paid for those; credit bought earlier still pays toward what is owed. A usage report, statement or invoice that holds an old agent or model meter shows it as "Other usage" rather than failing, and the get_ai_credit and buy_ai_credit API operations and MCP billing actions go. Integrations no longer connects model providers or routes models, and no longer assigns imported issues or alerts to g1t; a model provider already connected can still be disconnected. Security drops "Fix with g1t". Identity no longer creates agent tokens or puts agents on teams, a team's lead is a person, and run credentials are issued only for checks, the merge queue, merge checks, deployments and bumps; tokens and credentials already issued keep working until they expire. The reserved names g1t and g1t-agent stay reserved. No tables are dropped.42/// Meters from when g1t ran agents and sold model access: the agent rate,
43/// its weights, models at the provider's price, and the AI Gateway. They
44/// stay in the tables for the statements that name them, but are never
45/// shown as prices, proposed or charged again.
46pub(crate) const RETIRED_METERS: [&str; 8] = [
47 "agent_models",
48 "agent_tokens",
49 "agent_tokens_own",
50 "agent_token_weight_input",
51 "agent_token_weight_output",
52 "agent_token_weight_cache_read",
53 "agent_token_weight_cache_write",
54 "gateway_models",
55];
56
57/// Whether `meter` is one of the [`RETIRED_METERS`].
58pub(crate) fn retired(meter: &str) -> bool {
59 RETIRED_METERS.contains(&meter)
60}
61
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request62/// Meters charged once a month from the month's total (`storage`). A rise
63/// in one takes effect at the start of a month.
64pub(crate) const MONTHLY: [&str; 7] = ["git_operations", "private_storage", "actions_cache", "custom_domain_month", "embedding_tokens", "scan_cpu", "scan_rows"];
65
66/// The price meters a month-end source is charged at, for the ledger's
67/// `price_version`.
68pub(crate) fn meters_of(source: &str) -> &'static [&'static str] {
69 match source {
70 "git" => &["git_operations"],
71 "storage" => &["private_storage"],
72 "context" => &["embedding_tokens"],
73 "security" => &["scan_cpu", "scan_rows"],
74 "domains" => &["custom_domain_month"],
75 "cache" => &["actions_cache"],
76 _ => &[],
77 }
78}
79
80/// Rises smaller than this, in percent, are listed on the pricing page
81/// with their date but not emailed: the keeper moves sandbox seconds by a
82/// percent or two at a time, and an email for each would be noise.
83const EMAIL_RISE_PERCENT: f64 = 5.0;
84
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises85/// What a meter's `cost_micros` is (`PriceVersion::basis`): a weight of the
86/// agent rate's tokens is a multiplier; the agent rate and security
87/// activation are prices g1t sets, with no per-unit cost behind them (the
88/// models a run uses are charged apart, at cost); everything else is a
89/// cost g1t pays.
90pub(crate) fn basis_of(meter: &str) -> &'static str {
91 if meter.starts_with("agent_token_weight_") {
92 "weight"
93 } else if matches!(meter, "agent_tokens" | "agent_tokens_own") || meter == crate::features::SECURITY_METER {
94 "rate"
95 } else {
96 "cost"
97 }
98}
99
100/// Marks the proposals behind a meter's versions still waiting for their
101/// date as superseded, before a newer version replaces them; who decided
102/// it, and when, stay. Parameter: the meter.
103pub(crate) const SUPERSEDE_WAITING_SQL: &str = "UPDATE price_proposals SET status = 'superseded'
104 WHERE version_id IN (SELECT id FROM price_versions WHERE meter = ?1 AND applied_at IS NULL)";
105
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request106/// Owners told of rises per run, at most; the rest on the next run.
107const NOTICES_PER_RUN: usize = 40;
108
109/// What may change prices without a person.
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub(crate) struct Guard {
112 pub auto_apply: bool,
113 /// The largest move applied on its own, in percent either way.
114 pub auto_percent: f64,
115 /// Days between deciding a rise and charging it.
116 pub notice_days: u32,
117}
118
119impl From<&CostSettings> for Guard {
120 fn from(s: &CostSettings) -> Self {
121 Guard { auto_apply: s.auto_apply, auto_percent: s.auto_apply_percent, notice_days: s.notice_days }
122 }
123}
124
125#[derive(Clone, Debug, PartialEq)]
126pub(crate) enum Decision {
127 /// Too small to matter.
128 Nothing,
129 /// Applied without a person, from `effective_ms`.
130 Auto { effective_ms: u64 },
131 /// Waits for staff. `suspect` when the measurement is wildly off.
132 Approve { suspect: bool },
133}
134
135/// When a new cost takes effect: a fall at once; a rise after the notice
136/// period, and for a monthly meter at the start of the first month after
137/// it.
138pub(crate) fn effective_ms(current: f64, new: f64, now_ms: u64, notice_days: u32, monthly: bool) -> u64 {
139 if new <= current {
140 return now_ms;
141 }
142 let after = now_ms + u64::from(notice_days) * crate::costs::DAY_MS;
143 if !monthly {
144 return after;
145 }
146 let stamp = rfc3339(after);
147 if &stamp[8..] == "01T00:00:00.000Z" {
148 return after;
149 }
150 parse_rfc3339(&crate::credits::next_month_start(&stamp[..7])).unwrap_or(after)
151}
152
153/// What to do with a measured cost against the one in force (or the one
154/// already scheduled).
155pub(crate) fn decide(current: f64, measured: f64, guard: Guard, now_ms: u64, monthly: bool) -> Decision {
156 if !measured.is_finite() || measured <= 0.0 || !current.is_finite() || current <= 0.0 {
157 return Decision::Nothing;
158 }
159 let ratio = measured / current;
160 if (ratio - 1.0).abs() < MIN_CHANGE {
161 return Decision::Nothing;
162 }
163 if !(1.0 / MAX_FACTOR..=MAX_FACTOR).contains(&ratio) {
164 return Decision::Approve { suspect: true };
165 }
166 if guard.auto_apply && (ratio - 1.0).abs() * 100.0 <= guard.auto_percent {
167 return Decision::Auto { effective_ms: effective_ms(current, measured, now_ms, guard.notice_days, monthly) };
168 }
169 Decision::Approve { suspect: false }
170}
171
172/// A version of one meter's price.
173#[derive(Clone, Debug, PartialEq, Deserialize)]
174pub(crate) struct Version {
175 pub id: String,
176 pub meter: String,
177 pub version: u32,
178 pub cost_micros: f64,
179 pub markup_percent: u32,
180 pub effective_at: String,
181 pub reason: String,
182 pub created_by: String,
183 pub applied_at: Option<String>,
184}
185
186/// The version in force for `meter` at `at`: the newest whose date has
187/// come. Old versions never change, so a past month's charges are always
188/// explained by the version of then.
189pub(crate) fn in_force<'a>(versions: &'a [Version], meter: &str, at: &str) -> Option<&'a Version> {
190 versions
191 .iter()
192 .filter(|v| v.meter == meter && v.effective_at.as_str() <= at)
193 .max_by(|a, b| a.effective_at.cmp(&b.effective_at).then(a.version.cmp(&b.version)))
194}
195
196/// Settings from `cost_settings` rows, defaults for anything missing or
197/// unreadable.
198pub(crate) fn settings_from(rows: &[(String, String)]) -> CostSettings {
199 let mut s = CostSettings::default();
200 for (key, value) in rows {
201 let value = value.trim();
202 match key.as_str() {
203 "auto_apply" => s.auto_apply = value == "true",
204 "auto_apply_percent" => s.auto_apply_percent = value.parse().unwrap_or(s.auto_apply_percent),
205 "notice_days" => s.notice_days = value.parse().unwrap_or(s.notice_days),
206 "margin_floor_percent" => s.margin_floor_percent = value.parse().unwrap_or(s.margin_floor_percent),
207 "alert_days" => s.alert_days = value.parse().unwrap_or(s.alert_days),
208 "min_daily_cost_micros" => s.min_daily_cost_micros = value.parse().unwrap_or(s.min_daily_cost_micros),
209 "anomaly_factor" => s.anomaly_factor = value.parse().unwrap_or(s.anomaly_factor),
210 "anomaly_floor_micros" => s.anomaly_floor_micros = value.parse().unwrap_or(s.anomaly_floor_micros),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit211 "card_fee" => s.card_fee = value != "off",
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request212 _ => {}
213 }
214 }
215 s
216}
217
218/// Why settings cannot be saved, if they cannot.
219pub(crate) fn check_settings(s: &CostSettings) -> std::result::Result<(), String> {
220 if !(0.0..=100.0).contains(&s.auto_apply_percent) {
221 return Err("The guardrail is a percentage from 0 to 100.".into());
222 }
223 if s.notice_days > 90 {
224 return Err("Notice is at most 90 days.".into());
225 }
226 if !(-100.0..=100.0).contains(&s.margin_floor_percent) {
227 return Err("The margin floor is a percentage.".into());
228 }
229 if s.alert_days == 0 || s.alert_days > 30 {
230 return Err("Alert after 1 to 30 days.".into());
231 }
232 if s.min_daily_cost_micros < 0 || s.anomaly_floor_micros < 0 || !(s.anomaly_factor > 0.0 && s.anomaly_factor.is_finite()) {
233 return Err("Amounts and the factor must be positive.".into());
234 }
235 Ok(())
236}
237
238#[derive(Deserialize)]
239struct ProposalRow {
240 id: String,
241 meter: String,
242 current_cost_micros: f64,
243 proposed_cost_micros: f64,
244 reason: String,
245 source: String,
246 suspect: i64,
247 status: String,
248 created_at: String,
249 decided_at: Option<String>,
250 decided_by: Option<String>,
251 note: Option<String>,
252 version_id: Option<String>,
253 title: Option<String>,
254 unit: Option<String>,
255 markup_percent: Option<u32>,
256 effective_at: Option<String>,
257}
258
259impl From<ProposalRow> for PriceProposal {
260 fn from(r: ProposalRow) -> Self {
261 let change = if r.current_cost_micros > 0.0 { (r.proposed_cost_micros / r.current_cost_micros - 1.0) * 100.0 } else { 0.0 };
262 PriceProposal {
263 title: r.title.unwrap_or_else(|| r.meter.clone()),
264 unit: r.unit.unwrap_or_default(),
265 markup_percent: r.markup_percent.unwrap_or(20),
266 id: r.id,
267 meter: r.meter,
268 current_cost_micros: r.current_cost_micros,
269 proposed_cost_micros: r.proposed_cost_micros,
270 change_percent: change,
271 reason: r.reason,
272 source: r.source,
273 suspect: r.suspect != 0,
274 status: r.status,
275 created_at: r.created_at,
276 decided_at: r.decided_at,
277 decided_by: r.decided_by,
278 note: r.note,
279 effective_at: r.version_id.and(r.effective_at),
280 }
281 }
282}
283
284const PROPOSAL_SQL: &str = "SELECT p.*, pr.title, pr.unit, pr.markup_percent, v.effective_at
285 FROM price_proposals p
286 LEFT JOIN prices pr ON pr.meter = p.meter
287 LEFT JOIN price_versions v ON v.id = p.version_id";
288
289impl Billing {
290 pub(crate) async fn cost_settings(&self) -> Result<CostSettings> {
291 #[derive(Deserialize)]
292 struct Row {
293 key: String,
294 value: String,
295 }
296 let rows = self.db.prepare("SELECT key, value FROM cost_settings").all().await?.results::<Row>()?;
297 Ok(settings_from(&rows.into_iter().map(|r| (r.key, r.value)).collect::<Vec<_>>()))
298 }
299
300 pub(crate) async fn admin_set_cost_settings(&self, a: AdminSetCostSettingsArgs) -> Result<Outcome<CostSettings>> {
301 if let Err(why) = check_settings(&a.settings) {
302 return Ok(Outcome::fail(FailureCode::Invalid, why));
303 }
304 let s = &a.settings;
305 let now = rfc3339(now_ms());
306 let pairs = [
307 ("auto_apply", s.auto_apply.to_string()),
308 ("auto_apply_percent", s.auto_apply_percent.to_string()),
309 ("notice_days", s.notice_days.to_string()),
310 ("margin_floor_percent", s.margin_floor_percent.to_string()),
311 ("alert_days", s.alert_days.to_string()),
312 ("min_daily_cost_micros", s.min_daily_cost_micros.to_string()),
313 ("anomaly_factor", s.anomaly_factor.to_string()),
314 ("anomaly_floor_micros", s.anomaly_floor_micros.to_string()),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit315 ("card_fee", if s.card_fee { "on" } else { "off" }.to_owned()),
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request316 ];
317 let mut statements = Vec::new();
318 for (key, value) in &pairs {
319 statements.push(
320 self.db
321 .prepare(
322 "INSERT INTO cost_settings (key, value, updated_at, updated_by) VALUES (?1, ?2, ?3, ?4)
323 ON CONFLICT (key) DO UPDATE SET value = ?2, updated_at = ?3, updated_by = ?4",
324 )
325 .bind(&[(*key).into(), value.as_str().into(), now.as_str().into(), a.by.as_str().into()])?,
326 );
327 }
328 self.db.batch(statements).await?;
329 let detail = pairs.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(", ");
330 self.audit("costs", "cost_settings", &detail, &a.by).await?;
331 Ok(Outcome::Ok(self.cost_settings().await?))
332 }
333
334 /// The cost a new measurement is judged against: the newest version
335 /// scheduled, else the one in force.
336 async fn latest_cost(&self, meter: &str) -> Result<Option<(f64, u32)>> {
337 #[derive(Deserialize)]
338 struct Row {
339 cost_micros: f64,
340 markup_percent: u32,
341 }
342 let scheduled = self
343 .db
344 .prepare("SELECT cost_micros, markup_percent FROM price_versions WHERE meter = ? AND applied_at IS NULL ORDER BY version DESC LIMIT 1")
345 .bind(&[meter.into()])?
346 .first::<Row>(None)
347 .await?;
348 if let Some(row) = scheduled {
349 return Ok(Some((row.cost_micros, row.markup_percent)));
350 }
351 Ok(self
352 .db
353 .prepare("SELECT cost_micros, markup_percent FROM prices WHERE meter = ?")
354 .bind(&[meter.into()])?
355 .first::<Row>(None)
356 .await?
357 .map(|r| (r.cost_micros, r.markup_percent)))
358 }
359
360 /// Proposes a measured cost for a meter. Returns what happened, in
361 /// words, or None when there was nothing to do.
362 pub(crate) async fn propose(&self, meter: &str, measured: f64, reason: &str, source: &str) -> Result<Option<String>> {
363 let Some((current, markup)) = self.latest_cost(meter).await? else {
364 return Ok(None);
365 };
366 // Ten-thousandths of a micro are plenty; floating-point tails are not.
367 let measured = (measured * 10_000.0).round() / 10_000.0;
368 let settings = self.cost_settings().await?;
369 let now = now_ms();
370 let decision = decide(current, measured, Guard::from(&settings), now, MONTHLY.contains(&meter));
371 if decision == Decision::Nothing {
372 return Ok(None);
373 }
374 let stamp = rfc3339(now);
375 let id = new_id("ppr", now);
376 // A newer measurement replaces an open one.
377 self.db
378 .prepare("UPDATE price_proposals SET status = 'superseded', decided_at = ? WHERE meter = ? AND status = 'open'")
379 .bind(&[stamp.as_str().into(), meter.into()])?
380 .run()
381 .await?;
382 let (status, suspect) = match decision {
383 Decision::Auto { .. } => ("applied", false),
384 Decision::Approve { suspect } => ("open", suspect),
385 Decision::Nothing => unreachable!(),
386 };
387 self.db
388 .prepare(
389 "INSERT INTO price_proposals (id, meter, current_cost_micros, proposed_cost_micros, reason, source, suspect, status, created_at, decided_at, decided_by)
390 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
391 )
392 .bind(&[
393 id.as_str().into(),
394 meter.into(),
395 current.into(),
396 measured.into(),
397 reason.into(),
398 source.into(),
399 i32::from(suspect).into(),
400 status.into(),
401 stamp.as_str().into(),
402 crate::optional((status == "applied").then_some(stamp.as_str())),
403 crate::optional((status == "applied").then_some("guardrail")),
404 ])?
405 .run()
406 .await?;
407 if status == "open" {
408 return Ok(Some(format!(
409 "proposed {measured:.4} against {current:.4}{}, waiting for staff",
410 if suspect { " (far off: look before approving)" } else { "" }
411 )));
412 }
413 let Decision::Auto { effective_ms } = decision else { unreachable!() };
414 let version = self.schedule_version(meter, measured, markup, effective_ms, reason, source, Some(&id)).await?;
415 self.apply_due_versions().await?;
416 Ok(Some(format!("applied {measured:.4} (was {current:.4}) from {} as {version}", rfc3339(effective_ms))))
417 }
418
419 /// Writes the next version of a meter's price, to take effect at
420 /// `effective_ms`. Returns its id.
421 #[allow(clippy::too_many_arguments)]
422 pub(crate) async fn schedule_version(
423 &self,
424 meter: &str,
425 cost: f64,
426 markup: u32,
427 effective_ms: u64,
428 reason: &str,
429 by: &str,
430 proposal: Option<&str>,
431 ) -> Result<String> {
432 #[derive(Deserialize)]
433 struct Top {
434 version: Option<u32>,
435 }
436 let next = self
437 .db
438 .prepare("SELECT MAX(version) AS version FROM price_versions WHERE meter = ?")
439 .bind(&[meter.into()])?
440 .first::<Top>(None)
441 .await?
442 .and_then(|t| t.version)
443 .unwrap_or(0)
444 + 1;
445 let id = format!("pv_{meter}_{next}");
446 let now = rfc3339(now_ms());
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises447 // A newer decision replaces a rise still waiting for its date. The
448 // proposal behind it never took effect: superseded, not "applied"
449 // with no date it is in force from.
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request450 self.db
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises451 .batch(vec![
452 self.db.prepare(SUPERSEDE_WAITING_SQL).bind(&[meter.into()])?,
453 self.db.prepare("DELETE FROM price_versions WHERE meter = ? AND applied_at IS NULL").bind(&[meter.into()])?,
454 ])
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request455 .await?;
456 self.db
457 .prepare(
458 "INSERT INTO price_versions (id, meter, version, cost_micros, markup_percent, effective_at, reason, created_by, proposal_id, created_at)
459 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
460 )
461 .bind(&[
462 id.as_str().into(),
463 meter.into(),
464 next.into(),
465 cost.into(),
466 markup.into(),
467 rfc3339(effective_ms).into(),
468 reason.into(),
469 by.into(),
470 crate::optional(proposal),
471 now.as_str().into(),
472 ])?
473 .run()
474 .await?;
475 if let Some(proposal) = proposal {
476 self.db
477 .prepare("UPDATE price_proposals SET version_id = ? WHERE id = ?")
478 .bind(&[id.as_str().into(), proposal.into()])?
479 .run()
480 .await?;
481 }
482 Ok(id)
483 }
484
485 /// Puts every version whose date has come into the price book, oldest
486 /// first, each once, with a public record of the change.
487 pub(crate) async fn apply_due_versions(&self) -> Result<u32> {
488 let now = rfc3339(now_ms());
489 let due = self
490 .db
491 .prepare("SELECT * FROM price_versions WHERE applied_at IS NULL AND effective_at <= ? ORDER BY effective_at, version")
492 .bind(&[now.as_str().into()])?
493 .all()
494 .await?
495 .results::<Version>()?;
496 let mut applied = 0;
497 for v in due {
498 let claimed = self
499 .db
500 .prepare("UPDATE price_versions SET applied_at = ? WHERE id = ? AND applied_at IS NULL RETURNING id")
501 .bind(&[now.as_str().into(), v.id.as_str().into()])?
502 .first::<Value>(None)
503 .await?;
504 if claimed.is_none() {
505 continue;
506 }
507 let reason = if v.created_by.contains('@') { format!("{} (approved by g1t staff)", v.reason) } else { v.reason.clone() };
508 self.db
509 .batch(vec![
510 self.db
511 .prepare(
512 "INSERT INTO price_changes (id, meter, old_cost_micros, new_cost_micros, markup_percent, old_markup_percent, reason, created_at)
513 SELECT ?, meter, cost_micros, ?, ?, CASE WHEN markup_percent <> ? THEN markup_percent END, ?, ? FROM prices WHERE meter = ?",
514 )
515 .bind(&[
516 new_id("prc", now_ms()).into(),
517 v.cost_micros.into(),
518 v.markup_percent.into(),
519 v.markup_percent.into(),
520 reason.as_str().into(),
521 now.as_str().into(),
522 v.meter.as_str().into(),
523 ])?,
524 self.db
525 .prepare("UPDATE prices SET cost_micros = ?, markup_percent = ?, source = 'cloudflare', updated_at = ? WHERE meter = ?")
526 .bind(&[v.cost_micros.into(), v.markup_percent.into(), now.as_str().into(), v.meter.as_str().into()])?,
527 ])
528 .await?;
529 applied += 1;
530 }
531 Ok(applied)
532 }
533
534 /// The id of the price version in force for `meter` now, for the
535 /// ledger.
536 pub(crate) async fn version_now(&self, meter: &str) -> Result<Option<String>> {
537 let versions = self
538 .db
539 .prepare("SELECT * FROM price_versions WHERE meter = ? AND applied_at IS NOT NULL")
540 .bind(&[meter.into()])?
541 .all()
542 .await?
543 .results::<Version>()?;
544 Ok(in_force(&versions, meter, &rfc3339(now_ms())).map(|v| v.id.clone()))
545 }
546
547 pub(crate) async fn proposals(&self) -> Result<Vec<PriceProposal>> {
548 Ok(self
549 .db
550 .prepare(format!(
551 "{PROPOSAL_SQL} ORDER BY CASE WHEN p.status = 'open' THEN 0 ELSE 1 END, p.created_at DESC LIMIT 40"
552 ))
553 .all()
554 .await?
555 .results::<ProposalRow>()?
556 .into_iter()
557 .map(PriceProposal::from)
558 .collect())
559 }
560
561 pub(crate) async fn versions(&self) -> Result<Vec<PriceVersion>> {
562 Ok(self
563 .db
564 .prepare("SELECT * FROM price_versions ORDER BY CASE WHEN applied_at IS NULL THEN 0 ELSE 1 END, effective_at DESC, version DESC LIMIT 60")
565 .all()
566 .await?
567 .results::<Version>()?
568 .into_iter()
569 .map(|v| PriceVersion {
570 price_micros: Price::price_for(v.cost_micros, v.markup_percent),
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises571 basis: basis_of(&v.meter).to_owned(),
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request572 id: v.id,
573 meter: v.meter,
574 version: v.version,
575 cost_micros: v.cost_micros,
576 markup_percent: v.markup_percent,
577 effective_at: v.effective_at,
578 reason: v.reason,
579 created_by: v.created_by,
580 applied_at: v.applied_at,
581 })
582 .collect())
583 }
584
585 /// Prices not in force yet, for the pricing page's "coming" changes.
586 pub(crate) async fn coming_changes(&self) -> Result<Vec<PriceChange>> {
587 #[derive(Deserialize)]
588 struct Row {
589 meter: String,
590 old_cost_micros: Option<f64>,
591 cost_micros: f64,
592 markup_percent: u32,
593 reason: String,
594 created_at: String,
595 effective_at: String,
596 }
597 Ok(self
598 .db
599 .prepare(
600 "SELECT v.meter, p.cost_micros AS old_cost_micros, v.cost_micros, v.markup_percent, v.reason, v.created_at, v.effective_at
601 FROM price_versions v LEFT JOIN prices p ON p.meter = v.meter
602 WHERE v.applied_at IS NULL ORDER BY v.effective_at",
603 )
604 .all()
605 .await?
606 .results::<Row>()?
607 .into_iter()
608 .map(|r| PriceChange {
609 old_cost_micros: r.old_cost_micros.unwrap_or(r.cost_micros),
610 meter: r.meter,
611 new_cost_micros: r.cost_micros,
612 markup_percent: r.markup_percent,
613 old_markup_percent: None,
614 reason: r.reason,
615 created_at: r.created_at,
616 effective_at: Some(r.effective_at),
617 })
618 .collect())
619 }
620
621 /// `admin_decide_proposal`: an approved fall applies now; an approved
622 /// rise after the notice period.
623 pub(crate) async fn admin_decide_proposal(&self, a: AdminDecideProposalArgs) -> Result<Outcome<PriceProposal>> {
624 let found = self
625 .db
626 .prepare(format!("{PROPOSAL_SQL} WHERE p.id = ?"))
627 .bind(&[a.id.as_str().into()])?
628 .first::<ProposalRow>(None)
629 .await?;
630 let Some(found) = found else {
631 return Ok(Outcome::fail(FailureCode::NotFound, "No such proposal."));
632 };
633 if found.status != "open" {
634 return Ok(Outcome::fail(FailureCode::Conflict, format!("This proposal is already {}.", found.status)));
635 }
636 let approve = match a.decision.as_str() {
637 "approve" => true,
638 "reject" => false,
639 _ => return Ok(Outcome::fail(FailureCode::Invalid, "Approve or reject.")),
640 };
641 if !approve && a.note.trim().is_empty() {
642 return Ok(Outcome::fail(FailureCode::Invalid, "Say why it is rejected, for whoever measures it next."));
643 }
644 let now = now_ms();
645 let stamp = rfc3339(now);
646 self.db
647 .prepare("UPDATE price_proposals SET status = ?, decided_at = ?, decided_by = ?, note = ? WHERE id = ? AND status = 'open'")
648 .bind(&[
649 if approve { "approved" } else { "rejected" }.into(),
650 stamp.as_str().into(),
651 a.by.as_str().into(),
652 a.note.trim().into(),
653 a.id.as_str().into(),
654 ])?
655 .run()
656 .await?;
657 if approve {
658 let settings = self.cost_settings().await?;
659 let (current, markup) = self.latest_cost(&found.meter).await?.unwrap_or((found.current_cost_micros, 20));
660 let effective = effective_ms(current, found.proposed_cost_micros, now, settings.notice_days, MONTHLY.contains(&found.meter.as_str()));
661 self.schedule_version(&found.meter, found.proposed_cost_micros, markup, effective, &found.reason, &a.by, Some(&found.id))
662 .await?;
663 self.apply_due_versions().await?;
664 }
665 self.audit(
666 "costs",
667 if approve { "price_approved" } else { "price_rejected" },
668 &format!("{}: {:.4} to {:.4}. {}", found.meter, found.current_cost_micros, found.proposed_cost_micros, a.note.trim()),
669 &a.by,
670 )
671 .await?;
672 let row = self
673 .db
674 .prepare(format!("{PROPOSAL_SQL} WHERE p.id = ?"))
675 .bind(&[a.id.as_str().into()])?
676 .first::<ProposalRow>(None)
677 .await?;
678 Ok(match row {
679 Some(row) => Outcome::Ok(row.into()),
680 None => Outcome::fail(FailureCode::NotFound, "No such proposal."),
681 })
682 }
683
684 /// Emails owners of workspaces on the plan about each rise still to
685 /// come, once per rise per workspace.
686 pub(crate) async fn tell_owners_of_rises(&self, identity: &worker::Fetcher) -> Result<()> {
687 #[derive(Deserialize)]
688 struct Rise {
689 id: String,
690 title: Option<String>,
691 old_cost: f64,
692 cost_micros: f64,
693 markup_percent: u32,
694 unit: Option<String>,
695 effective_at: String,
696 reason: String,
697 }
698 let rises = self
699 .db
700 .prepare(
701 "SELECT v.id, p.title, p.cost_micros AS old_cost, v.cost_micros, v.markup_percent, p.unit, v.effective_at, v.reason
702 FROM price_versions v JOIN prices p ON p.meter = v.meter
703 WHERE v.applied_at IS NULL AND v.cost_micros > p.cost_micros * ?",
704 )
705 .bind(&[(1.0 + EMAIL_RISE_PERCENT / 100.0).into()])?
706 .all()
707 .await?
708 .results::<Rise>()?;
709 let mut sent = 0;
710 for rise in rises {
711 #[derive(Deserialize)]
712 struct Workspace {
713 workspace: String,
714 }
715 let workspaces = self
716 .db
717 .prepare(
718 "SELECT DISTINCT workspace FROM subscriptions WHERE feature = 'plan' AND status IN ('active', 'canceling')
719 AND workspace NOT IN (SELECT workspace FROM price_notices WHERE version_id = ?) LIMIT ?",
720 )
721 .bind(&[rise.id.as_str().into(), ((NOTICES_PER_RUN - sent) as u32).into()])?
722 .all()
723 .await?
724 .results::<Workspace>()?;
725 let title = rise.title.clone().unwrap_or_default();
726 let unit = rise.unit.clone().unwrap_or_default();
727 let price = |cost: f64| crate::features::dollars(Price::price_for(cost, rise.markup_percent).round() as i64);
728 let intro = format!(
729 "From {}, {title} on g1t goes from {} to {} per {unit}. It is what g1t pays Cloudflare plus 20%, and the cost moved: {} Nothing already charged changes.",
730 &rise.effective_at[..10],
731 price(rise.old_cost),
732 price(rise.cost_micros),
733 rise.reason
734 );
735 for Workspace { workspace } in workspaces {
736 let args = g1t_contracts::identity::NotifyOwnersArgs {
737 workspace: workspace.clone(),
738 subject: format!("g1t: {title} costs more from {}", &rise.effective_at[..10]),
739 intro: intro.clone(),
740 action: "See prices".to_owned(),
741 link: "https://g1t.sh/pricing".to_owned(),
742 footer: "You get this because you own a workspace on the g1t plan. How prices follow costs: https://docs.g1t.sh/guides/usage-and-billing/#how-prices-are-set".to_owned(),
743 };
744 // Recorded whether or not anyone was there to tell.
745 if let Err(error) = g1t_kit::call::<_, u32>(identity, "notify_owners", &args).await {
746 worker::console_error!("could not tell {workspace} of a price rise: {error}");
747 continue;
748 }
749 self.db
750 .prepare("INSERT OR IGNORE INTO price_notices (version_id, workspace, sent_at) VALUES (?, ?, ?)")
751 .bind(&[rise.id.as_str().into(), workspace.as_str().into(), rfc3339(now_ms()).into()])?
752 .run()
753 .await?;
754 sent += 1;
755 if sent >= NOTICES_PER_RUN {
756 return Ok(());
757 }
758 }
759 }
760 Ok(())
761 }
762}
763
764#[cfg(test)]
765mod tests {
766 use super::*;
767
768 const NOW: &str = "2026-10-06T04:17:00.000Z";
769
770 fn now() -> u64 {
771 parse_rfc3339(NOW).unwrap()
772 }
773
774 fn guard() -> Guard {
775 Guard { auto_apply: true, auto_percent: 25.0, notice_days: 14 }
776 }
777
778 #[test]
779 fn small_moves_are_noise_and_wild_ones_wait_for_a_person() {
780 assert_eq!(decide(21.0, 21.2, guard(), now(), false), Decision::Nothing);
781 assert_eq!(decide(21.0, 0.0, guard(), now(), false), Decision::Nothing);
782 assert_eq!(decide(21.0, 200.0, guard(), now(), false), Decision::Approve { suspect: true });
783 assert_eq!(decide(21.0, 2.0, guard(), now(), false), Decision::Approve { suspect: true });
784 }
785
786 #[test]
787 fn moves_inside_the_guardrail_apply_themselves_falls_at_once_rises_after_notice() {
788 // Down 19%: at once.
789 assert_eq!(decide(21.0, 17.0, guard(), now(), false), Decision::Auto { effective_ms: now() });
790 // Up 19%: after 14 days.
791 let Decision::Auto { effective_ms } = decide(21.0, 25.0, guard(), now(), false) else { panic!() };
792 assert_eq!(rfc3339(effective_ms), "2026-10-20T04:17:00.000Z");
793 // A monthly meter's rise waits for the month after the notice.
794 let Decision::Auto { effective_ms } = decide(150_000.0, 180_000.0, guard(), now(), true) else { panic!() };
795 assert_eq!(rfc3339(effective_ms), "2026-11-01T00:00:00.000Z");
796 let late = parse_rfc3339("2026-10-25T00:00:00Z").unwrap();
797 assert_eq!(rfc3339(effective_ms_for(late)), "2026-12-01T00:00:00.000Z");
798 }
799
800 fn effective_ms_for(now: u64) -> u64 {
801 effective_ms(1.0, 2.0, now, 14, true)
802 }
803
804 #[test]
Merge costs and margin review: gateway query, own spend, discount meters, superseded rises805 fn a_versions_cost_says_what_it_is() {
806 // The agent rate's $0.25 a million tokens is g1t's price, not what
807 // tokens cost g1t; the weights are multipliers.
808 assert_eq!(basis_of("agent_tokens"), "rate");
809 assert_eq!(basis_of("agent_tokens_own"), "rate");
810 assert_eq!(basis_of("security_activation"), "rate");
811 assert_eq!(basis_of("agent_token_weight_cache_read"), "weight");
812 // A provider's dollar passed on at cost, and Cloudflare's units, are costs.
813 for meter in ["agent_models", "gateway_models", "sandbox_second", "git_operations", "card_fee_percent"] {
814 assert_eq!(basis_of(meter), "cost", "{meter}");
815 }
816 }
817
818 #[test]
819 fn a_rise_replaced_before_its_date_is_superseded_not_applied() {
820 // 2026-10-07's sandbox rise (v2, due 10-21) was replaced by
821 // 10-08's (v3, due 10-22): v2's proposal never took effect.
822 let sql = SUPERSEDE_WAITING_SQL;
823 assert_eq!(crate::rename::parameters(sql), 1);
824 assert!(sql.contains("status = 'superseded'") && sql.contains("applied_at IS NULL") && !sql.contains("decided_"), "{sql}");
825 // A rise still waits its notice: the replacement is no shortcut.
826 let Decision::Auto { effective_ms } = decide(18.1817, 19.5181, guard(), now(), false) else { panic!() };
827 assert_eq!(rfc3339(effective_ms), "2026-10-20T04:17:00.000Z");
828 }
829
830 #[test]
Compare: any two branches, the commits one has that the other does not, and the diff, with Open a pull request831 fn past_the_guardrail_or_with_auto_off_staff_decide() {
832 // Up 50%: staff.
833 assert_eq!(decide(150_000.0, 225_000.0, guard(), now(), true), Decision::Approve { suspect: false });
834 // Down 30%: staff too; the guardrail is either way.
835 assert_eq!(decide(100.0, 70.0, guard(), now(), false), Decision::Approve { suspect: false });
836 let off = Guard { auto_apply: false, ..guard() };
837 assert_eq!(decide(21.0, 22.0, off, now(), false), Decision::Approve { suspect: false });
838 }
839
840 #[test]
841 fn a_past_statement_keeps_the_price_of_its_time() {
842 let v = |version: u32, cost: f64, at: &str| Version {
843 id: format!("pv_git_operations_{version}"),
844 meter: "git_operations".into(),
845 version,
846 cost_micros: cost,
847 markup_percent: 20,
848 effective_at: at.into(),
849 reason: String::new(),
850 created_by: "keeper".into(),
851 applied_at: None,
852 };
853 let versions = vec![v(1, 150_000.0, "2026-10-05T00:00:00Z"), v(2, 450_000.0, "2026-11-01T00:00:00.000Z"), v(3, 400_000.0, "2026-12-01T00:00:00.000Z")];
854 // October's charges were at version 1, whatever came later.
855 assert_eq!(in_force(&versions, "git_operations", "2026-10-31T23:59:59Z").unwrap().version, 1);
856 assert_eq!(in_force(&versions, "git_operations", "2026-11-15T00:00:00Z").unwrap().version, 2);
857 assert_eq!(in_force(&versions, "git_operations", "2027-01-01T00:00:00Z").unwrap().cost_micros, 400_000.0);
858 assert!(in_force(&versions, "git_operations", "2026-01-01T00:00:00Z").is_none());
859 assert!(in_force(&versions, "sandbox_second", "2027-01-01T00:00:00Z").is_none());
860 }
861
862 #[test]
863 fn settings_read_with_defaults_and_are_checked() {
864 let s = settings_from(&[("auto_apply".into(), "false".into()), ("notice_days".into(), "30".into()), ("anomaly_factor".into(), "x".into())]);
865 assert!(!s.auto_apply);
866 assert_eq!(s.notice_days, 30);
867 assert_eq!(s.anomaly_factor, 1.0);
868 assert_eq!(s.auto_apply_percent, 25.0);
869 assert!(check_settings(&s).is_ok());
870 assert!(check_settings(&CostSettings { notice_days: 120, ..s.clone() }).is_err());
871 assert!(check_settings(&CostSettings { alert_days: 0, ..s.clone() }).is_err());
872 assert!(check_settings(&CostSettings { auto_apply_percent: 150.0, ..s }).is_err());
873 }
874}

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