Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

chore: await autumn calls and move to locks in new sdk (#3138)

Charlie Lamb1729e5877090
diff --git a/apps/api/package.json b/apps/api/package.json
index 7d5c4422a..106cce85b 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -98,7 +98,7 @@
"ajv-formats": "^3.0.1",
"amqplib": "^0.10.9",
"async-mutex": "^0.5.0",
- "autumn-js": "1.0.0-beta.6",
+ "autumn-js": "1.0.0-beta.10",
"axios": "^1.13.5",
"body-parser": "^1.20.3",
"bullmq": "^5.56.7",
diff --git a/apps/api/pnpm-lock.yaml b/apps/api/pnpm-lock.yaml
index 29868ef90..a2f7a8146 100644
--- a/apps/api/pnpm-lock.yaml
+++ b/apps/api/pnpm-lock.yaml
@@ -100,8 +100,8 @@ importers:
specifier: ^0.5.0
version: 0.5.0
autumn-js:
- specifier: 1.0.0-beta.6
- version: 1.0.0-beta.6([email protected])
+ specifier: 1.0.0-beta.10
+ version: 1.0.0-beta.10([email protected])
axios:
specifier: ^1.13.5
version: 1.13.5
@@ -3020,8 +3020,8 @@ packages:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
- resolution: {integrity: sha512-OUdPvoPQVhcg/pxYuUExgiE/P2OPSvwyiTt6r7q5cTz5QEW8WSaBprc8IsEaT7ChB3usYfdh15O9cnEdgXeUvw==}
+ resolution: {integrity: sha512-Gohg4VB9npGRik0MED35kdFYHzET5NVCsVeCwsaPg11Kw9eXbbP7TDqlamaANOE+TUZ1A6RDSvgMQBrsIDrnVw==}
peerDependencies:
better-auth: ^1.3.17
better-call: ^1.0.12
@@ -8578,7 +8578,7 @@ snapshots:
dependencies:
query-string: 9.3.1
rou3: 0.6.3
diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts
index cfe251aed..e48302b04 100644
--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts
+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts
@@ -15,6 +15,12 @@ import { jest } from "@jest/globals";
const mockTrack = jest
.fn<(args: any) => Promise<void>>()
.mockResolvedValue(undefined);
+const mockCheck = jest
+ .fn<(args: any) => Promise<any>>()
+ .mockResolvedValue({ allowed: true, customerId: "org-1", balance: null });
+const mockFinalize = jest
+ .fn<(args: any) => Promise<void>>()
+ .mockResolvedValue(undefined);
const mockGetOrCreate = jest
.fn<(args: any) => Promise<unknown>>()
.mockResolvedValue({ id: "org-1" });
@@ -24,6 +30,8 @@ const mockEntityCreate = jest.fn<(args: any) => Promise<unknown>>();
const mockAutumnClient = {
customers: { getOrCreate: mockGetOrCreate },
entities: { get: mockEntityGet, create: mockEntityCreate },
+ balances: { finalize: mockFinalize },
+ check: mockCheck,
track: mockTrack,
};
@@ -97,6 +105,12 @@ beforeEach(() => {
jest.clearAllMocks();
autumnClientRef = mockAutumnClient;
supabaseStubData = { data: { org_id: "org-1" }, error: null };
+ mockCheck.mockResolvedValue({
+ allowed: true,
+ customerId: "org-1",
+ balance: null,
+ });
+ mockFinalize.mockResolvedValue(undefined);
mockEntityGet.mockResolvedValue(makeEntity(0));
mockEntityCreate.mockResolvedValue({ id: "team-1" });
});
@@ -260,6 +274,71 @@ describe("ensureTrackingContext warm-cache short-circuit", () => {
});
});
+// ---------------------------------------------------------------------------
+// lockCredits
+// ---------------------------------------------------------------------------
+
+describe("lockCredits", () => {
+ it("returns null when autumnClient is null", async () => {
+ autumnClientRef = null;
+ const svc = makeService();
+ const result = await svc.lockCredits({ teamId: "team-1", value: 10 });
+ expect(result).toBeNull();
+ expect(mockCheck).not.toHaveBeenCalled();
+ });
+
+ it("returns null for preview teams", async () => {
+ const svc = makeService();
+ const result = await svc.lockCredits({
+ teamId: "preview_abc",
+ value: 10,
+ });
+ expect(result).toBeNull();
+ expect(mockCheck).not.toHaveBeenCalled();
+ });
+
+ it("returns the lockId on happy path", async () => {
+ const svc = makeService();
+
+ const result = await svc.lockCredits({
+ teamId: "team-1",
+ value: 42,
+ lockId: "lock-123",
+ properties: { source: "billTeam", endpoint: "extract" },
+ });
+
+ expect(result).toBe("lock-123");
+ expect(mockCheck).toHaveBeenCalledWith(
+ expect.objectContaining({
+ customerId: "org-1",
+ entityId: "team-1",
+ featureId: "CREDITS",
+ requiredBalance: 42,
+ properties: { source: "billTeam", endpoint: "extract" },
+ lock: expect.objectContaining({
+ enabled: true,
+ lockId: "lock-123",
+ }),
+ }),
+ );
+ });
+
+ it("returns null when Autumn denies the lock", async () => {
+ mockCheck.mockResolvedValue({
+ allowed: false,
+ customerId: "org-1",
+ balance: null,
+ });
+ const svc = makeService();
+ const result = await svc.lockCredits({
+ teamId: "team-1",
+ value: 10,
+ lockId: "lock-123",
+ });
+ expect(result).toBeNull();
+ });
+});
+
// ---------------------------------------------------------------------------
// reserveCredits
// ---------------------------------------------------------------------------
@@ -303,6 +382,35 @@ describe("reserveCredits", () => {
});
});
+// ---------------------------------------------------------------------------
+// finalizeCreditsLock
+// ---------------------------------------------------------------------------
+
+describe("finalizeCreditsLock", () => {
+ it("calls balances.finalize with confirm", async () => {
+ const svc = makeService();
+ await svc.finalizeCreditsLock({
+ lockId: "lock-123",
+ action: "confirm",
+ properties: { source: "test" },
+ });
+
+ expect(mockFinalize).toHaveBeenCalledWith({
+ lockId: "lock-123",
+ action: "confirm",
+ overrideValue: undefined,
+ properties: { source: "test" },
+ });
+ });
+
+ it("is a no-op when autumnClient is null", async () => {
+ autumnClientRef = null;
+ const svc = makeService();
+ await svc.finalizeCreditsLock({ lockId: "lock-123", action: "release" });
+ expect(mockFinalize).not.toHaveBeenCalled();
+ });
+});
+
// ---------------------------------------------------------------------------
// refundCredits
// ---------------------------------------------------------------------------
@@ -402,21 +510,21 @@ describe("isAutumnEnabled", () => {
});
});
-describe("experiment gate on reserveCredits", () => {
+describe("experiment gate on lockCredits", () => {
afterEach(() => {
(config as any).AUTUMN_EXPERIMENT = "true";
(config as any).AUTUMN_EXPERIMENT_PERCENT = 100;
});
- it("reserveCredits returns false when experiment is disabled", async () => {
+ it("lockCredits returns null when experiment is disabled", async () => {
(config as any).AUTUMN_EXPERIMENT = undefined;
const svc = makeService();
- const result = await svc.reserveCredits({ teamId: "team-1", value: 10 });
- expect(result).toBe(false);
- expect(mockTrack).not.toHaveBeenCalled();
+ const result = await svc.lockCredits({ teamId: "team-1", value: 10 });
+ expect(result).toBeNull();
+ expect(mockCheck).not.toHaveBeenCalled();
});
- it("reserveCredits returns false when org is outside the percent bucket", async () => {
+ it("lockCredits returns null when org is outside the percent bucket", async () => {
// Supabase returns org whose bucket (16) is >= percent (10).
supabaseStubData = {
data: { org_id: "a1b2c3d4-0000-0000-0000-000000000000" },
@@ -424,12 +532,12 @@ describe("experiment gate on reserveCredits", () => {
};
(config as any).AUTUMN_EXPERIMENT_PERCENT = 10;
const svc = makeService();
- const result = await svc.reserveCredits({ teamId: "team-1", value: 10 });
- expect(result).toBe(false);
- expect(mockTrack).not.toHaveBeenCalled();
+ const result = await svc.lockCredits({ teamId: "team-1", value: 10 });
+ expect(result).toBeNull();
+ expect(mockCheck).not.toHaveBeenCalled();
});
- it("reserveCredits succeeds when org is inside the percent bucket", async () => {
+ it("lockCredits succeeds when org is inside the percent bucket", async () => {
// Supabase returns org whose bucket (16) is < percent (50).
supabaseStubData = {
data: { org_id: "a1b2c3d4-0000-0000-0000-000000000000" },
@@ -437,9 +545,13 @@ describe("experiment gate on reserveCredits", () => {
};
(config as any).AUTUMN_EXPERIMENT_PERCENT = 50;
const svc = makeService();
- const result = await svc.reserveCredits({ teamId: "team-1", value: 10 });
- expect(result).toBe(true);
- expect(mockTrack).toHaveBeenCalled();
+ const result = await svc.lockCredits({
+ teamId: "team-1",
+ value: 10,
+ lockId: "lock-123",
+ });
+ expect(result).toBe("lock-123");
+ expect(mockCheck).toHaveBeenCalled();
});
it("refundCredits still works when experiment is disabled (guard is autumnReserved)", async () => {
diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.ts
index ca9671447..25227fa5f 100644
--- a/apps/api/src/services/autumn/autumn.service.ts
+++ b/apps/api/src/services/autumn/autumn.service.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from "crypto";
import { config } from "../../config";
import { logger } from "../../lib/logger";
import { supabase_rr_service } from "../supabase";
@@ -7,8 +8,10 @@ import type {
CreateEntityResult,
EnsureOrgProvisionedParams,
EnsureTeamProvisionedParams,
+ FinalizeCreditsLockParams,
GetEntityParams,
GetOrCreateCustomerParams,
+ LockCreditsParams,
TrackCreditsParams,
TrackParams,
} from "./types";
@@ -36,10 +39,10 @@ export function orgBucket(orgId: string): number {
* stable percent gate is also evaluated so the same org always gets the
* same answer.
*
- * Only checked at the top-level billing entry point (`reserveCredits`).
- * NOT checked by `refundCredits` (already guarded by `autumnReserved`) or
- * `ensureTeamProvisioned` (handled by firecrawl-web edge functions
- * independently).
+ * Only checked at the top-level billing entry points (`lockCredits` and the
+ * legacy direct-track `reserveCredits`).
+ * NOT checked by `finalizeCreditsLock`, `refundCredits`, or
+ * `ensureTeamProvisioned`.
*/
export function isAutumnEnabled(orgId?: string): boolean {
if (config.AUTUMN_EXPERIMENT !== "true") return false;
@@ -324,8 +327,105 @@ export class AutumnService {
}
/**
- * Records a credit usage event in Autumn at request time.
- * Returns true on success, false if Autumn is unavailable or an error occurs.
+ * Reserves a team's credits in Autumn without letting Autumn gate usage.
+ * Returns the lock ID on success, or null if no lock was acquired.
+ */
+ async lockCredits({
+ teamId,
+ value,
+ lockId,
+ expiresAt,
+ properties,
+ }: LockCreditsParams): Promise<string | null> {
+ if (!isAutumnEnabled() || !autumnClient || this.isPreviewTeam(teamId)) {
+ return null;
+ }
+
+ const resolvedLockId = lockId ?? `billing_${randomUUID()}`;
+
+ try {
+ const orgId = await this.resolveOrgId(teamId);
+ if (!isAutumnEnabled(orgId)) return null;
+
+ const customerId = await this.ensureTrackingContext(teamId);
+ const { allowed } = await autumnClient.check({
+ customerId,
+ entityId: teamId,
+ featureId: CREDITS_FEATURE_ID,
+ requiredBalance: value,
+ properties,
+ lock: {
+ enabled: true,
+ lockId: resolvedLockId,
+ expiresAt,
+ },
+ });
+
+ if (!allowed) {
+ logger.info("Autumn lockCredits denied", {
+ teamId,
+ value,
+ lockId: resolvedLockId,
+ });
+ return null;
+ }
+
+ logger.info("Autumn lockCredits succeeded", {
+ customerId,
+ entityId: teamId,
+ featureId: CREDITS_FEATURE_ID,
+ value,
+ lockId: resolvedLockId,
+ properties,
+ });
+ return resolvedLockId;
+ } catch (error) {
+ logger.warn("Autumn lockCredits failed", {
+ teamId,
+ value,
+ lockId: resolvedLockId,
+ error,
+ });
+ return null;
+ }
+ }
+
+ /**
+ * Finalizes a previously-acquired Autumn lock.
+ */
+ async finalizeCreditsLock({
+ lockId,
+ action,
+ overrideValue,
+ properties,
+ }: FinalizeCreditsLockParams): Promise<void> {
+ if (!autumnClient) return;
+
+ try {
+ await autumnClient.balances.finalize({
+ lockId,
+ action,
+ overrideValue,
+ properties,
+ });
+ logger.info("Autumn finalizeCreditsLock succeeded", {
+ lockId,
+ action,
+ overrideValue,
+ });
+ } catch (error) {
+ logger.warn("Autumn finalizeCreditsLock failed", {
+ lockId,
+ action,
+ overrideValue,
+ error,
+ });
+ }
+ }
+
+ /**
+ * Records a credit usage event directly in Autumn for flows that do not
+ * acquire a request-time lock. Returns true on success.
*
* The experiment gate is evaluated here β€” once per request β€” using a stable
* bucket derived from the org UUID so the same org always gets the same
diff --git a/apps/api/src/services/autumn/types.ts b/apps/api/src/services/autumn/types.ts
index 9b72346d5..ec05e5c5c 100644
--- a/apps/api/src/services/autumn/types.ts
+++ b/apps/api/src/services/autumn/types.ts
@@ -37,6 +37,21 @@ export type EnsureTeamProvisionedParams = {
name?: string | null;
};
+export type LockCreditsParams = {
+ teamId: string;
+ value: number;
+ lockId?: string;
+ expiresAt?: number;
+ properties?: Record<string, unknown>;
+};
+
+export type FinalizeCreditsLockParams = {
+ lockId: string;
+ action: "confirm" | "release";
+ overrideValue?: number;
+ properties?: Record<string, unknown>;
+};
+
export type TrackCreditsParams = {
teamId: string;
value: number;
diff --git a/apps/api/src/services/billing/__tests__/batch_billing.test.ts b/apps/api/src/services/billing/__tests__/batch_billing.test.ts
new file mode 100644
index 000000000..0b6e617e8
--- /dev/null
+++ b/apps/api/src/services/billing/__tests__/batch_billing.test.ts
@@ -0,0 +1,250 @@
+import { jest } from "@jest/globals";
+
+const captureException = jest.fn();
+jest.mock("@sentry/node", () => ({
+ captureException,
+}));
+
+const logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ child: jest.fn(() => logger),
+};
+jest.mock("../../../lib/logger", () => ({
+ logger,
+}));
+
+const withAuth = jest.fn((fn: any) => fn);
+jest.mock("../../../lib/withAuth", () => ({
+ withAuth,
+}));
+
+const reserveCredits = jest.fn<(args: any) => Promise<boolean>>();
+const finalizeCreditsLock = jest.fn<(args: any) => Promise<void>>();
+jest.mock("../../autumn/autumn.service", () => ({
+ autumnService: {
+ reserveCredits,
+ finalizeCreditsLock,
+ },
+}));
+
+const rpc = jest.fn<(name: string, args: any) => Promise<any>>();
+jest.mock("../../supabase", () => ({
+ supabase_service: {
+ rpc,
+ },
+}));
+
+const setCachedACUC = jest.fn();
+const setCachedACUCTeam = jest.fn();
+jest.mock("../../../controllers/auth", () => ({
+ setCachedACUC,
+ setCachedACUCTeam,
+}));
+
+let queue: string[] = [];
+const billedTeams = new Set<string>();
+const locks = new Map<string, string>();
+const redis = {
+ set: jest.fn(
+ async (
+ key: string,
+ value: string,
+ mode: string,
+ timeout: number,
+ nx: string,
+ ) => {
+ if (
+ key !== "billing_batch_lock" ||
+ value !== "1" ||
+ mode !== "PX" ||
+ timeout !== 30000 ||
+ nx !== "NX"
+ ) {
+ throw new Error("unexpected redis.set args");
+ }
+ if (locks.has(key)) return null;
+ locks.set(key, value);
+ return "OK";
+ },
+ ),
+ del: jest.fn(async (key: string) => {
+ if (key !== "billing_batch_lock") {
+ throw new Error("unexpected redis.del key");
+ }
+ return locks.delete(key) ? 1 : 0;
+ }),
+ lpop: jest.fn(async (key: string) => {
+ if (key !== "billing_batch") {
+ throw new Error("unexpected redis.lpop key");
+ }
+ return queue.shift() ?? null;
+ }),
+ llen: jest.fn(async (key: string) => {
+ if (key !== "billing_batch") {
+ throw new Error("unexpected redis.llen key");
+ }
+ return queue.length;
+ }),
+ rpush: jest.fn(async (key: string, value: string) => {
+ if (key !== "billing_batch") {
+ throw new Error("unexpected redis.rpush key");
+ }
+ queue.push(value);
+ return queue.length;
+ }),
+ sadd: jest.fn(async (key: string, teamId: string) => {
+ if (key !== "billed_teams") {
+ throw new Error("unexpected redis.sadd key");
+ }
+ billedTeams.add(teamId);
+ return 1;
+ }),
+};
+jest.mock("../../queue-service", () => ({
+ getRedisConnection: () => redis,
+}));
+
+import { processBillingBatch } from "../batch_billing";
+
+function makeOp(overrides: Record<string, unknown> = {}) {
+ return JSON.stringify({
+ team_id: "team-1",
+ subscription_id: "sub-1",
+ credits: 10,
+ billing: { endpoint: "extract" },
+ is_extract: false,
+ timestamp: "2026-03-13T00:00:00.000Z",
+ api_key_id: 123,
+ autumnLockId: null,
+ autumnProperties: {
+ source: "billTeam",
+ endpoint: "extract",
+ apiKeyId: 123,
+ },
+ ...overrides,
+ });
+}
+
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ queue = [];
+ billedTeams.clear();
+ locks.clear();
+ reserveCredits.mockResolvedValue(true);
+ finalizeCreditsLock.mockResolvedValue(undefined);
+ rpc.mockResolvedValue({ data: [], error: null });
+});
+
+describe("processBillingBatch", () => {
+ it("awaits lock confirmation before tracking unlocked credits", async () => {
+ const finalize = deferred<void>();
+ finalizeCreditsLock.mockReturnValueOnce(finalize.promise);
+ queue = [
+ makeOp({ credits: 7, autumnLockId: "lock-1" }),
+ makeOp({ credits: 3, autumnLockId: null }),
+ ];
+
+ const run = processBillingBatch();
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(finalizeCreditsLock).toHaveBeenCalledWith({
+ lockId: "lock-1",
+ action: "confirm",
+ properties: expect.objectContaining({
+ source: "billTeam",
+ apiKeyId: 123,
+ subscriptionId: "sub-1",
+ finalizeSource: "processBillingBatch",
+ }),
+ });
+ expect(reserveCredits).not.toHaveBeenCalled();
+
+ finalize.resolve();
+ await run;
+
+ expect(reserveCredits).toHaveBeenCalledWith({
+ teamId: "team-1",
+ value: 3,
+ properties: expect.objectContaining({
+ source: "processBillingBatch",
+ apiKeyId: 123,
+ subscriptionId: "sub-1",
+ }),
+ });
+ });
+
+ it("releases Autumn locks when billing returns success false", async () => {
+ queue = [makeOp({ autumnLockId: "lock-1" })];
+ rpc.mockResolvedValueOnce({ data: null, error: new Error("db failed") });
+
+ await processBillingBatch();
+
+ expect(finalizeCreditsLock).toHaveBeenCalledWith({
+ lockId: "lock-1",
+ action: "release",
+ properties: expect.objectContaining({
+ source: "billTeam",
+ finalizeSource: "processBillingBatch_failure",
+ }),
+ });
+ expect(reserveCredits).not.toHaveBeenCalled();
+ });
+
+ it("releases Autumn locks when billing throws", async () => {
+ queue = [makeOp({ autumnLockId: "lock-1" })];
+ rpc.mockRejectedValueOnce(new Error("rpc exploded"));
+
+ await processBillingBatch();
+
+ expect(finalizeCreditsLock).toHaveBeenCalledWith({
+ lockId: "lock-1",
+ action: "release",
+ properties: expect.objectContaining({
+ source: "billTeam",
+ finalizeSource: "processBillingBatch_exception",
+ }),
+ });
+ expect(captureException).toHaveBeenCalled();
+ });
+
+ it("treats undefined autumnLockId as unlocked for legacy queued ops", async () => {
+ queue = [makeOp({ autumnLockId: undefined })];
+
+ await processBillingBatch();
+
+ expect(finalizeCreditsLock).not.toHaveBeenCalled();
+ expect(reserveCredits).toHaveBeenCalledWith({
+ teamId: "team-1",
+ value: 10,
+ properties: expect.objectContaining({
+ source: "processBillingBatch",
+ }),
+ });
+ });
+
+ it("survives unexpected synchronous finalizeAutumnLocks failures", async () => {
+ queue = [makeOp({ autumnLockId: "lock-1" })];
+ finalizeCreditsLock.mockImplementationOnce(() => {
+ throw new Error("sync finalize failure");
+ });
+
+ await processBillingBatch();
+
+ expect(logger.warn).toHaveBeenCalledWith(
+ "Autumn finalizeAutumnLocks failed unexpectedly",
+ expect.objectContaining({ team_id: "team-1", action: "confirm" }),
+ );
+ });
+});
diff --git a/apps/api/src/services/billing/batch_billing.ts b/apps/api/src/services/billing/batch_billing.ts
index 04b859208..b7f734a0f 100644
--- a/apps/api/src/services/billing/batch_billing.ts
+++ b/apps/api/src/services/billing/batch_billing.ts
@@ -30,8 +30,9 @@ interface BillingOperation {
is_extract: boolean;
timestamp: string;
api_key_id: number | null;
- /** True if credits were pre-reserved in Autumn at request time via reserveCredits(). */
- autumnReserved: boolean;
+ /** Autumn lock ID acquired at request time, if any. */
+ autumnLockId: string | null;
+ autumnProperties?: Record<string, unknown>;
}
// Grouped billing operations for batch processing
@@ -64,12 +65,62 @@ async function releaseLock() {
logger.info("πŸ”“ Released billing batch processing lock");
}
+async function finalizeAutumnLocks(
+ group: GroupedBillingOperation,
+ action: "confirm" | "release",
+ source: string,
+) {
+ const lockedOperations = group.operations.filter(
+ (
+ op,
+ ): op is BillingOperation & {
+ autumnLockId: string;
+ } => typeof op.autumnLockId === "string",
+ );
+
+ if (lockedOperations.length === 0) return;
+
+ try {
+ const results = await Promise.allSettled(
+ lockedOperations.map(op =>
+ autumnService.finalizeCreditsLock({
+ lockId: op.autumnLockId,
+ action,
+ properties: {
+ ...op.autumnProperties,
+ subscriptionId: op.subscription_id,
+ finalizeSource: source,
+ },
+ }),
+ ),
+ );
+
+ const rejectedCount = results.filter(
+ result => result.status === "rejected",
+ ).length;
+ if (rejectedCount > 0) {
+ logger.warn("Autumn finalizeCreditsLock rejected unexpectedly", {
+ team_id: group.team_id,
+ action,
+ rejectedCount,
+ });
+ }
+ } catch (error) {
+ logger.warn("Autumn finalizeAutumnLocks failed unexpectedly", {
+ team_id: group.team_id,
+ action,
+ operation_count: lockedOperations.length,
+ error,
+ });
+ }
+}
+
/**
* Dequeues pending billing operations from Redis, groups them by team, and
* commits each group to Supabase via the `bill_team_6` RPC.
*
- * For groups where credits were pre-reserved in Autumn (`autumnReserved: true`),
- * a refund is issued on failure; nothing is done on success. For unreserved
+ * For groups where credits were locked in Autumn (`autumnLockId != null`),
+ * the lock is confirmed on success and released on failure. For unlocked
* groups (legacy / BullMQ path), Autumn is updated post-commit.
*/
export async function processBillingBatch() {
@@ -127,7 +178,7 @@ export async function processBillingBatch() {
}
// Process each group of operations
- for (const [key, group] of groupedOperations.entries()) {
+ for (const [, group] of groupedOperations.entries()) {
logger.info(
`πŸ”„ Billing team ${group.team_id} for ${group.total_credits} credits`,
{
@@ -146,12 +197,9 @@ export async function processBillingBatch() {
continue;
}
- // Compute per-group credit split before billing so the catch block can
- // issue a refund even if supaBillTeam throws.
- const reservedCredits = group.operations
- .filter(op => op.autumnReserved)
+ const unreservedCredits = group.operations
+ .filter(op => op.autumnLockId == null)
.reduce((sum, op) => sum + op.credits, 0);
- const unreservedCredits = group.total_credits - reservedCredits;
try {
// Execute the actual billing
@@ -176,19 +224,11 @@ export async function processBillingBatch() {
credits: group.total_credits,
},
);
- // Refund only the credits that were actually reserved in Autumn.
- if (reservedCredits > 0) {
- void autumnService.refundCredits({
- teamId: group.team_id,
- value: reservedCredits,
- properties: {
- source: "processBillingBatch_failure",
- ...toAutumnBillingProperties(group.billing),
- apiKeyId: group.api_key_id,
- subscriptionId: group.subscription_id,
- },
- });
- }
+ await finalizeAutumnLocks(
+ group,
+ "release",
+ "processBillingBatch_failure",
+ );
continue;
}
@@ -196,10 +236,12 @@ export async function processBillingBatch() {
`βœ… Successfully billed team ${group.team_id} for ${group.total_credits} credits`,
);
- // Track only unreserved credits post-commit; reserved credits were
- // already recorded in Autumn at request time.
+ await finalizeAutumnLocks(group, "confirm", "processBillingBatch");
+
+ // Track only unlocked credits post-commit; locked credits are
+ // confirmed above and should not be re-tracked.
if (unreservedCredits > 0) {
- void autumnService.reserveCredits({
+ await autumnService.reserveCredits({
teamId: group.team_id,
value: unreservedCredits,
properties: {
@@ -222,19 +264,11 @@ export async function processBillingBatch() {
credits: group.total_credits,
},
});
- // Billing threw before committing β€” refund any Autumn-reserved credits.
- if (reservedCredits > 0) {
- void autumnService.refundCredits({
- teamId: group.team_id,
- value: reservedCredits,
- properties: {
- source: "processBillingBatch_exception",
- ...toAutumnBillingProperties(group.billing),
- apiKeyId: group.api_key_id,
- subscriptionId: group.subscription_id,
- },
- });
- }
+ await finalizeAutumnLocks(
+ group,
+ "release",
+ "processBillingBatch_exception",
+ );
}
}
@@ -271,9 +305,9 @@ export function startBillingBatchProcessing() {
/**
* Enqueues a billing operation for async batch processing.
*
- * Pass `autumnReserved: true` if credits were already reserved in Autumn via
- * `autumnService.reserveCredits()` β€” the batch processor will refund on
- * `bill_team_6` failure and skip re-tracking on success.
+ * Pass `autumnLockId` when credits were locked in Autumn via
+ * `autumnService.lockCredits()` β€” the batch processor will release on
+ * `bill_team_6` failure and confirm on success.
*/
export async function queueBillingOperation(
team_id: string,
@@ -282,7 +316,8 @@ export async function queueBillingOperation(
api_key_id: number | null,
billing: BillingMetadata,
is_extract: boolean = false,
- autumnReserved: boolean = false,
+ autumnLockId: string | null = null,
+ autumnProperties?: Record<string, unknown>,
) {
// Skip queuing for preview teams
if (team_id === "preview" || team_id.startsWith("preview_")) {
@@ -307,7 +342,8 @@ export async function queueBillingOperation(
is_extract,
timestamp: new Date().toISOString(),
api_key_id,
- autumnReserved,
+ autumnLockId,
+ autumnProperties,
};
// Add operation to Redis list
diff --git a/apps/api/src/services/billing/credit_billing.ts b/apps/api/src/services/billing/credit_billing.ts
index 7bcc547e8..52d63bea4 100644
--- a/apps/api/src/services/billing/credit_billing.ts
+++ b/apps/api/src/services/billing/credit_billing.ts
@@ -9,10 +9,7 @@ import { autoCharge } from "./auto_charge";
import { getValue, setValue } from "../redis";
import { queueBillingOperation } from "./batch_billing";
import { autumnService } from "../autumn/autumn.service";
-import {
- toAutumnBillingProperties,
- type BillingMetadata,
-} from "./types";
+import { toAutumnBillingProperties, type BillingMetadata } from "./types";
import type { Logger } from "winston";
/**
@@ -35,16 +32,17 @@ export async function billTeam(
billing: BillingMetadata,
logger: Logger | undefined,
) => {
- // Reserve in Autumn at request time; await so autumnReserved is accurate.
- // billTeam is fire-and-forget at call sites, so this doesn't block responses.
- const autumnReserved = await autumnService.reserveCredits({
+ const autumnProperties = {
+ source: "billTeam",
+ ...toAutumnBillingProperties(billing),
+ apiKeyId: api_key_id,
+ };
+ // Acquire an Autumn lock opportunistically, but never gate usage on it.
+ // billTeam is fire-and-forget at call sites, so this does not block responses.
+ const autumnLockId = await autumnService.lockCredits({
teamId: team_id,
value: credits,
- properties: {
- source: "billTeam",
- ...toAutumnBillingProperties(billing),
- apiKeyId: api_key_id,
- },
+ properties: autumnProperties,
});
return queueBillingOperation(
team_id,
@@ -53,7 +51,8 @@ export async function billTeam(
api_key_id,
billing,
false,
- autumnReserved,
+ autumnLockId,
+ autumnProperties,
);
},
{ success: true, message: "No DB, bypassed." },