An open-source, faster Devin alternative
TypeScript
adjust implementation, correct logic around auto top up"
Brian Reardon5b5e1e4a776f
diff --git a/cloudflare-workers/api-edge/src/autumn_meter.ts b/cloudflare-workers/api-edge/src/autumn_meter.tsnew file mode 100644index 00000000..4c58f214--- /dev/null+++ b/cloudflare-workers/api-edge/src/autumn_meter.ts@@ -0,0 +1,161 @@+// Edge-native autumn billing. THE place autumn usage bills — one place (this+// cron), not 70 per-cell reporters — off the same `usage_samples` rows that+// drive the Stripe billing-rollup for legacy orgs. Replaces the (deleted) cell+// AutumnReporter.+//+// Per autumn org it ships every fully-elapsed 5-minute bucket since the org's+// watermark to Autumn via track(), advancing the watermark one bucket at a time+// so a mid-run failure only replays the unfinished bucket (idempotency dedupes).+// A bucket whose track() returns a non-positive balance triggers projectOrg →+// is_halted + hibernate-dispatch.++import { type AutumnEnv, projectOrg, trackAutumnUsage } from "./autumn_webhook";++// Fixed 5-minute bucket: the unit of idempotency AND the bound on overspend past+// a zero balance before the halt fires. Mirrors the old cell autumnBucketSize.+const BUCKET_SEC = 300;++// Don't close a bucket until this long after its end, so late-delivered samples+// (forwarder + ingest + PEL retries) land before we track + advance the+// watermark. A sample arriving after the grace is bounded drift — Autumn dedupes+// the bucket's idempotency key, so it can't be re-added. Same "acceptable drift"+// model as billing-rollup.+const GRACE_SEC = 120;++// Cap buckets processed per org per run so one very-stale org can't monopolize a+// tick. Idle gaps are skipped in O(1) via the MIN(ts) fast-forward below, so this+// only bounds genuine continuous-usage catch-up; the next run continues.+const MAX_BUCKETS_PER_ORG = 24; // 2h of continuous catch-up per 5-min run++// Mirror of internal/billing/autumn.tierFeatureByMemoryMB — keep in sync with+// pricing.go and the Autumn credit schema.+const TIER_FEATURE_BY_MEMORY_MB: Record<number, string> = {+ 1024: "compute_1gb",+ 4096: "compute_4gb",+ 8192: "compute_8gb",+ 16384: "compute_16gb",+ 32768: "compute_32gb",+ 65536: "compute_64gb",+};++// Globally-unique, retry-stable key. Autumn dedupes on the bare key across all+// customers, so it includes the org; keyed on bucket start (not wall-clock) so a+// replay reuses it. Matches autumn.UsageIdempotencyKey on the (removed) cell.+function usageIdempotencyKey(orgID: string, bucketStartUnix: number, featureID: string): string {+ return `usage:${orgID}:${bucketStartUnix}:${featureID}`;+}++interface AutumnOrgRow {+ id: string;+ autumn_usage_watermark: number;+}++interface TierAgg {+ memory_mb: number;+ secs: number;+}++export async function runAutumnMeter(env: AutumnEnv, nowMs: number): Promise<void> {+ const nowSec = Math.floor(nowMs / 1000);+ const orgsRes = await env.OPENCOMPUTER_DB.prepare(+ "SELECT id, autumn_usage_watermark FROM orgs WHERE billing_provider = 'autumn'",+ ).all<AutumnOrgRow>();+ const orgs = orgsRes.results ?? [];+ if (orgs.length === 0) return;++ let withUsage = 0;+ for (const org of orgs) {+ try {+ if (await meterOrg(env, org, nowSec)) withUsage++;+ } catch (err) {+ // Leave the watermark; the next run replays from it (idempotent).+ console.error(`autumn-meter: org ${org.id} failed`, err);+ }+ }+ console.log(`autumn-meter: ${orgs.length} autumn org(s), ${withUsage} billed this run`);+}++// meterOrg processes one org's closed buckets. Returns true if it tracked usage.+async function meterOrg(env: AutumnEnv, org: AutumnOrgRow, nowSec: number): Promise<boolean> {+ // First sight: seed the watermark to now and bill forward only — never+ // retroactively charge usage accrued before the org moved to Autumn.+ if (!org.autumn_usage_watermark || org.autumn_usage_watermark === 0) {+ await setWatermark(env, org.id, nowSec);+ console.log(`autumn-meter: org ${org.id} seeded watermark at ${nowSec}`);+ return false;+ }++ const closeBefore = nowSec - GRACE_SEC;+ let cursor = org.autumn_usage_watermark;+ if (cursor + BUCKET_SEC > closeBefore) return false; // nothing fully closed yet++ // Earliest un-billed sample in the closeable window. If none, the org is idle:+ // fast-forward the watermark so its gap never grows (keeps catch-up O(1)).+ const win = await env.OPENCOMPUTER_DB.prepare(+ "SELECT MIN(ts) AS mn FROM usage_samples WHERE org_id = ?1 AND ts >= ?2 AND ts < ?3",+ )+ .bind(org.id, cursor * 1000, closeBefore * 1000)+ .first<{ mn: number | null }>();+ if (!win?.mn) {+ const aligned = cursor + Math.floor((closeBefore - cursor) / BUCKET_SEC) * BUCKET_SEC;+ if (aligned > cursor) await setWatermark(env, org.id, aligned);+ return false;+ }++ // Jump straight to the bucket holding the earliest sample (skip idle buckets).+ const firstSampleSec = Math.floor(win.mn / 1000);+ cursor += Math.floor((firstSampleSec - cursor) / BUCKET_SEC) * BUCKET_SEC;++ for (let n = 0; n < MAX_BUCKETS_PER_ORG; n++) {+ const bucketEnd = cursor + BUCKET_SEC;+ if (bucketEnd > closeBefore) break;+ const exhausted = await trackBucket(env, org.id, cursor, bucketEnd);+ await setWatermark(env, org.id, bucketEnd);+ cursor = bucketEnd;+ if (exhausted) {+ // projectOrg re-reads the balance, sets is_halted, and dispatches+ // /admin/halt-org to hibernate running boxes. Stop here — usage halts.+ await projectOrg(env, org.id);+ break;+ }+ }+ return true;+}++// trackBucket aggregates usage_samples in [from, to) by memory tier and tracks+// one usage event per tier to Autumn. Returns true if the balance is now <= 0.+async function trackBucket(env: AutumnEnv, orgID: string, fromSec: number, toSec: number): Promise<boolean> {+ const aggRes = await env.OPENCOMPUTER_DB.prepare(+ `SELECT memory_mb AS memory_mb, SUM(interval_s) AS secs+ FROM usage_samples+ WHERE org_id = ?1 AND ts >= ?2 AND ts < ?3+ GROUP BY memory_mb`,+ )+ .bind(orgID, fromSec * 1000, toSec * 1000)+ .all<TierAgg>();+ const tiers = aggRes.results ?? [];+ if (tiers.length === 0) return false;++ let remaining: number | null = null;+ for (const t of tiers) {+ if (!t.secs || t.secs <= 0) continue;+ const feature = TIER_FEATURE_BY_MEMORY_MB[t.memory_mb];+ if (!feature) {+ console.warn(`autumn-meter: org ${orgID} unknown memory tier ${t.memory_mb}MB — skipping`);+ continue;+ }+ remaining = await trackAutumnUsage(env, {+ customerID: orgID,+ featureID: feature,+ value: t.secs,+ idempotencyKey: usageIdempotencyKey(orgID, fromSec, feature),+ });+ }+ return remaining !== null && remaining <= 0;+}++async function setWatermark(env: AutumnEnv, orgID: string, ts: number): Promise<void> {+ await env.OPENCOMPUTER_DB.prepare("UPDATE orgs SET autumn_usage_watermark = ?1 WHERE id = ?2")+ .bind(ts, orgID)+ .run();+}diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 72c7c972..3587d942 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -69,6 +69,11 @@ export interface AutumnAutoTopup {export interface AutumnCustomer {id: string;subscriptions?: AutumnSubscription[];+ // Completed one-off purchases. A `top_up` here means the customer has charged a+ // top-up — and since every top-up goes through the off-session flow+ // (autumnTopUpCharge), that's also when auto-recharge becomes armed. So it's our+ // "auto-recharge will fire" signal (Autumn exposes no payment-method field).+ purchases?: Array<{ plan_id: string }>;balances?: Record<string, { remaining?: number }>;billing_controls?: { auto_topups?: AutumnAutoTopup[] };}@@ -267,14 +272,14 @@ export async function autumnSetProviderInternal(req: Request, env: AutumnEnv): P// do NOT dispatch — D1.is_halted is already cleared, which unblocks the gates;// hibernated boxes wake lazily on the next request. This is the locked "no// auto-wake for prepaid" decision: a top-up unblocks but never force-wakes.-async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {+export async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {const r = await syncAutumnToD1(env, orgID);if (!r || !r.halted) return;// Dispatch halt on the fresh transition, OR whenever a halted org STILL has// running sandboxes — so a halt is eventually complete even if a single- // hibernation flaked on the first dispatch. The reconciler calls projectOrg- // every 60s, so this is the straggler safety net (mirrors the legacy- // halt_reconciler, which re-issues HaltOrg for every halted org each sweep).+ // hibernation flaked on the first dispatch. The autumn-meter cron + the+ // webhook both call projectOrg, so this is the straggler safety net (a halted+ // org with a leftover running box gets re-dispatched on the next sight).if (!r.wasHalted || (await hasRunningSandboxes(env, orgID))) {await dispatchToCells(env, orgID, "/admin/halt-org", { org_id: orgID, reason: "credits_exhausted" });}@@ -328,6 +333,44 @@ export async function getAutumnCustomer(env: AutumnApiEnv, customerID: string):return (await resp.json()) as AutumnCustomer;}+// trackAutumnUsage records metered usage against a feature. Autumn dedupes on+// idempotency_key across ALL customers, so the key must be globally unique and+// stable across retries (see usageIdempotencyKey). Returns the post-track+// `credits` balance so the caller can halt on exhaustion.+//+// A 409 duplicate_idempotency_key means this bucket already landed on an earlier+// run (the watermark write failed after the track) — not an error. We re-read+// the balance so the halt check still fires if this was the exhausting bucket.+export async function trackAutumnUsage(+ env: AutumnApiEnv,+ p: { customerID: string; featureID: string; value: number; idempotencyKey: string },+): Promise<number | null> {+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;+ const resp = await fetch(`${base}/track`, {+ method: "POST",+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`, "content-type": "application/json" },+ body: JSON.stringify({+ customer_id: p.customerID,+ feature_id: p.featureID,+ value: p.value,+ idempotency_key: p.idempotencyKey,+ }),+ });+ if (resp.ok) {+ const body = (await resp.json()) as { balance?: { remaining?: number } };+ return body.balance?.remaining ?? null;+ }+ if (resp.status === 409) {+ const text = await resp.text();+ if (text.includes("duplicate_idempotency_key")) {+ const cust = await getAutumnCustomer(env, p.customerID);+ return cust?.balances?.[CREDITS_FEATURE_ID]?.remaining ?? null;+ }+ throw new Error(`autumn track 409: ${text}`);+ }+ throw new Error(`autumn track ${resp.status}: ${await resp.text()}`);+}+// CheckoutOption sets a quantity for a priced feature in the product (e.g. the// number of $1 credits in a top-up).export interface AutumnCheckoutOption {@@ -336,7 +379,9 @@ export interface AutumnCheckoutOption {}export interface AutumnCheckoutResult {- url: string;+ // null when the customer already has a payment method on file — Autumn expects+ // a direct /attach instead of a hosted checkout redirect (see autumnPurchase).+ url: string | null;total?: number;currency?: string;}@@ -365,6 +410,96 @@ export async function autumnCheckout(return (await resp.json()) as AutumnCheckoutResult;}+// autumnAttach completes a purchase using the customer's existing payment method+// — no hosted checkout. Used when /checkout returns url=null (a card is on file).+export async function autumnAttach(+ env: AutumnApiEnv,+ params: { customerId: string; productId: string; options?: AutumnCheckoutOption[] },+): Promise<void> {+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;+ const body: Record<string, unknown> = { customer_id: params.customerId, product_id: params.productId };+ if (params.options && params.options.length > 0) body.options = params.options;+ const resp = await fetch(`${base}/attach`, {+ method: "POST",+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`, "content-type": "application/json" },+ body: JSON.stringify(body),+ });+ if (!resp.ok) throw new Error(`autumn attach ${resp.status}: ${await resp.text()}`);+ // code=checkout_created means there was no chargeable card so Autumn made a+ // hosted checkout instead of charging — for our "charge the card on file" path+ // that's a failure, not success. Surface it rather than silently no-op'ing.+ const d = (await resp.json()) as { code?: string };+ if (d.code === "checkout_created") {+ throw new Error("autumn attach: no payment method on file (got checkout_created)");+ }+}++// autumnPurchase buys a product (top-up or concurrency tier), handling both+// Autumn flows: a customer with NO card gets a hosted-checkout url to redirect+// to; a customer WITH a card on file gets url=null from /checkout, so we charge+// directly via /attach. Returns the url to redirect to, or null when the charge+// already completed (caller should just refresh the balance — no redirect).+export async function autumnPurchase(+ env: AutumnApiEnv,+ params: { customerId: string; productId: string; options?: AutumnCheckoutOption[]; successUrl: string },+): Promise<{ url: string | null }> {+ const co = await autumnCheckout(env, params);+ if (co.url) return { url: co.url };+ await autumnAttach(env, { customerId: params.customerId, productId: params.productId, options: params.options });+ return { url: null };+}++// autumnSetupPayment creates a Stripe SETUP session that saves a card for future+// OFF-SESSION use — POST /v1/billing.setup_payment. It does NOT charge (setup+// mode), so arming auto-recharge takes a follow-up /attach once the card is on+// file (see autumnTopUpCharge + the ?charge_topup return handler). Returns the+// URL to redirect the customer to.+export async function autumnSetupPayment(+ env: AutumnApiEnv,+ params: { customerId: string; successUrl: string },+): Promise<{ url: string | null }> {+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;+ const resp = await fetch(`${base}/billing.setup_payment`, {+ method: "POST",+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`, "content-type": "application/json" },+ body: JSON.stringify({ customer_id: params.customerId, success_url: params.successUrl }),+ });+ if (!resp.ok) throw new Error(`autumn setup_payment ${resp.status}: ${await resp.text()}`);+ const d = (await resp.json()) as { url?: string };+ return { url: d.url ?? null };+}++// autumnTopUpCharge buys `quantity` credits while ensuring the card ends up saved+// OFF-SESSION — so a top-up also ARMS auto-recharge. No single Autumn hosted flow+// does both (a /checkout top-up charges but leaves the card on-session-only;+// setup_payment saves off-session but doesn't charge), so:+// - card already on file → /attach charges directly (no redirect), {url:null}.+// - no card → setup_payment saves the card off-session and returns a redirect+// URL; the CHARGE happens when the user returns — the caller's successUrl must+// carry ?charge_topup=<quantity> so the UI fires the /attach on return.+export async function autumnTopUpCharge(+ env: AutumnApiEnv,+ params: { customerId: string; quantity: number; successUrl: string },+): Promise<{ url: string | null }> {+ // hasToppedUp = a top-up has been charged = a card is on file (reliable). We do+ // NOT probe /checkout — it spuriously returns url=null for cardless customers.+ if (await autumnHasToppedUp(env, params.customerId)) {+ const options = [{ feature_id: "credits", quantity: params.quantity }];+ await autumnAttach(env, { customerId: params.customerId, productId: "top_up", options });+ return { url: null };+ }+ return autumnSetupPayment(env, { customerId: params.customerId, successUrl: params.successUrl });+}++// autumnHasToppedUp reports whether the customer has ever charged a top-up. Since+// every top-up goes through autumnTopUpCharge (off-session), this doubles as the+// "auto-recharge is armed" signal: true means enabling auto-recharge needs no new+// charge; false means the first recharge must run to arm it.+export async function autumnHasToppedUp(env: AutumnApiEnv, customerId: string): Promise<boolean> {+ const cust = await getAutumnCustomer(env, customerId);+ return (cust?.purchases ?? []).some((p) => p.plan_id === "top_up");+}+// autumnSetAutoTopup configures (or disables) automatic credit top-up for the// `credits` feature. POST /customers/{id} with billing_controls.auto_topups —// confirmed live: after every track() Autumn checks the balance and, if belowdiff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 978a5fb8..24b4a0f8 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -17,7 +17,14 @@// 3. Fetch the cell's /internal/dashboard/{path} with Authorization: Bearer.// 4. Stream the response (or WebSocket pair) back to the browser.-import { getAutumnCustomer, autumnCheckout, syncAutumnToD1, autumnSetAutoTopup } from "./autumn_webhook";+import {+ autumnPurchase,+ autumnTopUpCharge,+ autumnAttach,+ autumnHasToppedUp,+ syncAutumnToD1,+ autumnSetAutoTopup,+} from "./autumn_webhook";export interface DashboardEnv {OPENCOMPUTER_DB: D1Database;@@ -960,6 +967,9 @@ export async function handleDashboard(if (sub === "/billing/autumn/auto-topup" && method === "POST") {return handleAutumnAutoTopup(req, env, caller);}+ if (sub === "/billing/autumn/finalize-arm" && method === "GET") {+ return handleAutumnFinalizeArm(req, env, caller);+ }return json({ error: `not found: ${method} ${sub}` }, 404);}@@ -1192,11 +1202,17 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { oconst at = r.customer.billing_controls?.auto_topups?.find((a) => a.feature_id === "credits");+ // Has the customer charged a top-up? That's when auto-recharge becomes armed,+ // so the UI uses it to tell whether enabling auto-recharge will run a first+ // recharge or just save. Free — the customer is already loaded above.+ const hasToppedUp = (r.customer.purchases ?? []).some((p) => p.plan_id === "top_up");+return json({creditsRemainingCents: Math.round(r.creditsRemaining * 100),maxConcurrentSandboxes: r.maxConcurrent,concurrencyPlan,isHalted: r.halted,+ hasToppedUp,autoTopup: at ? { enabled: at.enabled, threshold: at.threshold, quantity: at.quantity } : null,});}@@ -1221,13 +1237,57 @@ async function handleAutumnAutoTopup(req: Request, env: DashboardEnv, caller: {}try {await autumnSetAutoTopup(env, caller.orgID, { enabled, threshold, quantity });- return json({ ok: true });++ // Auto-recharge is armed once the customer has charged a top-up (a+ // saved-but-never-charged card is unarmed). If they've already topped up, just+ // save — no redundant charge. If not, run their first recharge now to arm it+ // (no card → one hosted setup_payment flow saves the card off-session AND+ // charges; card on file → /attach charges directly).+ if (enabled && !(await autumnHasToppedUp(env, caller.orgID))) {+ const origin = new URL(req.url).origin;+ const co = await autumnTopUpCharge(env, {+ customerId: caller.orgID,+ quantity,+ successUrl: `${origin}/api/dashboard/billing/autumn/finalize-arm?credits=${quantity}`,+ });+ return json({ ok: true, url: co.url });+ }+ return json({ ok: true, url: null });} catch (e) {console.error("billing/autumn auto-topup:", e);return json({ error: (e as Error).message }, 502);}}+// GET /billing/autumn/finalize-arm?credits=N — the return target Stripe sends the+// browser to after a setup_payment card setup. The card is now saved, so we+// charge the deferred first recharge HERE (server-side, immune to browser cache /+// dropped query params), which both adds the credits and arms auto-recharge, then+// 302 back to the billing page. Authenticated by the session cookie carried on+// the redirect.+async function handleAutumnFinalizeArm(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {+ const origin = new URL(req.url).origin;+ const billing = `${origin}/dashboard/billing`;+ if (!env.AUTUMN_SECRET_KEY) return Response.redirect(billing, 302);+ const credits = Math.floor(Number(new URL(req.url).searchParams.get("credits") ?? "0"));+ // Idempotency: only charge if not already topped up — so a refresh / double+ // redirect to this URL can't charge twice (after the first charge, hasToppedUp+ // is true).+ if (credits >= 1 && !(await autumnHasToppedUp(env, caller.orgID))) {+ try {+ await autumnAttach(env, {+ customerId: caller.orgID,+ productId: "top_up",+ options: [{ feature_id: "credits", quantity: credits }],+ });+ } catch (e) {+ console.error("billing/autumn finalize-arm:", e);+ return Response.redirect(`${billing}?arm=failed`, 302);+ }+ }+ return Response.redirect(`${billing}?arm=ok`, 302);+}+// POST /api/dashboard/billing/autumn/topup { credits } — one-off prepaid credit// purchase. Returns a Stripe checkout URL; success returns to the billing page// where handleAutumnBilling re-syncs the new balance.@@ -1245,11 +1305,13 @@ async function handleAutumnTopup(req: Request, env: DashboardEnv, caller: { orgI}const origin = new URL(req.url).origin;try {- const co = await autumnCheckout(env, {+ // Charge via the off-session-establishing flow so a top-up also arms+ // auto-recharge. url present → redirect (hosted card setup, no card yet);+ // url null → existing card charged directly. Frontend redirects or refreshes.+ const co = await autumnTopUpCharge(env, {customerId: caller.orgID,- productId: "top_up",- options: [{ feature_id: "credits", quantity: credits }],- successUrl: `${origin}/dashboard/billing?topup=success`,+ quantity: credits,+ successUrl: `${origin}/api/dashboard/billing/autumn/finalize-arm?credits=${credits}`,});return json({ url: co.url });} catch (e) {@@ -1274,7 +1336,9 @@ async function handleAutumnConcurrency(req: Request, env: DashboardEnv, caller:}const origin = new URL(req.url).origin;try {- const co = await autumnCheckout(env, {+ // Same dual flow as top-up: redirect for a new card, or attach the existing+ // card directly (url null) when upgrading a tier with a payment method on file.+ const co = await autumnPurchase(env, {customerId: caller.orgID,productId: plan,successUrl: `${origin}/dashboard/billing?plan=success`,diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 0b4b401d..1eb7ed1a 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -25,6 +25,7 @@ import {selfHealHalt,createAutumnCustomer,} from "./autumn_webhook";+import { runAutumnMeter } from "./autumn_meter";import * as secretStores from "./secret_stores";import * as snapshots from "./snapshots";import * as templates from "./templates";@@ -404,7 +405,8 @@ async function enforceCreatePolicy(// Autumn orgs: Autumn owns the balance, so the credit gate is purely the// is_halted projection — no CreditAccount DO. On a halt, self-heal (re-check// Autumn) so a just-topped-up user isn't stuck behind a lagging webhook. The- // free-tier size ceilings below still apply by plan.+ // free-tier memory/CPU/disk ceilings below are skipped for autumn orgs (they+ // pay per GB-second); only the per-org max_disk_mb cap applies.if (org.billing_provider === "autumn") {if (org.is_halted === 1 && (await selfHealHalt(env, orgID))) {return json({ error: "credits exhausted — top up to resume" }, 402);@@ -428,8 +430,10 @@ async function enforceCreatePolicy(}}- // Free-tier ceilings: 4GB / 1 vCPU, 20GB disk.- if (plan === "free") {+ // Free-tier ceilings: 4GB / 1 vCPU, 20GB disk. Legacy only — autumn (prepaid)+ // orgs pay per GB-second and are gated by balance/halt, so they may launch any+ // size. Disk is still bounded for everyone by the per-org max_disk_mb check below.+ if (org.billing_provider !== "autumn" && plan === "free") {if (sizes.memoryMB > 4096 || sizes.cpuCount > 1) {return json({ error: "upgrade to pro for larger instances" }, 402);}@@ -1605,6 +1609,13 @@ export default {if (req.method !== "POST") return json({ error: "method not allowed" }, 405);return autumnSetProviderInternal(req, env);}+ // Dev-only: force an autumn-meter run (the cron is */5). 404 in prod so only+ // the scheduled trigger moves money there. Deterministic testing aid.+ if (path === "/internal/run-autumn-meter" && req.method === "POST") {+ if (env.WORKER_ENV === "prod") return new Response("not found", { status: 404 });+ await runAutumnMeter(env, Date.now());+ return json({ ok: true });+ }if (path === "/internal/org-policy") {if (req.method !== "GET") return json({ error: "method not allowed" }, 405);@@ -1902,4 +1913,15 @@ export default {if (env.ASSETS) return env.ASSETS.fetch(req);return new Response("not found", { status: 404 });},++ // Cron (*/5): edge-native autumn billing. Meters autumn orgs' usage_samples to+ // Autumn and halts on exhaustion — one place, not per-cell. Legacy orgs bill+ // via the separate billing-rollup worker; this no-ops unless AUTUMN_SECRET_KEY+ // is set (dormant until the cutover switch is flipped).+ async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {+ if (!env.AUTUMN_SECRET_KEY) return;+ ctx.waitUntil(+ runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),+ );+ },} satisfies ExportedHandler<Env>;diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 384b8a63..e1126e51 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -57,6 +57,12 @@ new_sqlite_classes = ["CreditAccount"]# (must match Infisical /shared/ key the CPs use, so# plaintext stays in sync across edge ↔ cells)+# Edge-native autumn billing: every 5 min, meter autumn orgs' usage_samples to+# Autumn + halt on exhaustion (src/autumn_meter.ts). One place, not per-cell.+# No-ops unless AUTUMN_SECRET_KEY is set, so it's dormant until cutover.+[triggers]+crons = ["*/5 * * * *"]+[vars]WORKER_ENV = "prod"# Cells eligible for new-org home assignment live in the D1 `cells` tablediff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex b291c00d..d024d890 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -87,6 +87,12 @@ new_sqlite_classes = ["CreditAccount"]# WORKOS_CLIENT_ID — WorkOS client identifier# EVENT_SECRET — HMAC for /internal/halt-list endpoint (shared with CP halt_reconciler)+# Edge-native autumn billing: every 5 min, meter autumn orgs' usage_samples to+# Autumn + halt on exhaustion (src/autumn_meter.ts). One place, not per-cell.+# No-ops unless AUTUMN_SECRET_KEY is set, so it's dormant until cutover.+[triggers]+crons = ["*/5 * * * *"]+[vars]WORKER_ENV = "dev"# Cells eligible for new-org home assignment are NOT configured here anymore —diff --git a/cloudflare-workers/billing-rollup/src/index.ts b/cloudflare-workers/billing-rollup/src/index.tsindex 42ac6c4a..c6800be1 100644--- a/cloudflare-workers/billing-rollup/src/index.ts+++ b/cloudflare-workers/billing-rollup/src/index.ts@@ -195,6 +195,7 @@ async function rollBucket(FROM usage_samples sJOIN orgs o ON o.id = s.org_idWHERE s.rolled_up = 0 AND s.ts >= ?1 AND s.ts < ?2+ AND o.billing_provider != 'autumn'GROUP BY s.org_id, s.memory_mb`,).bind(startMs, endMs)@@ -250,6 +251,11 @@ async function rollBucket(// replays: re-aggregating recomputes identical deterministic ids (deduped),// and the unmarked samples get picked up and marked next run. Marking first// would risk dropping samples whose meter rows never landed (underbilling).+ // Mark the whole bucket window rolled — including autumn rows, which are+ // excluded from the aggregation above (they bill to Autumn via the edge+ // autumn-meter cron, keyed off a per-org watermark, not rolled_up). Marking+ // them here just keeps autumn-only buckets from being rediscovered forever;+ // it never affects autumn billing.const markRolled = env.OPENCOMPUTER_DB.prepare(`UPDATE usage_samples SET rolled_up = 1 WHERE rolled_up = 0 AND ts >= ?1 AND ts < ?2`,).bind(startMs, endMs);diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex b05a3046..080c95ba 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -408,8 +408,22 @@ export default {}return true;};+ // usage_samples is the single billing source. Pro orgs are rolled up to+ // Stripe (billing-rollup); autumn orgs are metered to Autumn by the edge+ // autumn-meter cron (api-edge) off these same rows. So both land samples —+ // free orgs are debited via the DO fan-out below and need none. The two+ // consumers don't collide: the Stripe rollup keys off rolled_up, the autumn+ // meter keys off a per-org watermark (ts), and billing-rollup excludes+ // autumn from its aggregation so a row never bills twice.const usageSampleBatches = fresh- .filter((e) => e.type === "usage_tick" && planFor(e) === "pro" && e.org_id && e.sandbox_id && tickFromCurrentWorker(e))+ .filter(+ (e) =>+ e.type === "usage_tick" &&+ (planFor(e) === "pro" || providerFor(e) === "autumn") &&+ e.org_id &&+ e.sandbox_id &&+ tickFromCurrentWorker(e),+ ).map((e) => {const p = (e.payload ?? {}) as {memory_mb?: number;diff --git a/cloudflare-workers/schema_phase6.sql b/cloudflare-workers/schema_phase6.sqlindex 3d871af3..63a1b77d 100644--- a/cloudflare-workers/schema_phase6.sql+++ b/cloudflare-workers/schema_phase6.sql@@ -27,3 +27,11 @@ ALTER TABLE orgs ADD COLUMN billing_provider TEXT NOT NULL DEFAULT 'legacy';-- Cutover backfill / dashboard reads filter on it; partial index keeps the-- "which orgs are on Autumn" sweep tight while almost everyone is still legacy.CREATE INDEX IF NOT EXISTS idx_orgs_billing_provider ON orgs(billing_provider) WHERE billing_provider = 'autumn';++-- Per-org watermark (unix seconds) for the edge autumn meter loop: the end of+-- the last fully-tracked 5-minute bucket. 0 = unseeded; the first cron sight+-- seeds it to "now" and bills forward only (never retroactively charges usage+-- accrued before the org moved to Autumn). This is the edge-native replacement+-- for the cell's orgs.last_usage_synced_at — billing is one place (the edge),+-- off usage_samples, not per-cell.+ALTER TABLE orgs ADD COLUMN autumn_usage_watermark INTEGER NOT NULL DEFAULT 0;diff --git a/cmd/server/main.go b/cmd/server/main.goindex 2e80291b..a1935ff9 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -19,7 +19,6 @@ import ("github.com/opensandbox/opensandbox/internal/api""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/billing"- "github.com/opensandbox/opensandbox/internal/billing/autumn""github.com/opensandbox/opensandbox/internal/cloudflare""github.com/opensandbox/opensandbox/internal/compute""github.com/opensandbox/opensandbox/internal/config"@@ -776,50 +775,10 @@ func main() {log.Println("opensandbox: usage reporter started (interval=5m)")}- // Start Autumn usage reporter (Phase 2: SHADOW). Ships per-org compute/disk- // usage to Autumn via track() for orgs flagged billing_provider='autumn',- // building the real ledger and logging a parity line against our local cost- // math — but never halting yet. Inert unless an Autumn API key is set.- if opts.Store != nil && cfg.AutumnSecretKey != "" {- var autumnOpts []autumn.Option- if cfg.AutumnBaseURL != "" {- autumnOpts = append(autumnOpts, autumn.WithBaseURL(cfg.AutumnBaseURL))- }- autumnClient := autumn.New(cfg.AutumnSecretKey, autumnOpts...)- autumnReporter := billing.NewAutumnReporter(opts.Store, autumnClient)-- // Edge client for D1 projection (halt enforce + reconciler). Nil in- // combined dev mode where there's no separate edge.- var autumnEdge *edgeclient.Client- if cfg.CFEdgeBaseURL != "" && cfg.CFEventSecret != "" {- autumnEdge = edgeclient.New(cfg.CFEdgeBaseURL, cfg.CFEventSecret)- }-- // Enforce mode (off by default): on balance exhaustion, hibernate the- // org's sandboxes on this cell AND ask the edge to re-check Autumn and- // project is_halted into D1 so create/wake gates reject it everywhere.- if cfg.AutumnEnforce {- var workers billing.WorkerClientSource- if redisRegistry != nil {- workers = redisRegistry- }- autumnReporter.SetEnforce(true)- autumnReporter.SetHaltFunc(func(ctx context.Context, orgID uuid.UUID) error {- if _, err := billing.EnforceCreditExhaustion(ctx, opts.Store, workers, orgID); err != nil {- log.Printf("autumn: local hibernate for %s: %v", orgID, err)- }- if autumnEdge != nil {- return autumnEdge.ProjectAutumnOrg(ctx, orgID)- }- return nil- })- log.Println("opensandbox: autumn usage reporter ENFORCING (halt on exhaustion)")- }-- autumnReporter.Start()- defer autumnReporter.Stop()- log.Println("opensandbox: autumn usage reporter started (interval=5m)")- }+ // Autumn billing is edge-native: the api-edge `autumn-meter` cron meters+ // usage_samples to Autumn and halts on exhaustion (one place, not per-cell).+ // The cell only EXECUTES halts dispatched to /admin/halt-org (HaltOrg). No+ // per-cell Autumn reporter here anymore — that would double-track usage.// Halt reconciler — safety net for missed CF halt webhooks. Pulls the// authoritative halt-list from api-edge every 60s and re-issues haltsdiff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex dfb69755..0849883b 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -53,6 +53,7 @@ func (s *Server) capTokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {}}auth.SetPlan(c, claims.Plan)+ auth.SetBillingProvider(c, claims.BillingProvider)return next(c)}}diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 3633e94e..333f704e 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -61,6 +61,7 @@ func (s *Server) createSandbox(c echo.Context) error {orgID, hasOrg := auth.GetOrgID(c)var org *db.Orgvar effPlan string+ var effProvider stringif hasOrg && s.store != nil {var err errororg, err = s.store.GetOrg(ctx, orgID)@@ -69,6 +70,7 @@ func (s *Server) createSandbox(c echo.Context) error {// → D1 org-policy → cell-PG last resort), never trusting the stale// cell-PG org row outright. See effectivePlan.effPlan = s.effectivePlan(c, orgID)+ effProvider = s.effectiveBillingProvider(c, orgID)// Concurrent sandbox limit applies to all plans.count, err := s.store.CountActiveSandboxes(ctx, orgID)@@ -78,8 +80,12 @@ func (s *Server) createSandbox(c echo.Context) error {})}- // Free-tier: trial credits gate + machine-size restriction.- if effPlan == "free" {+ // Free-tier gate (legacy only): trial-credit + machine-size limit.+ // Autumn orgs pay per GB-second and are gated at the edge+ // (balance/halt), so neither the credit check nor the size ceiling+ // applies — they may launch any size (disk still bounded by the+ // per-org MaxDiskMB knob below).+ if effPlan == "free" && effProvider != "autumn" {if org.FreeCreditsRemainingCents <= 0 {return c.JSON(http.StatusPaymentRequired, map[string]string{"error": "free trial credits exhausted — upgrade to pro to create new sandboxes",@@ -115,7 +121,7 @@ func (s *Server) createSandbox(c echo.Context) error {})}if org != nil {- if effPlan == "free" && cfg.DiskMB > 20480 {+ if effPlan == "free" && effProvider != "autumn" && cfg.DiskMB > 20480 {return c.JSON(http.StatusPaymentRequired, map[string]string{"error": "upgrade to pro for larger disk sizes",})@@ -1151,6 +1157,23 @@ func (s *Server) effectivePlan(c echo.Context, orgID uuid.UUID) string {return ""}+// effectiveBillingProvider resolves the org's billing provider ("legacy" |+// "autumn") the same way effectivePlan resolves the plan: prefer the cap-token+// value (edge-authoritative, stamped from D1 at mint time), falling back to the+// cell-PG org row for direct API-key requests. Autumn orgs are exempt from the+// legacy free-tier size ceilings — they pay per GB-second.+func (s *Server) effectiveBillingProvider(c echo.Context, orgID uuid.UUID) string {+ if bp, ok := auth.GetBillingProvider(c); ok {+ return bp+ }+ if s.store != nil {+ if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org != nil {+ return org.BillingProvider+ }+ }+ return ""+}+func (s *Server) setLimits(c echo.Context) error {id := c.Param("id")ctx := c.Request().Context()@@ -1179,7 +1202,7 @@ func (s *Server) setLimits(c echo.Context) error {// Free tier: block scaling beyond 4GB / 1 vCPU. Plan comes from the// cap-token (edge-authoritative) when present, else the cell-PG copy.if orgID, hasOrg := auth.GetOrgID(c); hasOrg {- if s.effectivePlan(c, orgID) == "free" && (req.MemoryMB > 4096 || req.CPUPercent > 100) {+ if s.effectivePlan(c, orgID) == "free" && s.effectiveBillingProvider(c, orgID) != "autumn" && (req.MemoryMB > 4096 || req.CPUPercent > 100) {return c.JSON(http.StatusPaymentRequired, map[string]string{"error": "upgrade to pro for larger instances",})@@ -1233,9 +1256,10 @@ func (s *Server) scaleSandbox(c echo.Context) error {}// Free tier: block scaling beyond 4GB. Plan comes from the cap-token- // (edge-authoritative) when present, else the cell-PG copy.+ // (edge-authoritative) when present, else the cell-PG copy. Autumn orgs are+ // metered, not tiered, so the ceiling doesn't apply to them.if orgID, hasOrg := auth.GetOrgID(c); hasOrg {- if s.effectivePlan(c, orgID) == "free" && req.MemoryMB > 4096 {+ if s.effectivePlan(c, orgID) == "free" && s.effectiveBillingProvider(c, orgID) != "autumn" && req.MemoryMB > 4096 {return c.JSON(http.StatusPaymentRequired, map[string]string{"error": "upgrade to pro for larger instances",})diff --git a/internal/auth/middleware.go b/internal/auth/middleware.goindex 6856da5a..657fdfa9 100644--- a/internal/auth/middleware.go+++ b/internal/auth/middleware.go@@ -20,6 +20,11 @@ const (// the request carried an edge-minted cap-token (which stamps the plan from// D1 at mint time). Absent for direct API-key auth.ContextKeyPlan contextKey = "plan"+ // ContextKeyBillingProvider is the echo context key for the org's billing+ // provider ("legacy" | "autumn"), stamped onto the cap-token from D1 at mint+ // time. Autumn orgs pay per GB-second, so size gates that key off the legacy+ // free-tier plan must not apply to them. Absent for direct API-key auth.+ ContextKeyBillingProvider contextKey = "billing_provider")// SetOrgID stores the org ID in the echo context.@@ -66,6 +71,30 @@ func GetPlan(c echo.Context) (string, bool) {return p, true}+// SetBillingProvider stores the org's billing provider (from a cap-token) in the+// echo context. Empty strings are ignored so a later authoritative value isn't+// clobbered by an absent one.+func SetBillingProvider(c echo.Context, provider string) {+ if provider != "" {+ c.Set(string(ContextKeyBillingProvider), provider)+ }+}++// GetBillingProvider retrieves the cap-token-supplied billing provider from the+// echo context. The bool is false when the request didn't carry one (e.g. direct+// API-key auth), so callers can fall back to a cell-PG lookup.+func GetBillingProvider(c echo.Context) (string, bool) {+ v := c.Get(string(ContextKeyBillingProvider))+ if v == nil {+ return "", false+ }+ p, ok := v.(string)+ if !ok || p == "" {+ return "", false+ }+ return p, true+}+// GetUserID retrieves the user ID from the echo context. Returns nil if not set.func GetUserID(c echo.Context) *uuid.UUID {v := c.Get(string(ContextKeyUserID))@@ -141,6 +170,7 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer,// instead of the cell-PG copy, which goes stale on// plan changes between sandbox creates.SetPlan(c, claims.Plan)+ SetBillingProvider(c, claims.BillingProvider)return next(c)}}diff --git a/internal/billing/autumn_reporter.go b/internal/billing/autumn_reporter.godeleted file mode 100644index acc9fbcd..00000000--- a/internal/billing/autumn_reporter.go+++ /dev/null@@ -1,238 +0,0 @@-package billing--import (- "context"- "log"- "time"-- "github.com/google/uuid"- "github.com/opensandbox/opensandbox/internal/billing/autumn"- "github.com/opensandbox/opensandbox/internal/db"-)--// autumnBucketSize is the fixed window each track() call covers. Buckets are-// aligned to each org's seed watermark (not wall-clock) and are the unit of-// idempotency: a retried bucket reuses the same idempotency_key, so Autumn-// dedupes it. It also bounds the overspend window once enforcement is on-// (Phase 3) — usage can run at most one bucket past a zero balance before the-// inline halt fires. 5m matches the legacy reporter's debit cadence.-const autumnBucketSize = 5 * time.Minute--// autumnUsageStore is the narrow slice of *db.Store the reporter needs. Keeping-// it an interface lets the bucket/idempotency logic be unit-tested against an-// in-memory fake without standing up Postgres.-type autumnUsageStore interface {- ListAutumnOrgIDsWithUsage(ctx context.Context) ([]uuid.UUID, error)- GetOrg(ctx context.Context, id uuid.UUID) (*db.Org, error)- GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]db.OrgUsageSummary, error)- SetLastUsageSyncedAt(ctx context.Context, orgID uuid.UUID, t time.Time) error-}--// HaltFunc halts an org whose Autumn balance is exhausted: hibernate its running-// sandboxes locally (via EnforceCreditExhaustion) and project is_halted to the-// edge (D1) so create/wake gates reject it everywhere. Injected via SetHaltFunc;-// nil keeps the reporter in shadow (log-only) even when enforce is on.-type HaltFunc func(ctx context.Context, orgID uuid.UUID) error--// AutumnReporter ships per-org compute/disk usage to Autumn via track(). It is-// the Autumn-side counterpart of UsageReporter and runs only for orgs flagged-// billing_provider='autumn'.-//-// Phase 2 (now): SHADOW. It tracks usage to Autumn (building the real ledger)-// but never halts — it only logs a parity line comparing our locally-computed-// cost against Autumn's returned balance, so we can confirm Autumn's credit-// schema matches pricing.go before any org's sandboxes are gated on it.-//-// Phase 3 will flip enforce=true: when a bucket's track() comes back with-// Remaining <= 0, the reporter halts the org inline (same tightness as today's-// debit loop) instead of just logging.-type AutumnReporter struct {- store autumnUsageStore- client autumn.Client- interval time.Duration- enforce bool- halt HaltFunc // invoked on exhaustion when enforce is on- now func() time.Time // injectable clock (tests)-- stop chan struct{}- stopped chan struct{}-}--func NewAutumnReporter(store autumnUsageStore, client autumn.Client) *AutumnReporter {- return &AutumnReporter{- store: store,- client: client,- interval: 5 * time.Minute,- enforce: false, // shadow until Phase 3- now: time.Now,- stop: make(chan struct{}),- stopped: make(chan struct{}),- }-}--// SetEnforce flips the reporter out of shadow mode: track() responses with a-// non-positive balance halt the org inline (requires a HaltFunc). Wired in Phase 3.-func (r *AutumnReporter) SetEnforce(enabled bool) { r.enforce = enabled }--// SetHaltFunc installs the action taken when an org's balance is exhausted.-func (r *AutumnReporter) SetHaltFunc(fn HaltFunc) { r.halt = fn }--func (r *AutumnReporter) Start() { go r.loop() }-func (r *AutumnReporter) Stop() { close(r.stop); <-r.stopped }--func (r *AutumnReporter) loop() {- defer close(r.stopped)- ticker := time.NewTicker(r.interval)- defer ticker.Stop()- for {- select {- case <-ticker.C:- r.safeReportAll()- case <-r.stop:- return- }- }-}--func (r *AutumnReporter) safeReportAll() {- defer func() {- if p := recover(); p != nil {- log.Printf("autumn-reporter: panic in tick: %v", p)- }- }()- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)- defer cancel()- r.reportAll(ctx)-}--func (r *AutumnReporter) reportAll(ctx context.Context) {- orgIDs, err := r.store.ListAutumnOrgIDsWithUsage(ctx)- if err != nil {- log.Printf("autumn-reporter: failed to list autumn orgs: %v", err)- return- }- if len(orgIDs) == 0 {- return- }- log.Printf("autumn-reporter: tracking usage for %d org(s)", len(orgIDs))- for _, orgID := range orgIDs {- if err := r.reportOrg(ctx, orgID); err != nil {- log.Printf("autumn-reporter: org %s: %v", orgID, err)- }- }-}--// reportOrg ships every fully-elapsed bucket since the org's watermark to-// Autumn, advancing the watermark one bucket at a time so a mid-run failure-// only replays the unfinished bucket (whose idempotency keys dedupe).-func (r *AutumnReporter) reportOrg(ctx context.Context, orgID uuid.UUID) error {- org, err := r.store.GetOrg(ctx, orgID)- if err != nil {- return err- }- if org.BillingProvider != "autumn" {- return nil // flag flipped back between listing and now- }-- now := r.now()-- // First sight: seed the watermark to now and bill forward only — never- // retroactively charge usage that accrued before the org moved to Autumn.- if org.LastUsageSyncedAt == nil {- if err := r.store.SetLastUsageSyncedAt(ctx, orgID, now); err != nil {- return err- }- log.Printf("autumn-reporter: org %s seeded watermark at %s", orgID, now.Format(time.RFC3339))- return nil- }-- cursor := *org.LastUsageSyncedAt- for bucketEnd := cursor.Add(autumnBucketSize); !bucketEnd.After(now); bucketEnd = cursor.Add(autumnBucketSize) {- if err := r.trackBucket(ctx, org, cursor, bucketEnd); err != nil {- // Leave the watermark where it is; the next tick replays this- // bucket with the same idempotency keys (Autumn dedupes the parts- // that already landed).- return err- }- if err := r.store.SetLastUsageSyncedAt(ctx, orgID, bucketEnd); err != nil {- return err- }- cursor = bucketEnd- }- return nil-}--// trackBucket reports one [from, to) window: one track() per compute tier plus-// one for disk overage, then (shadow) logs the parity line.-func (r *AutumnReporter) trackBucket(ctx context.Context, org *db.Org, from, to time.Time) error {- usage, err := r.store.GetOrgUsage(ctx, org.ID.String(), from, to)- if err != nil {- return err- }- if len(usage) == 0 {- return nil- }-- bucketStart := from.Unix()- var lastBalance float64- var diskGBSeconds float64- tracked := false-- for _, u := range usage {- diskGBSeconds += DiskOverageGBSeconds(u)- if u.TotalSeconds <= 0 {- continue- }- feature, ok := autumn.FeatureForMemoryMB(u.MemoryMB)- if !ok {- log.Printf("autumn-reporter: org %s unknown memory tier %dMB — skipping", org.ID, u.MemoryMB)- continue- }- res, err := r.client.Track(ctx, autumn.TrackParams{- CustomerID: org.ID.String(),- FeatureID: feature,- Value: u.TotalSeconds,- IdempotencyKey: autumn.UsageIdempotencyKey(org.ID.String(), bucketStart, feature),- })- if err != nil {- return err- }- lastBalance = res.Balance.Remaining- tracked = true- }-- if diskGBSeconds > 0 {- res, err := r.client.Track(ctx, autumn.TrackParams{- CustomerID: org.ID.String(),- FeatureID: autumn.DiskOverageFeatureID,- Value: diskGBSeconds,- IdempotencyKey: autumn.UsageIdempotencyKey(org.ID.String(), bucketStart, autumn.DiskOverageFeatureID),- })- if err != nil {- return err- }- lastBalance = res.Balance.Remaining- tracked = true- }-- if !tracked {- return nil- }-- ourCents := CalculateUsageCostCents(usage)- log.Printf("autumn-reporter: org %s bucket [%s,%s) our_cost=$%.4f autumn_remaining=$%.4f",- org.ID, from.Format("15:04"), to.Format("15:04"), ourCents/100.0, lastBalance)-- if lastBalance <= 0 {- if r.enforce && r.halt != nil {- if err := r.halt(ctx, org.ID); err != nil {- log.Printf("autumn-reporter: org %s halt failed: %v", org.ID, err)- } else {- log.Printf("autumn-reporter: org %s balance exhausted — halted", org.ID)- }- } else {- log.Printf("autumn-reporter: org %s balance exhausted — WOULD halt (shadow)", org.ID)- }- }- return nil-}diff --git a/internal/billing/autumn_reporter_test.go b/internal/billing/autumn_reporter_test.godeleted file mode 100644index 85d96aeb..00000000--- a/internal/billing/autumn_reporter_test.go+++ /dev/null@@ -1,232 +0,0 @@-package billing--import (- "context"- "testing"- "time"-- "github.com/google/uuid"- "github.com/opensandbox/opensandbox/internal/billing/autumn"- "github.com/opensandbox/opensandbox/internal/db"-)--// fakeAutumnStore is an in-memory autumnUsageStore. Usage is keyed by the bucket-// start (Unix seconds), so GetOrgUsage returns exactly what the reporter's-// bucketing asks for — this tests the reporter's windowing/idempotency without-// reimplementing GetOrgUsage's SQL clipping.-type fakeAutumnStore struct {- orgs map[uuid.UUID]*db.Org- usageByFrom map[int64][]db.OrgUsageSummary-}--func newFakeAutumnStore() *fakeAutumnStore {- return &fakeAutumnStore{- orgs: map[uuid.UUID]*db.Org{},- usageByFrom: map[int64][]db.OrgUsageSummary{},- }-}--func (f *fakeAutumnStore) ListAutumnOrgIDsWithUsage(_ context.Context) ([]uuid.UUID, error) {- var ids []uuid.UUID- for id, o := range f.orgs {- if o.BillingProvider == "autumn" {- ids = append(ids, id)- }- }- return ids, nil-}--func (f *fakeAutumnStore) GetOrg(_ context.Context, id uuid.UUID) (*db.Org, error) {- return f.orgs[id], nil-}--func (f *fakeAutumnStore) GetOrgUsage(_ context.Context, _ string, from, _ time.Time) ([]db.OrgUsageSummary, error) {- return f.usageByFrom[from.Unix()], nil-}--func (f *fakeAutumnStore) SetLastUsageSyncedAt(_ context.Context, orgID uuid.UUID, t time.Time) error {- tc := t- f.orgs[orgID].LastUsageSyncedAt = &tc- return nil-}--func creditsRemaining(t *testing.T, fake *autumn.Fake, orgID string) float64 {- t.Helper()- c, err := fake.GetCustomer(context.Background(), orgID)- if err != nil {- t.Fatalf("GetCustomer: %v", err)- }- return c.CreditsRemaining()-}--// fixed base time so bucket math is exact and reproducible.-var baseT = time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)--func newTestReporter(store autumnUsageStore, client autumn.Client, now time.Time) *AutumnReporter {- r := NewAutumnReporter(store, client)- r.now = func() time.Time { return now }- return r-}--func TestAutumnReporter_seedsWatermarkWithoutBilling(t *testing.T) {- store := newFakeAutumnStore()- id := uuid.New()- store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT} // LastUsageSyncedAt nil-- fake := autumn.NewFake()- fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})-- r := newTestReporter(store, fake, baseT.Add(time.Hour))- r.reportAll(context.Background())-- if store.orgs[id].LastUsageSyncedAt == nil {- t.Fatal("expected watermark seeded on first sight")- }- if got := *store.orgs[id].LastUsageSyncedAt; !got.Equal(baseT.Add(time.Hour)) {- t.Fatalf("watermark = %v, want seed = now", got)- }- if bal := creditsRemaining(t, fake, id.String()); bal != 5 {- t.Fatalf("balance = %v, want 5 (no retroactive billing on seed)", bal)- }-}--func TestAutumnReporter_tracksCompleteBucketsOnly(t *testing.T) {- store := newFakeAutumnStore()- id := uuid.New()- wm := baseT- store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}-- // bucket 0: [baseT, +5m) — a 64GB box for the full 300s.- store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 300}}- // bucket 1: [+5m, +10m) — a 1GB box + 1GB disk overage for 300s.- store.usageByFrom[baseT.Add(5*time.Minute).Unix()] = []db.OrgUsageSummary{- {MemoryMB: 1024, TotalSeconds: 300, DiskMB: DiskFreeAllowanceMB + 1024},- }-- fake := autumn.NewFake()- fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})-- // now = +12m → buckets 0 and 1 are complete; [+10m,+15m) is not.- r := newTestReporter(store, fake, baseT.Add(12*time.Minute))- r.reportAll(context.Background())-- wantWM := baseT.Add(10 * time.Minute)- if got := *store.orgs[id].LastUsageSyncedAt; !got.Equal(wantWM) {- t.Fatalf("watermark = %v, want %v (partial bucket deferred)", got, wantWM)- }-- // Expected deduction via the Fake's credit schema.- cc := fake.CreditCosts- want := 5.0 -- 300*cc["compute_64gb"] -- 300*cc["compute_1gb"] -- 300*cc["disk_overage"] // 1GB overage × 300s = 300 GB-seconds- if bal := creditsRemaining(t, fake, id.String()); !almostEqual(bal, want) {- t.Fatalf("balance = %v, want %v", bal, want)- }-}--func TestAutumnReporter_idempotentReplay(t *testing.T) {- store := newFakeAutumnStore()- id := uuid.New()- wm := baseT- store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}- store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 300}}-- fake := autumn.NewFake()- fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})-- r := newTestReporter(store, fake, baseT.Add(7*time.Minute)) // 1 complete bucket- r.reportAll(context.Background())- afterFirst := creditsRemaining(t, fake, id.String())-- // Rewind the watermark to force a replay of the same bucket — the stable- // idempotency keys must make Autumn dedupe, leaving the balance untouched.- store.orgs[id].LastUsageSyncedAt = &wm- r.reportAll(context.Background())- afterReplay := creditsRemaining(t, fake, id.String())-- if !almostEqual(afterFirst, afterReplay) {- t.Fatalf("replay double-charged: first=%v replay=%v", afterFirst, afterReplay)- }-}--func TestAutumnReporter_skipsUnknownTierButAdvances(t *testing.T) {- store := newFakeAutumnStore()- id := uuid.New()- wm := baseT- store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}- store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 2048, TotalSeconds: 300}} // unmapped tier-- fake := autumn.NewFake()- fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})-- r := newTestReporter(store, fake, baseT.Add(7*time.Minute))- r.reportAll(context.Background())-- if bal := creditsRemaining(t, fake, id.String()); bal != 5 {- t.Fatalf("balance = %v, want 5 (unknown tier not charged)", bal)- }- if got := *store.orgs[id].LastUsageSyncedAt; !got.Equal(baseT.Add(5 * time.Minute)) {- t.Fatalf("watermark = %v, want bucket advanced past unknown tier", got)- }-}--func TestAutumnReporter_haltsOnExhaustionWhenEnforced(t *testing.T) {- store := newFakeAutumnStore()- id := uuid.New()- wm := baseT- store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}- // A 64GB box for 10000s costs > $5 → drives the $5 grant negative.- store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 10000}}-- fake := autumn.NewFake()- fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})-- var halted []uuid.UUID- r := newTestReporter(store, fake, baseT.Add(7*time.Minute))- r.SetEnforce(true)- r.SetHaltFunc(func(_ context.Context, orgID uuid.UUID) error {- halted = append(halted, orgID)- return nil- })- r.reportAll(context.Background())-- if len(halted) != 1 || halted[0] != id {- t.Fatalf("expected halt(%s), got %v", id, halted)- }- if bal := creditsRemaining(t, fake, id.String()); bal >= 0 {- t.Fatalf("balance = %v, want negative (exhausted)", bal)- }-}--func TestAutumnReporter_shadowNeverHalts(t *testing.T) {- store := newFakeAutumnStore()- id := uuid.New()- wm := baseT- store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}- store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 10000}}-- fake := autumn.NewFake()- fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})-- var halted []uuid.UUID- r := newTestReporter(store, fake, baseT.Add(7*time.Minute)) // enforce=false (default)- r.SetHaltFunc(func(_ context.Context, orgID uuid.UUID) error {- halted = append(halted, orgID)- return nil- })- r.reportAll(context.Background())-- if len(halted) != 0 {- t.Fatalf("shadow mode must not halt; got %v", halted)- }-}--func almostEqual(a, b float64) bool {- d := a - b- if d < 0 {- d = -d- }- return d < 1e-9-}diff --git a/internal/db/usage.go b/internal/db/usage.goindex b91afe4e..064717ce 100644--- a/internal/db/usage.go+++ b/internal/db/usage.go@@ -301,44 +301,11 @@ func (s *Store) SetBillingProvider(ctx context.Context, orgID uuid.UUID, providereturn err}-// SetLastUsageSyncedAt advances the external metered-billing (Autumn) loop's-// watermark. Separate from last_usage_reported_at so the shadow Autumn reporter-// and the legacy reporter can run concurrently without starving each other.-func (s *Store) SetLastUsageSyncedAt(ctx context.Context, orgID uuid.UUID, t time.Time) error {- _, err := s.pool.Exec(ctx,- `UPDATE orgs SET last_usage_synced_at = $2 WHERE id = $1`,- orgID, t)- return err-}--// ListAutumnOrgIDsWithUsage returns org IDs whose billing_provider is 'autumn'-// and that have scale-event usage not yet shipped to Autumn — either a-// currently-running sandbox or a scale event that ended after the org's-// last_usage_synced_at watermark. Orgs first seen (NULL watermark) are included-// so the reporter can seed them; it bills forward from now, never retroactively.-func (s *Store) ListAutumnOrgIDsWithUsage(ctx context.Context) ([]uuid.UUID, error) {- rows, err := s.pool.Query(ctx,- `SELECT DISTINCT se.org_id- FROM sandbox_scale_events se- JOIN orgs o ON o.id = se.org_id- WHERE o.billing_provider = 'autumn'- AND (se.ended_at IS NULL- OR se.ended_at > COALESCE(o.last_usage_synced_at, o.created_at))`)- if err != nil {- return nil, err- }- defer rows.Close()-- var ids []uuid.UUID- for rows.Next() {- var id uuid.UUID- if err := rows.Scan(&id); err != nil {- return nil, err- }- ids = append(ids, id)- }- return ids, rows.Err()-}+// Autumn billing moved to the edge (api-edge autumn-meter cron, off D1+// usage_samples). The cell no longer ships Autumn usage, so the per-cell+// watermark helpers (SetLastUsageSyncedAt / ListAutumnOrgIDsWithUsage) and the+// orgs.last_usage_synced_at column they drove are retired — see+// cloudflare-workers/src/autumn_meter.ts for the replacement.// ListBillableOrgIDs returns org IDs with plan="pro" AND// billing_mode='legacy' that have unreported usage: either adiff --git a/scripts/dev/autumn-test.sh b/scripts/dev/autumn-test.shnew file mode 100755index 00000000..727c07c3--- /dev/null+++ b/scripts/dev/autumn-test.sh@@ -0,0 +1,57 @@+#!/usr/bin/env bash+# Dev-only Autumn billing test helper. NOT part of any deploy — local use only.+#+# Autumn key + EVENT_SECRET are Infisical-injected (not in dev Key Vault), so+# export them first (values from Infisical / the Autumn dashboard):+# export AUTUMN_SK=am_sk_... # for customer / set-balance+# export EVENT_SECRET=... # for project+# Nothing sensitive is written to disk or echoed. Org state is read from D1.+#+# ./autumn-test.sh state <org-prefix|uuid> # D1: provider/halt/concurrency/balance+# ./autumn-test.sh customer <org-uuid> # Autumn: balance + subscriptions+# ./autumn-test.sh set-balance <org-uuid> <usd> # Autumn: overwrite credit balance+# ./autumn-test.sh project <org-uuid> # force edge re-projection (signed)+#+# Typical halt test: set-balance <org> 0 -> project <org> -> state <org> (is_halted=1)+set -euo pipefail++VAULT=opensandbox-dev-kv+EDGE=https://app2.opensandbox.ai+AUTUMN=https://api.useautumn.com/v1+D1DIR="$(cd "$(dirname "$0")/../../cloudflare-workers/api-edge" && pwd)"++kv() { az keyvault secret show --vault-name "$VAULT" --name "$1" --query value -o tsv 2>/dev/null; }++cmd="${1:-}"; org="${2:-}"+[ -z "$cmd" ] && { grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0; }++case "$cmd" in+ state)+ [ -z "$org" ] && { echo "need <org>"; exit 1; }+ ( cd "$D1DIR" && node_modules/.bin/wrangler d1 execute opencomputer-dev --remote --json \+ --command "SELECT substr(id,1,8) org, plan, billing_provider, is_halted, max_concurrent_sandboxes, free_credits_remaining_cents, credit_balance_cents, max_disk_mb FROM orgs WHERE id LIKE '${org}%';" 2>/dev/null ) \+ | python3 -c "import sys,json;[print(r) for r in json.load(sys.stdin)[0]['results']] or print('no match')"+ ;;+ customer)+ [ -z "$org" ] && { echo "need <org-uuid>"; exit 1; }+ SK="${AUTUMN_SK:-$(kv server-autumn-secret-key)}"+ curl -s "$AUTUMN/customers/$org" -H "Authorization: Bearer $SK" \+ | python3 -c "import sys,json;d=json.load(sys.stdin);print('balance:',d.get('balances',{}).get('credits',{}).get('remaining'));print('subs:',[{ 'plan':s.get('plan_id'),'status':s.get('status')} for s in d.get('subscriptions',[])])"+ ;;+ set-balance)+ usd="${3:-}"; [ -z "$org" ] || [ -z "$usd" ] && { echo "need <org-uuid> <usd>"; exit 1; }+ SK="${AUTUMN_SK:-$(kv server-autumn-secret-key)}"+ curl -s -X POST "$AUTUMN/customers/$org/balances" -H "Authorization: Bearer $SK" \+ -H "content-type: application/json" \+ -d "{\"balances\":[{\"feature_id\":\"credits\",\"balance\":$usd}]}" -o /dev/null -w "set-balance -> HTTP %{http_code}\n"+ ;;+ project)+ [ -z "$org" ] && { echo "need <org-uuid>"; exit 1; }+ ES="${EVENT_SECRET:-$(kv server-cf-event-secret)}"+ ts=$(date +%s); path="/internal/autumn-project"; body="{\"org_id\":\"$org\"}"+ sig=$(printf '%s' "$ts.$path.$body" | openssl dgst -sha256 -hmac "$ES" -hex | sed 's/^.*= //')+ curl -s -X POST "$EDGE$path" -H "X-Timestamp: $ts" -H "X-Signature: $sig" \+ -H "content-type: application/json" -d "$body" -w "\nproject -> HTTP %{http_code}\n"+ ;;+ *) echo "unknown: $cmd"; grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 1;;+esacdiff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 7764788f..098764a4 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -356,6 +356,7 @@ export interface AutumnBilling {maxConcurrentSandboxes: numberconcurrencyPlan: string // 'base' | 'concurrency_pro' | 'concurrency_pro_plus' | 'concurrency_pro_plus_plus'isHalted: boolean+ hasToppedUp: boolean // charged a top-up before → auto-recharge is armed (enabling won't re-charge)autoTopup: AutumnAutoTopup | null}@@ -392,20 +393,24 @@ export const redeemPromoCode = (code: string) =>// Autumn prepaid billing APIexport const getAutumnBilling = () => apiFetch<AutumnBilling>('/billing/autumn')+// url is non-null → redirect to a hosted Stripe flow (no card yet); null → the+// existing card was charged server-side, so just refresh the balance.export const autumnTopup = (credits: number) =>- apiFetch<{ url: string }>('/billing/autumn/topup', {+ apiFetch<{ url: string | null }>('/billing/autumn/topup', {method: 'POST',body: JSON.stringify({ credits }),})export const autumnSubscribeConcurrency = (plan: string) =>- apiFetch<{ url: string }>('/billing/autumn/concurrency', {+ apiFetch<{ url: string | null }>('/billing/autumn/concurrency', {method: 'POST',body: JSON.stringify({ plan }),})+// url is non-null when enabling auto-recharge requires capturing an off-session+// card first — the caller redirects there (a no-charge Stripe setup session).export const setAutumnAutoTopup = (cfg: { enabled: boolean; threshold: number; quantity: number }) =>- apiFetch<{ ok: boolean }>('/billing/autumn/auto-topup', {+ apiFetch<{ ok: boolean; url?: string | null }>('/billing/autumn/auto-topup', {method: 'POST',body: JSON.stringify(cfg),})diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex dab9870e..262ab322 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -278,16 +278,24 @@ function PrepaidPlan() {queryKey: ['autumn-billing'], queryFn: getAutumnBilling, refetchInterval: 30_000,})const [amount, setAmount] = useState<number>(25)+ const queryClient = useQueryClient()+ // url present → redirect to hosted checkout (collect a new card); url null →+ // the existing card was charged server-side, so just refresh the balance.+ const onPurchase = (data: { url: string | null }) => {+ if (data.url) window.location.href = data.url+ else queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })+ }const topupMutation = useMutation({mutationFn: () => autumnTopup(amount),- onSuccess: (data) => { window.location.href = data.url },+ onSuccess: onPurchase,})const planMutation = useMutation({mutationFn: (plan: string) => autumnSubscribeConcurrency(plan),- onSuccess: (data) => { window.location.href = data.url },+ onSuccess: onPurchase,})+if (isLoading) {return (<div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>@@ -377,7 +385,7 @@ function PrepaidPlan() {</div></div>- <AutoTopupCard current={autumn?.autoTopup ?? null} />+ <AutoTopupCard current={autumn?.autoTopup ?? null} hasToppedUp={autumn?.hasToppedUp ?? false} />{/* Concurrency plans */}<div className="glass-card animate-in stagger-3" style={{ padding: 28 }}>@@ -519,7 +527,7 @@ const autoTopupInputStyle = {background: 'transparent', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontSize: 13,}-function AutoTopupCard({ current }: { current: AutumnBilling['autoTopup'] }) {+function AutoTopupCard({ current, hasToppedUp }: { current: AutumnBilling['autoTopup']; hasToppedUp: boolean }) {const queryClient = useQueryClient()const [enabled, setEnabled] = useState(current?.enabled ?? false)const [threshold, setThreshold] = useState(current?.threshold ?? 5)@@ -528,7 +536,11 @@ function AutoTopupCard({ current }: { current: AutumnBilling['autoTopup'] }) {const mutation = useMutation({mutationFn: () => setAutumnAutoTopup({ enabled, threshold, quantity }),- onSuccess: () => {+ onSuccess: (data) => {+ // Auto-recharge needs a saved off-session card. If enabling without one, the+ // server returns a no-charge Stripe setup URL — redirect to capture the card,+ // after which auto-recharge is live. Otherwise just confirm the save.+ if (data?.url) { window.location.href = data.url; return }queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })setSaved(true)setTimeout(() => setSaved(false), 3000)@@ -584,7 +596,8 @@ function AutoTopupCard({ current }: { current: AutumnBilling['autoTopup'] }) {</button>{enabled && (<div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 10 }}>- Requires a payment method on file — added automatically on your first top-up.+ Charges your saved card automatically when the balance drops below the threshold.+ {!hasToppedUp && ` Since you haven't topped up yet, enabling runs your first $${quantity} recharge now to set up your card.`}</div>)}{mutation.isError && (