An open-source, faster Devin alternative
TypeScript
billing: keep the stored warning current (Devin review on #960)
Mohamed Habib via Computer32d6f2a70e8a
diff --git a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.tsindex bf00a97a..19e8083e 100644--- a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts+++ b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts@@ -57,18 +57,23 @@ async function post(fields: Record<string, unknown>, envOverrides: Partial<Autumdescribe("managed-agent runtime usage billing", () => {afterEach(() => vi.restoreAllMocks());- it("re-projects a trial whose minutes cross the warning line", async () => {- const trial = (minutes: number) =>- Response.json({- id: "org_1",- subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],- balances: { work_minutes: { remaining: minutes }, credits: { remaining: 10 } },- });+ const trial = (minutes: number) =>+ Response.json({+ id: "org_1",+ subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],+ balances: { work_minutes: { remaining: minutes }, credits: { remaining: 10 } },+ });+ // D1 holding one org with the given trial start and stored warning.+ function orgDB(org: { trial_started_at: number | null; billing_warning: string | null }) {const writes: string[] = [];const db = {prepare: (sql: string) => ({bind: () => ({- first: async () => (sql.startsWith("SELECT is_halted") ? { is_halted: 0, usage_plan: "base" } : null),+ first: async () => {+ if (sql.startsWith("SELECT is_halted")) return { is_halted: 0, usage_plan: "base", ...org };+ if (sql.startsWith("SELECT trial_started_at")) return { payment_past_due_at: null, ...org };+ return null;+ },run: async () => {writes.push(sql);return { meta: { changes: 1 } };@@ -76,6 +81,11 @@ describe("managed-agent runtime usage billing", () => {}),}),} as unknown as D1Database;+ return { db, writes };+ }++ it("re-projects a trial whose minutes cross the warning line", async () => {+ const { db, writes } = orgDB({ trial_started_at: null, billing_warning: null });const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(trial(121))@@ -90,6 +100,35 @@ describe("managed-agent runtime usage billing", () => {expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);});+ it("replaces a trial_days warning once the minutes are the nearer limit", async () => {+ // Day 6: 100/600 minutes ranks behind 1/7 days; 80/600 ranks ahead of it.+ const daySix = Math.floor(Date.now() / 1000) - 6 * 86_400;+ const { db, writes } = orgDB({ trial_started_at: daySix, billing_warning: "trial_days" });+ vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(trial(100))+ .mockResolvedValueOnce(Response.json({ balance: { remaining: 80 } }))+ .mockResolvedValueOnce(trial(80))+ .mockResolvedValue(new Response(null, { status: 200 }));++ await post({ quantity_seconds: 1_200, close_reason: "turn_settled", idempotency_key: "crt_1:5" }, { OPENCOMPUTER_DB: db });++ expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);+ });++ it("does not re-project when the stored warning still stands", async () => {+ const { db, writes } = orgDB({ trial_started_at: null, billing_warning: "trial_minutes" });+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(trial(100))+ .mockResolvedValueOnce(Response.json({ balance: { remaining: 99 } }))+ .mockResolvedValue(new Response(null, { status: 200 }));++ await post({ close_reason: "turn_settled", idempotency_key: "crt_1:6" }, { OPENCOMPUTER_DB: db });++ expect(fetchMock.mock.calls.filter(([url]) => String(url).includes("/customers/org_1"))).toHaveLength(1);+ expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(false);+ });+it("bills an org on a work-minute plan in work minutes", async () => {const fetchMock = vi.spyOn(globalThis, "fetch")diff --git a/cloudflare-workers/api-edge/src/autumn_meter.ts b/cloudflare-workers/api-edge/src/autumn_meter.tsindex 4c58f214..8eebef05 100644--- a/cloudflare-workers/api-edge/src/autumn_meter.ts+++ b/cloudflare-workers/api-edge/src/autumn_meter.ts@@ -9,7 +9,7 @@// A bucket whose track() returns a non-positive balance triggers projectOrg →// is_halted + hibernate-dispatch.-import { type AutumnEnv, projectOrg, trackAutumnUsage } from "./autumn_webhook";+import { type AutumnEnv, creditsInWarningBand, projectOrg, refreshWarning, 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.@@ -106,25 +106,30 @@ async function meterOrg(env: AutumnEnv, org: AutumnOrgRow, nowSec: number): Promconst firstSampleSec = Math.floor(win.mn / 1000);cursor += Math.floor((firstSampleSec - cursor) / BUCKET_SEC) * BUCKET_SEC;+ let remaining: number | null = null;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);+ remaining = (await trackBucket(env, org.id, cursor, bucketEnd)) ?? remaining;await setWatermark(env, org.id, bucketEnd);cursor = bucketEnd;- if (exhausted) {+ if (remaining !== null && remaining <= 0) {// 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;}}+ // Spend inside a credit warning line ($2 left on a trial, under $5 paid):+ // store the warning on this tick rather than at the next webhook.+ if (remaining !== null && creditsInWarningBand(remaining)) await refreshWarning(env, org.id);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> {+// one usage event per tier to Autumn. Returns the credits left after it, or+// null when nothing was tracked.+async function trackBucket(env: AutumnEnv, orgID: string, fromSec: number, toSec: number): Promise<number | null> {const aggRes = await env.OPENCOMPUTER_DB.prepare(`SELECT memory_mb AS memory_mb, SUM(interval_s) AS secsFROM usage_samples@@ -134,7 +139,7 @@ async function trackBucket(env: AutumnEnv, orgID: string, fromSec: number, toSec.bind(orgID, fromSec * 1000, toSec * 1000).all<TierAgg>();const tiers = aggRes.results ?? [];- if (tiers.length === 0) return false;+ if (tiers.length === 0) return null;let remaining: number | null = null;for (const t of tiers) {@@ -151,7 +156,7 @@ async function trackBucket(env: AutumnEnv, orgID: string, fromSec: number, toSecidempotencyKey: usageIdempotencyKey(orgID, fromSec, feature),});}- return remaining !== null && remaining <= 0;+ return remaining;}async function setWatermark(env: AutumnEnv, orgID: string, ts: number): Promise<void> {diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 1b167c80..db425422 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -451,6 +451,7 @@ export async function browserUsageInternal(req: Request, env: AutumnEnv): PromisidempotencyKey: p.idempotency_key,});if (remaining !== null && remaining <= 0) await projectOrg(env, p.org_id);+ else if (remaining !== null && creditsInWarningBand(remaining)) await refreshWarning(env, p.org_id);return json({ ok: true, billed: true, org_id: p.org_id, browser_id: p.browser_id, remaining });} catch (err) {console.error(`browser-usage: track failed org=${p.org_id} browser=${p.browser_id}`, err);@@ -571,8 +572,10 @@ export async function agentRuntimeUsageInternal(idempotencyKey: p.idempotency_key,});if (remaining !== null && remaining <= 0) await projectOrg(env, p.org_id);- else if (workMinutes && remaining !== null && customer && minutesWarningCrossed(customer, remaining)) {- await projectOrg(env, p.org_id);+ else if (workMinutes && remaining !== null && customer && minutesInWarningBand(customer, remaining)) {+ const minutes = { ...customer.balances?.[WORK_MINUTES_FEATURE_ID], remaining };+ const after = { ...customer, balances: { ...customer.balances, [WORK_MINUTES_FEATURE_ID]: minutes } };+ await refreshWarning(env, p.org_id, after as AutumnCustomer);}if (workMinutes) {await recordWorkMinutes(env, p.org_id, customer, {@@ -756,15 +759,37 @@ export function billingWarning(return near[0]?.[0] ?? null;}-// minutesWarningCrossed: did this track move the minutes past a warning line-// (480 trial minutes, 80% of the month)? Only usage differs between the two-// reads, so the clock-driven reasons are left out of the comparison.-function minutesWarningCrossed(before: AutumnCustomer, minutesRemaining: number): boolean {- const minutes = { ...before.balances?.[WORK_MINUTES_FEATURE_ID], remaining: minutesRemaining };- const after: AutumnCustomer = { ...before, balances: { ...before.balances, [WORK_MINUTES_FEATURE_ID]: minutes } };- const noClock = { trialStartedAt: null, paymentPastDueAt: null };- const nowSec = Math.floor(Date.now() / 1000);- return billingWarning(before, noClock, nowSec) !== billingWarning(after, noClock, nowSec);+// Usage only moves a warning once the balance it spends is inside a warning+// line: the trial's last 120 minutes or the last 20% of the month's, and+// credits under $5 (the trial's $2 line is inside it). Above the lines the+// usage paths skip the check, so a usage event costs no extra reads.+function minutesInWarningBand(customer: AutumnCustomer, minutesRemaining: number): boolean {+ const plan = activeUsagePlan(customer);+ const line = plan === "base" ? TRIAL_WARN_MINUTES_LEFT : (PLAN_WORK_MINUTES[plan] ?? 0) * ALLOWANCE_WARN_FRACTION;+ return minutesRemaining <= line;+}++export function creditsInWarningBand(creditsRemaining: number): boolean {+ return creditsRemaining > 0 && creditsRemaining <= CREDITS_LOW;+}++// refreshWarning re-projects an org whose stored warning is no longer the one+// its balances and clock give, for the usage paths that otherwise project only+// at exhaustion. It compares against the stored warning with the real clock, so+// a trial_days warning that minutes or credits now outrank is replaced too.+export async function refreshWarning(env: AutumnEnv, orgID: string, customer?: AutumnCustomer | null): Promise<void> {+ const row = await env.OPENCOMPUTER_DB.prepare(+ "SELECT trial_started_at, payment_past_due_at, billing_warning FROM orgs WHERE id = ?1",+ )+ .bind(orgID)+ .first<{ trial_started_at: number | null; payment_past_due_at: number | null; billing_warning: string | null }>();+ if (!row) return;+ const cust = customer ?? (await getAutumnCustomer(env, orgID));+ if (!cust) return;+ const clock = { trialStartedAt: row.trial_started_at ?? null, paymentPastDueAt: row.payment_past_due_at ?? null };+ if (billingWarning(cust, clock, Math.floor(Date.now() / 1000)) !== (row.billing_warning ?? null)) {+ await projectOrg(env, orgID);+ }}// The trial age at which trial_days starts, for the billing clock.diff --git a/cloudflare-workers/api-edge/src/billing_clock.test.ts b/cloudflare-workers/api-edge/src/billing_clock.test.tsindex 2438308c..162f8d74 100644--- a/cloudflare-workers/api-edge/src/billing_clock.test.ts+++ b/cloudflare-workers/api-edge/src/billing_clock.test.ts@@ -24,7 +24,9 @@ describe("billing clock", () => {expect(await runBillingClock(env, 1_800_000_000_000)).toBe(2);// Least recently updated first, so orgs that stay unhalted can't fill every batch.expect(sql).toMatch(/ORDER BY updated_at\s+LIMIT/);- expect(bound).toEqual([1_800_000_000 - 7 * 86_400, 1_800_000_000 - 3 * 86_400, 50, 1_800_000_000 - 5 * 86_400]);+ expect(bound).toEqual([1_800_000_000 - 7 * 86_400, 1_800_000_000 - 3 * 86_400, 50, 1_800_000_000 - 5 * 86_400, 1_800_000_000 - 3_600]);+ // A trial warned about minutes or credits is re-checked hourly, so trial_days can replace it.+ expect(sql).toMatch(/billing_warning IS NULL OR \(billing_warning <> 'trial_days' AND updated_at <= \?5\)/);expect(project.mock.calls.map((c) => c[1])).toEqual(["org_a", "org_b"]);});});diff --git a/cloudflare-workers/api-edge/src/billing_clock.ts b/cloudflare-workers/api-edge/src/billing_clock.tsindex 0a085dc2..a9862b8b 100644--- a/cloudflare-workers/api-edge/src/billing_clock.ts+++ b/cloudflare-workers/api-edge/src/billing_clock.ts@@ -3,7 +3,8 @@// halts after its grace even when the org does nothing, so the */5 cron// re-projects the orgs whose clock has run out; projectOrg decides and halts.// It also re-projects a trial reaching 2 days left that is not yet warned, so-// the trial_days warning goes out on time rather than on the next activity.+// the trial_days warning goes out on time rather than on the next activity,+// and hourly one warned about minutes or credits, which the days can outrank.// A halted, warned or paid-up org no longer matches. One that matches but stays// unhalted (a credit-only signup before the Autumn trial plan exists) is// re-projected every tick, so the batch takes the least recently updated rows@@ -12,6 +13,10 @@import { type AutumnEnv, PAYMENT_GRACE_DAYS, TRIAL_DAYS, TRIAL_WARN_AFTER_SEC, projectOrg } from "./autumn_webhook";const DAY_SEC = 86_400;+// A trial in its last 2 days already warned about minutes or credits is+// re-projected at most this often, so trial_days replaces that warning once the+// days left are the smaller share, even while the org is idle.+const WARNED_TRIAL_RECHECK_SEC = 3_600;// Bounds one tick; the next tick continues.const MAX_ORGS_PER_RUN = 50;@@ -21,7 +26,8 @@ export async function runBillingClock(env: AutumnEnv, nowMs: number): Promise<nu`SELECT id FROM orgsWHERE billing_provider = 'autumn' AND is_halted = 0AND ((usage_plan = 'base' AND trial_started_at <= ?1) OR payment_past_due_at <= ?2- OR (usage_plan = 'base' AND trial_started_at <= ?4 AND billing_warning IS NULL))+ OR (usage_plan = 'base' AND trial_started_at <= ?4+ AND (billing_warning IS NULL OR (billing_warning <> 'trial_days' AND updated_at <= ?5))))ORDER BY updated_atLIMIT ?3`,)@@ -30,6 +36,7 @@ export async function runBillingClock(env: AutumnEnv, nowMs: number): Promise<nunowSec - PAYMENT_GRACE_DAYS * DAY_SEC,MAX_ORGS_PER_RUN,nowSec - TRIAL_WARN_AFTER_SEC,+ nowSec - WARNED_TRIAL_RECHECK_SEC,).all<{ id: string }>();let projected = 0;diff --git a/cloudflare-workers/api-edge/src/browser_usage.test.ts b/cloudflare-workers/api-edge/src/browser_usage.test.tsindex b7579755..8a390668 100644--- a/cloudflare-workers/api-edge/src/browser_usage.test.ts+++ b/cloudflare-workers/api-edge/src/browser_usage.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { browserUsageInternal, type AutumnEnv } from "./autumn_webhook";async function hmacHex(secret: string, data: string) {@@ -19,7 +19,7 @@ async function hmacHex(secret: string, data: string) {.join("");}-function env(): AutumnEnv {+function env(db: D1Database = {} as D1Database): AutumnEnv {return {AUTUMN_SECRET_KEY: "autumn-secret",AUTUMN_BASE_URL: "https://autumn.test/v1",@@ -27,11 +27,55 @@ function env(): AutumnEnv {EVENT_SECRET: "event-secret",BROWSER_USAGE_HMAC_SECRET: "browser-usage-secret",CF_ADMIN_SECRET: "admin-secret",- OPENCOMPUTER_DB: {} as D1Database,+ OPENCOMPUTER_DB: db,};}+async function postUsage(e: AutumnEnv) {+ const body = JSON.stringify({ org_id: "org_1", browser_id: "br_2", value: 60, idempotency_key: "browser_runtime:br_2" });+ const ts = String(Math.floor(Date.now() / 1000));+ const path = "/internal/browser-usage";+ const sig = await hmacHex("browser-usage-secret", `${ts}.${path}.${body}`);+ return browserUsageInternal(+ new Request(`https://api.test${path}`, { method: "POST", headers: { "X-Timestamp": ts, "X-Signature": sig }, body }),+ e,+ );+}+describe("browser usage billing", () => {+ afterEach(() => vi.restoreAllMocks());++ it("stores the credit warning when browser spend crosses it", async () => {+ const writes: string[] = [];+ const db = {+ prepare: (sql: string) => ({+ bind: () => ({+ first: async () =>+ sql.startsWith("SELECT trial_started_at") || sql.startsWith("SELECT is_halted")+ ? { is_halted: 0, usage_plan: "base", trial_started_at: null, payment_past_due_at: null, billing_warning: null }+ : null,+ run: async () => {+ writes.push(sql);+ return { meta: { changes: 1 } };+ },+ }),+ }),+ } as unknown as D1Database;+ const trial = Response.json({+ id: "org_1",+ subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],+ balances: { work_minutes: { remaining: 300 }, credits: { remaining: 1.5 } },+ });+ vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(Response.json({ balance: { remaining: 1.5 } }))+ .mockResolvedValueOnce(trial.clone())+ .mockResolvedValueOnce(trial)+ .mockResolvedValue(new Response(null, { status: 200 }));++ expect((await postUsage(env(db))).status).toBe(200);+ expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);+ });+it("tracks browser runtime into Autumn with the signed usage payload", async () => {const fetchMock = vi.spyOn(globalThis, "fetch")