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.

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