Skip to content
297 linesCodeBlameRaw
1//! A test workspace's billing, wiped: `admin_reset_billing`.
2//!
3//! While billing runs on Stripe's test key, staff can return a workspace
4//! used for testing to how a new customer starts: no ledger, balance,
5//! plan, limits, trial grant, invoices, holds, signals or cost rows. Its
6//! workspace, members and repositories are not billing's and stay. Never
7//! with a live Stripe key, never for a comped workspace, and never for one
8//! an enterprise pays for. The reset itself is kept in the audit log, and
9//! g1t's own counts of the workspace's git operations stay: they are what
10//! Cloudflare's bill is compared with, not what the workspace owes.
11//!
12//! What the wiped usage cost g1t is kept too (`reset_costs`): the model
13//! calls and Cloudflare usage still happened, and AI Gateway and the bill
14//! still show them. The costs run counts that as given away on purpose
15//! ("testing resets"), so it is neither drift nor a leak.
16
17use g1t_contracts::billing::{AdminResetBillingArgs, BillingReset};
18use g1t_contracts::time::rfc3339;
19use g1t_contracts::{FailureCode, Outcome};
20use g1t_kit::now_ms;
21use serde::Deserialize;
22use worker::Result;
23use worker::wasm_bindgen::JsValue;
24
25use crate::Billing;
26use crate::accounts::own_account;
27
28/// The statements, in order. Parameters: `?1` the workspace, `?2` its own
29/// billing account (`ws_<slug>`).
30pub(crate) const STATEMENTS: &[&str] = &[
31 "DELETE FROM workspace_invoice_lines WHERE invoice_id IN (SELECT invoice_id FROM workspace_invoices WHERE workspace = ?1)",
32 "DELETE FROM workspace_invoices WHERE workspace = ?1",
33 "DELETE FROM ledger WHERE workspace = ?1",
34 "DELETE FROM runs WHERE workspace = ?1",
35 "DELETE FROM reservations WHERE workspace = ?1",
36 "DELETE FROM checkouts WHERE workspace = ?1",
37 "DELETE FROM ai_reload WHERE workspace = ?1",
38 "DELETE FROM ai_reloads WHERE workspace = ?1",
39 "DELETE FROM tax_and_fees WHERE workspace = ?1",
40 "DELETE FROM accounts WHERE workspace = ?1",
41 "DELETE FROM plan_payments WHERE workspace = ?1",
42 "DELETE FROM disputes WHERE workspace = ?1",
43 "DELETE FROM subscriptions WHERE workspace = ?1",
44 "DELETE FROM limits WHERE workspace = ?1",
45 "DELETE FROM limit_requests WHERE workspace = ?1",
46 "DELETE FROM trial_grants WHERE workspace = ?1",
47 "DELETE FROM credit_grants WHERE workspace = ?1",
48 "DELETE FROM card_checks WHERE workspace = ?1",
49 "DELETE FROM alerts_sent WHERE workspace = ?1",
50 "DELETE FROM price_notices WHERE workspace = ?1",
51 "DELETE FROM pending_usage WHERE workspace = ?1",
52 "DELETE FROM pending_baselines WHERE workspace = ?1",
53 "DELETE FROM pending_days WHERE workspace = ?1",
54 "DELETE FROM month_closes WHERE workspace = ?1",
55 "DELETE FROM storage_days WHERE workspace = ?1",
56 "DELETE FROM package_storage_days WHERE workspace = ?1",
57 "DELETE FROM token_usage WHERE workspace = ?1",
58 "DELETE FROM gateway_requests WHERE workspace = ?1",
59 "DELETE FROM spikes WHERE workspace = ?1",
60 "DELETE FROM closed_workspaces WHERE workspace = ?1",
61 "DELETE FROM sales_records WHERE workspace = ?1",
62 "DELETE FROM sales_notes WHERE workspace = ?1",
63 "DELETE FROM workspace_costs WHERE workspace = ?1",
64 "DELETE FROM margin_alerts WHERE kind = 'workspace' AND subject = ?1",
65 // Allowances drawn by the workspace, and its repositories' shares of
66 // the open-source pool (`<slug>/<name>`, compared exactly).
67 "DELETE FROM allowance_use WHERE scope = ?1 OR (kind = 'oss_repo' AND substr(scope, 1, length(?1) + 1) = ?1 || '/')",
68 "DELETE FROM budget_alerts WHERE account = ?2",
69 "DELETE FROM billing_accounts WHERE id = ?2",
70];
71
72/// Keeps one row of what a reset wiped that g1t paid for. Parameters: the
73/// workspace, day, bucket, cost, value, when and who.
74pub(crate) const KEEP: &str = "INSERT OR REPLACE INTO reset_costs (workspace, day, bucket, cost_micros, value_micros, reset_at, reset_by) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)";
75
76/// The `reset_costs` rows a reset at `at` writes, each (day, bucket, cost,
77/// value): what it wiped that g1t paid for, and one for the reset itself
78/// (bucket '', nothing in it), so every reset is on record even when it
79/// wiped nothing.
80pub(crate) fn kept_rows(at: &str, wiped: &[crate::margin::Wiped]) -> Vec<(String, String, i64, i64)> {
81 let mut rows = vec![(at[..10.min(at.len())].to_owned(), String::new(), 0, 0)];
82 rows.extend(wiped.iter().map(|w| (w.day.clone(), w.bucket.clone(), w.cost, w.value)));
83 rows
84}
85
86impl Billing {
87 pub(crate) async fn admin_reset_billing(&self, env: &worker::Env, a: AdminResetBillingArgs) -> Result<Outcome<BillingReset>> {
88 let workspace = a.workspace.trim().to_lowercase();
89 if workspace.is_empty() || a.by.trim().is_empty() {
90 return Ok(Outcome::fail(FailureCode::Invalid, "A reset needs a workspace and who did it."));
91 }
92 if a.note.trim().len() < 5 {
93 return Ok(Outcome::fail(FailureCode::Invalid, "Say why it is reset, for whoever looks next."));
94 }
95 if a.confirm.trim() != workspace {
96 return Ok(Outcome::fail(FailureCode::Invalid, format!("Type the workspace's slug, {workspace}, exactly, to reset it.")));
97 }
98 if self.stripe.as_ref().is_some_and(|s| s.live()) {
99 return Ok(Outcome::fail(FailureCode::Forbidden, "Billing takes real cards: a workspace's billing is never wiped."));
100 }
101 #[derive(Deserialize)]
102 struct Found {
103 comped: i64,
104 enterprise: i64,
105 }
106 let found = self
107 .db
108 .prepare(format!(
109 "SELECT CASE WHEN ?1 IN ({}) THEN 1 ELSE 0 END AS comped,
110 (SELECT COUNT(*) FROM account_members WHERE workspace = ?1) AS enterprise",
111 crate::sales::INTERNAL_SQL
112 ))
113 .bind(&[workspace.as_str().into()])?
114 .first::<Found>(None)
115 .await?;
116 if let Some(found) = found {
117 if found.comped > 0 {
118 return Ok(Outcome::fail(FailureCode::Forbidden, format!("{workspace} is comped (g1t's own): its spend is a budget, kept.")));
119 }
120 if found.enterprise > 0 {
121 return Ok(Outcome::fail(FailureCode::Forbidden, format!("An enterprise pays for {workspace}: move it off first.")));
122 }
123 }
124 let account = own_account(&workspace);
125 // What g1t paid for is kept before it is wiped, in the same batch,
126 // so the costs run counts it as given away (testing resets) rather
127 // than finding AI Gateway's and Cloudflare's figures unexplained.
128 let at_ms = now_ms();
129 let at = rfc3339(at_ms);
130 let wiped = self.wiped_by_reset(&workspace).await?;
131 let kept = kept_rows(&at, &wiped);
132 let mut batch = Vec::with_capacity(kept.len() + STATEMENTS.len());
133 for (day, bucket, cost, value) in &kept {
134 batch.push(self.db.prepare(KEEP).bind(&[
135 workspace.as_str().into(),
136 day.as_str().into(),
137 bucket.as_str().into(),
138 (*cost as f64).into(),
139 (*value as f64).into(),
140 at.as_str().into(),
141 a.by.as_str().into(),
142 ])?);
143 }
144 for sql in STATEMENTS {
145 let values: Vec<JsValue> =
146 [workspace.as_str(), account.as_str()][..crate::rename::parameters(sql)].iter().map(|v| (*v).into()).collect();
147 batch.push(self.db.prepare(*sql).bind(&values)?);
148 }
149 let mut rows = 0usize;
150 for result in self.db.batch(batch).await?.into_iter().skip(kept.len()) {
151 rows += result.meta()?.and_then(|m| m.changes).unwrap_or(0);
152 }
153 let paid: i64 = wiped.iter().map(|w| w.cost).sum();
154 let detail = format!(
155 "billing of {workspace} reset ({rows} rows; {} g1t paid for kept as given away): {}",
156 crate::features::dollars(paid),
157 a.note.trim()
158 );
159 // At the same instant as the kept rows: that is how the costs run
160 // tells a reset that kept its costs from one before resets did.
161 self.audit_at(&account, "reset", &detail, &a.by, at_ms).await?;
162 // The margin figures still hold the workspace's past usage: redo
163 // them now (the day's analysis: the bill, 31 days, the alerts), so
164 // the pages show the reset at once.
165 let refreshed = match self.costs_daily(env, &crate::keeper::Keeper::from_env(env)).await {
166 Ok(run) => run.problems.is_empty(),
167 Err(error) => {
168 worker::console_error!("costs after a reset of {workspace}: {error}");
169 false
170 }
171 };
172 Ok(Outcome::Ok(BillingReset { workspace, rows: rows as u32, refreshed }))
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn every_table_with_a_workspace_is_wiped_or_kept_on_purpose() {
182 let all = STATEMENTS.join("\n");
183 // What is kept: the audit log, g1t's own counts compared with
184 // Cloudflare's bill, and what resets wiped that g1t paid for.
185 let kept = ["admin_actions", "own_counts", "reset_costs"];
186 for table in kept {
187 assert!(!all.contains(&format!("DELETE FROM {table} ")), "{table} is kept on purpose");
188 }
189 for table in [
190 "ledger", "runs", "checkouts", "workspace_invoices", "workspace_invoice_lines", "sales_notes", "accounts",
191 "pending_usage", "pending_baselines", "pending_days", "limits", "subscriptions", "month_closes", "sales_records",
192 "billing_accounts", "allowance_use", "trial_grants", "credit_grants", "storage_days", "package_storage_days",
193 "token_usage", "reservations", "spikes", "limit_requests", "plan_payments",
194 "card_checks", "alerts_sent", "price_notices", "closed_workspaces", "workspace_costs",
195 "margin_alerts", "budget_alerts", "ai_reload", "ai_reloads", "tax_and_fees", "gateway_requests",
196 ] {
197 assert!(!kept.contains(&table));
198 assert!(all.contains(&format!("DELETE FROM {table} WHERE")), "{table}");
199 }
200 }
201
202 /// The tables the migrations leave: every one made, less those dropped.
203 fn live_tables() -> std::collections::BTreeSet<String> {
204 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("migrations");
205 let mut files: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()).collect();
206 files.sort();
207 let mut live = std::collections::BTreeSet::new();
208 for file in files {
209 let sql = std::fs::read_to_string(file).unwrap();
210 for line in sql.lines().map(str::trim) {
211 let words: Vec<&str> = line.split(|c: char| c.is_whitespace() || c == '(' || c == ';').filter(|w| !w.is_empty()).collect();
212 let name = |at: usize| words.get(at).map(|w| w.to_string());
213 match words.as_slice() {
214 ["CREATE", "TABLE", "IF", "NOT", "EXISTS", ..] => live.extend(name(5)),
215 ["CREATE", "TABLE", ..] => live.extend(name(2)),
216 ["DROP", "TABLE", "IF", "EXISTS", ..] => {
217 name(4).map(|n| live.remove(&n));
218 }
219 ["DROP", "TABLE", ..] => {
220 name(2).map(|n| live.remove(&n));
221 }
222 _ => {}
223 }
224 }
225 }
226 live
227 }
228
229 #[test]
230 fn every_table_wiped_is_one_the_migrations_leave() {
231 let live = live_tables();
232 assert!(live.contains("ledger") && !live.contains("sandbox_months"), "{live:?}");
233 for sql in STATEMENTS {
234 let table = sql.split_whitespace().nth(2).unwrap();
235 assert!(live.contains(table), "{table} is not a table after the migrations");
236 }
237 }
238
239 #[test]
240 fn a_rename_moves_every_table_a_reset_wipes() {
241 let moved = crate::rename::STATEMENTS.join("\n");
242 // Lines follow their invoice, which carries the workspace.
243 for sql in STATEMENTS.iter().filter(|sql| !sql.contains("workspace_invoice_lines")) {
244 let table = sql.split_whitespace().nth(2).unwrap();
245 assert!(moved.contains(&format!(" {table} ")), "{table} is wiped on a reset but not moved on a rename");
246 }
247 }
248
249 #[test]
250 fn a_reset_keeps_what_g1t_paid_for_and_a_row_for_itself() {
251 use crate::margin::{UsageRow, Wiped, wiped};
252 let map: std::collections::BTreeMap<String, String> =
253 [("sandbox", "sandboxes"), ("git", "git"), ("plan", "platform")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
254 let row = |day: &str, key: &str, value: i64, cash: i64, cost: i64| UsageRow {
255 day: day.into(),
256 workspace: "syntaqx".into(),
257 key: key.into(),
258 value,
259 cash,
260 cost,
261 ..UsageRow::default()
262 };
263 // Two agent runs and a sandbox on Oct 2, a run in a free period on
264 // Oct 7 (valued at price), the plan's payment and a run on the
265 // workspace's own key (no cost to g1t): only what g1t paid for.
266 let rows = vec![
267 row("2026-10-02", "implement", 3_600_000, 3_600_000, 3_000_000),
268 row("2026-10-02", "review", 1_200_000, 0, 1_000_000),
269 row("2026-10-02", "sandbox", 240_000, 240_000, 200_000),
270 row("2026-10-07", "implement", 0, 0, 4_600_000),
271 row("2026-10-07", "plan", 20_000_000, 20_000_000, 0),
272 row("2026-10-07", "own_key", 50_000, 50_000, 0),
273 ];
274 let kept = wiped(&rows, &map, 20);
275 assert_eq!(
276 kept,
277 vec![
278 Wiped { day: "2026-10-02".into(), bucket: "models".into(), cost: 4_000_000, value: 4_800_000 },
279 Wiped { day: "2026-10-02".into(), bucket: "sandboxes".into(), cost: 200_000, value: 240_000 },
280 Wiped { day: "2026-10-07".into(), bucket: "models".into(), cost: 4_600_000, value: 5_520_000 },
281 ]
282 );
283 let rows = kept_rows("2026-10-07T09:12:00.000Z", &kept);
284 assert_eq!(rows[0], ("2026-10-07".to_string(), String::new(), 0, 0));
285 assert_eq!(rows.len(), 4);
286 // Nothing paid for: still on record.
287 assert_eq!(kept_rows("2026-10-08T00:00:00.000Z", &[]), vec![("2026-10-08".to_string(), String::new(), 0, 0)]);
288 assert_eq!(crate::rename::parameters(KEEP), 7);
289 assert!(live_tables().contains("reset_costs"));
290 }
291
292 #[test]
293 fn statements_name_at_most_the_workspace_and_its_account() {
294 assert!(STATEMENTS.iter().all(|sql| crate::rename::parameters(sql) <= 2));
295 assert_eq!(crate::rename::parameters(STATEMENTS.last().unwrap()), 2);
296 }
297}