Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix(api): retry unanswered firebill tracks durably instead of dropping them (#5412)
Rakshith Ramprakash4c1e0d2aa15d
diff --git a/apps/api/src/controllers/v2/feedback/alexandria-refund.test.ts b/apps/api/src/controllers/v2/feedback/alexandria-refund.test.tsindex 21804dcef..66ccfba5c 100644--- a/apps/api/src/controllers/v2/feedback/alexandria-refund.test.ts+++ b/apps/api/src/controllers/v2/feedback/alexandria-refund.test.ts@@ -119,6 +119,7 @@ it("reserves the refund under a per-team lock before billing, then reports it",orgId: "org-1",value: 1,idempotencyKey: "fc:refund:alexandria-feedback:feedback-1",+ durableRetry: false,featureId: "CREDITS",properties: {source: "feedback",diff --git a/apps/api/src/controllers/v2/feedback/alexandria-refund.ts b/apps/api/src/controllers/v2/feedback/alexandria-refund.tsindex e8e18607b..6e8094a87 100644--- a/apps/api/src/controllers/v2/feedback/alexandria-refund.ts+++ b/apps/api/src/controllers/v2/feedback/alexandria-refund.ts@@ -212,6 +212,9 @@ export async function refundAlexandriaFeedback(params: {orgId,value: REFUND_CREDITS,idempotencyKey: `fc:refund:alexandria-feedback:${feedbackId}`,+ // An unconfirmed refund frees its cap reservation below, so a late+ // durable retry landing would credit outside both daily caps.+ durableRetry: false,featureId: CREDITS_FEATURE_ID,properties: {source: "feedback",diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 735aedcb6..a6d667fdf 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -9,6 +9,7 @@ import {getDeepResearchQueue,getBillingQueue,getPrecrawlQueue,+ getFirebillTrackRetryQueue,} from "./services/queue-service";import { v0Router } from "./routes/v0";import { startNodeRuntimeMetrics } from "./lib/node-runtime-metrics";@@ -107,6 +108,7 @@ const bullBoardQueues = [new BullMQAdapter(getDeepResearchQueue()),new BullMQAdapter(getBillingQueue()),new BullMQAdapter(getPrecrawlQueue()),+ new BullMQAdapter(getFirebillTrackRetryQueue()),// SIEM audit delivery runs on RabbitMQ; inspect it in the broker's// management UI, not here.];diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.tsindex e7217ccce..b40817650 100644--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts@@ -100,6 +100,15 @@ vi.mock("../client", () => ({},}));+// An unanswered firebill track is handed to a Redis-backed retry queue; no+// Redis here, so the hand-off is accepted and dropped.+const { retryQueueAdd } = vi.hoisted(() => ({+ retryQueueAdd: vi.fn(async (_name: string, _data: unknown) => undefined),+}));+vi.mock("../../queue-service", () => ({+ getFirebillTrackRetryQueue: () => ({ add: retryQueueAdd }),+}));+vi.mock("../../../db/connection", () => ({get dbRr() {return makeDbStub(state.gatewayStubRow, state.gatewayStubThrows);@@ -1170,6 +1179,33 @@ describe("firebill routing", () => {});});+ it.each([+ ["trackCredits", 4, "track"],+ ["refundCredits", 4, "refund"],+ ] as const)(+ "%s carries durableRetry through to firebill's retry hand-off",+ async (method, value, name) => {+ state.configRef = firebillConfig();+ mockFetch.mockRejectedValue(new Error("timeout"));+ const svc = makeService();+ const call = (durableRetry?: boolean) =>+ svc[method]({+ teamId: "team-1",+ orgId: "org-1",+ value,+ idempotencyKey: `fc:${name}:test:1`,+ ...(durableRetry === undefined ? {} : { durableRetry }),+ });++ await expect(call(false)).resolves.toBe(false);+ expect(retryQueueAdd).not.toHaveBeenCalled();++ await expect(call()).resolves.toBe(false);+ expect(retryQueueAdd).toHaveBeenCalledTimes(1);+ expect(retryQueueAdd.mock.calls[0]![0]).toBe(name);+ },+ );+// The gate, not the charge. Before this branch existed checkCredits asked// Autumn about the ghost's balance alone β and a gateway ghost is designed to// spend credits it does not have, so it 402'd exactly the requests thediff --git a/apps/api/src/services/autumn/__tests__/firebill.test.ts b/apps/api/src/services/autumn/__tests__/firebill.test.tsindex 5c40cec3e..3bd37e0b0 100644--- a/apps/api/src/services/autumn/__tests__/firebill.test.ts+++ b/apps/api/src/services/autumn/__tests__/firebill.test.ts@@ -1,9 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Job } from "bullmq";import {+ FIREBILL_DURABLE_RETRY_ATTEMPTS,firebillCheck,firebillFinalize,firebillLock,firebillTrack,+ processFirebillTrackRetry,shouldRouteToFirebill,} from "../firebill";import { logger } from "../../../lib/logger";@@ -11,8 +14,11 @@ import {firebillCheckTotal,firebillFailureCauseTotal,firebillRetryTotal,+ firebillTrackRetryExhaustedValueTotal,+ firebillTrackRetryTotal,firebillTrackTotal,} from "../metrics";+import type { FirebillTrackRetryJobData } from "../../queue-service";const { configState } = vi.hoisted(() => ({configState: {@@ -25,6 +31,13 @@ const { configState } = vi.hoisted(() => ({}));vi.mock("../../../config", () => ({ config: configState }));++const { retryQueueAdd } = vi.hoisted(() => ({+ retryQueueAdd: vi.fn(),+}));+vi.mock("../../queue-service", () => ({+ getFirebillTrackRetryQueue: () => ({ add: retryQueueAdd }),+}));vi.mock("../../../lib/logger", () => ({logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },}));@@ -72,6 +85,10 @@ beforeEach(() => {firebillRetryTotal.reset();firebillCheckTotal.reset();firebillFailureCauseTotal.reset();+ firebillTrackRetryTotal.reset();+ firebillTrackRetryExhaustedValueTotal.reset();+ retryQueueAdd.mockReset();+ retryQueueAdd.mockResolvedValue(undefined);vi.mocked(logger.info).mockClear();vi.mocked(logger.warn).mockClear();vi.mocked(logger.error).mockClear();@@ -542,6 +559,263 @@ describe("firebillTrack", () => {});});+const retryOutcomes = async () =>+ Object.fromEntries(+ (await firebillTrackRetryTotal.get()).values.map(v => [+ `${v.labels.operation}/${v.labels.outcome}`,+ v.value,+ ]),+ );++/** A retry job as the queue hands it to the worker on a given attempt. */+const retryJob = (+ data: FirebillTrackRetryJobData,+ attemptsMade: number,+): Job<FirebillTrackRetryJobData> =>+ ({+ data,+ attemptsMade,+ opts: { attempts: FIREBILL_DURABLE_RETRY_ATTEMPTS },+ }) as unknown as Job<FirebillTrackRetryJobData>;++/** Logger calls as [message, context], which the mocked signature hides. */+const logCalls = (method: "info" | "warn" | "error") =>+ vi.mocked(logger[method]).mock.calls as unknown as [+ string,+ Record<string, unknown>,+ ][];++describe("firebillTrack durable retry", () => {+ it("hands an unanswered track to the retry queue as the identical event", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => ambiguous()),+ );++ await expect(firebillTrack(params)).resolves.toBe(false);++ expect(retryQueueAdd).toHaveBeenCalledTimes(1);+ const [name, data, opts] = retryQueueAdd.mock.calls[0];+ expect(name).toBe("track");+ expect(data).toEqual(params);+ expect(opts).toMatchObject({+ jobId: "firebill|fc%3Atrack%3Ascrape%3Ajob-1",+ attempts: FIREBILL_DURABLE_RETRY_ATTEMPTS,+ backoff: { type: "exponential" },+ });+ // BullMQ waits backoff * 2^(n-1) after the nth failure: 30s to the first+ // re-send, then doubling, which puts the last one about two hours out.+ const gaps = [opts.delay];+ for (let n = 1; n < FIREBILL_DURABLE_RETRY_ATTEMPTS; n++) {+ gaps.push(opts.backoff.delay * 2 ** (n - 1));+ }+ expect(gaps.slice(0, 3)).toEqual([30_000, 60_000, 120_000]);+ const total = gaps.reduce((a, b) => a + b, 0);+ expect(total).toBeGreaterThan(2 * 60 * 60 * 1000);+ expect(total).toBeLessThan(3 * 60 * 60 * 1000);+ expect(await retryOutcomes()).toEqual({ "track/enqueued": 1 });+ // The alerted counter still says what the caller saw.+ expect(await trackOutcomes()).toEqual({ ambiguous: 1 });+ expect(logCalls("error")[0][1]).toMatchObject({+ idempotencyKey: params.idempotencyKey,+ handedToRetry: true,+ });+ });++ it("enqueues a timed-out refund under the minted key it already sent", async () => {+ const fetchMock = vi.fn().mockRejectedValue(wrapped(abortError()));+ vi.stubGlobal("fetch", fetchMock);++ await firebillTrack({ ...params, value: -3, idempotencyKey: undefined });++ const sentKey = JSON.parse(fetchMock.mock.calls[0][1].body).idempotency_key;+ const [name, data] = retryQueueAdd.mock.calls[0];+ expect(name).toBe("refund");+ expect(data).toMatchObject({ value: -3, idempotencyKey: sentKey });+ expect(await retryOutcomes()).toEqual({ "refund/enqueued": 1 });+ });++ it("does not enqueue an explicit refusal or an accepted event", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => refused()),+ );+ await firebillTrack(params);++ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => ok()),+ );+ await firebillTrack(params);++ expect(retryQueueAdd).not.toHaveBeenCalled();+ });++ it("keeps an unanswered event out of the retry when the caller opts out", async () => {+ const fetchMock = vi.fn().mockImplementation(async () => ambiguous());+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ firebillTrack({ ...params, value: -1, durableRetry: false }),+ ).resolves.toBe(false);++ expect(retryQueueAdd).not.toHaveBeenCalled();+ expect(await retryOutcomes()).toEqual({});+ expect(logCalls("error")[0][1]).toMatchObject({ handedToRetry: false });+ // The flag is ours; firebill never sees it.+ expect(+ Object.hasOwn(+ JSON.parse(fetchMock.mock.calls[0][1].body),+ "durableRetry",+ ),+ ).toBe(false);+ });++ it("gives distinct keys distinct job ids even when they differ only in delimiters", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => ambiguous()),+ );++ await firebillTrack({ ...params, idempotencyKey: "a:b" });+ await firebillTrack({ ...params, idempotencyKey: "a|b" });++ const [first, second] = retryQueueAdd.mock.calls.map(c => c[2].jobId);+ expect(first).not.toBe(second);+ });++ it("counts an enqueue that does not confirm in time as unknown, not lost", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => ambiguous()),+ );+ retryQueueAdd.mockImplementationOnce(() => new Promise(() => {}));++ await expect(firebillTrack(params)).resolves.toBe(false);++ expect(await retryOutcomes()).toEqual({ "track/enqueue_timeout": 1 });+ expect(logCalls("error").map(c => c[0])).toContain(+ "firebill durable retry enqueue timed out; the retry may or may not have been queued",+ );+ });++ it("logs and counts an enqueue that fails, still reporting false", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => ambiguous()),+ );+ retryQueueAdd.mockRejectedValueOnce(new Error("redis down"));++ await expect(firebillTrack(params)).resolves.toBe(false);++ expect(await retryOutcomes()).toEqual({ "track/enqueue_failed": 1 });+ const messages = vi.mocked(logger.error).mock.calls.map(c => c[0]);+ expect(messages).toContain(+ "firebill durable retry could not be enqueued; the event will not be billed unless replayed",+ );+ expect(logCalls("error").at(-1)?.[1]).toMatchObject({+ handedToRetry: false,+ });+ });++ it("re-sends with the same key, customer, entity, feature and value", async () => {+ const fetchMock = vi.fn().mockImplementation(async () => ok());+ vi.stubGlobal("fetch", fetchMock);+ const event = { ...params, externalRequestId: "partner-op-42" };++ await processFirebillTrackRetry(retryJob(event, 0));++ expect(fetchMock.mock.calls[0][0]).toBe("https://firebill.test/v1/track");+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({+ customer_id: "org-1",+ entity_id: "team-1",+ feature_id: "CREDITS",+ value: 3,+ properties: {},+ idempotency_key: params.idempotencyKey,+ external_request_id: "partner-op-42",+ });+ expect(await retryOutcomes()).toEqual({+ "track/retried": 1,+ "track/settled": 1,+ });+ });++ it("sends a refund retry to /v1/refund with the value made positive", async () => {+ const fetchMock = vi.fn().mockImplementation(async () => ok());+ vi.stubGlobal("fetch", fetchMock);++ await processFirebillTrackRetry(retryJob({ ...params, value: -3 }, 2));++ expect(fetchMock.mock.calls[0][0]).toBe("https://firebill.test/v1/refund");+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({+ value: 3,+ idempotency_key: params.idempotencyKey,+ });+ });++ it("throws on a failed attempt so the queue backs off and tries again", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => ambiguous()),+ );++ await expect(+ processFirebillTrackRetry(retryJob(params, 0)),+ ).rejects.toThrow(/retry 1\/8 failed/);++ expect(await retryOutcomes()).toEqual({ "track/retried": 1 });+ const messages = vi.mocked(logger.error).mock.calls.map(c => c[0]);+ expect(messages).not.toContain(+ "firebill durable retry exhausted; the event may not have been billed",+ );+ });++ it("keeps retrying a refusal, since an earlier attempt may have landed", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => refused()),+ );++ await expect(+ processFirebillTrackRetry(retryJob(params, 3)),+ ).rejects.toThrow();+ expect(await retryOutcomes()).toEqual({ "track/retried": 1 });+ });++ it("logs the key and amount and counts the value when the last attempt fails", async () => {+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(wrapped(abortError())));++ await expect(+ processFirebillTrackRetry(+ retryJob(params, FIREBILL_DURABLE_RETRY_ATTEMPTS - 1),+ ),+ ).rejects.toThrow(/retry 8\/8 failed/);++ expect(await retryOutcomes()).toEqual({+ "track/retried": 1,+ "track/exhausted": 1,+ });+ const [value] = (await firebillTrackRetryExhaustedValueTotal.get()).values;+ expect(value).toMatchObject({+ value: 3,+ labels: { operation: "track", feature: "CREDITS" },+ });+ const exhausted = logCalls("error").find(+ c =>+ c[0] ===+ "firebill durable retry exhausted; the event may not have been billed",+ );+ expect(exhausted?.[1]).toMatchObject({+ idempotencyKey: params.idempotencyKey,+ value: 3,+ attempt: 8,+ attempts: 8,+ cause: "timeout",+ });+ });+});+describe("firebillCheck", () => {const checkParams = {customerId: "org-1",diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex e53ec5732..873c61352 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -331,6 +331,7 @@ export class AutumnService {properties,idempotencyKey,externalRequestId,+ durableRetry,}: TrackParams,routed: boolean,): Promise<boolean> {@@ -348,6 +349,7 @@ export class AutumnService {properties,idempotencyKey,externalRequestId,+ durableRetry,});}@@ -834,6 +836,7 @@ export class AutumnService {featureId = CREDITS_FEATURE_ID,idempotencyKey,externalRequestId,+ durableRetry,orgId,}: TrackCreditsParams): Promise<boolean> {if (!autumnClient) return false;@@ -853,6 +856,7 @@ export class AutumnService {properties,idempotencyKey,externalRequestId,+ durableRetry,},routed,);@@ -928,6 +932,7 @@ export class AutumnService {featureId = CREDITS_FEATURE_ID,idempotencyKey,externalRequestId,+ durableRetry,orgId,}: TrackCreditsParams): Promise<boolean> {if (!autumnClient) return false;@@ -947,6 +952,7 @@ export class AutumnService {properties: { ...properties, source: "autumn_refund" },idempotencyKey,externalRequestId,+ durableRetry,},routed,);diff --git a/apps/api/src/services/autumn/firebill.ts b/apps/api/src/services/autumn/firebill.tsindex 95451de55..06fe07915 100644--- a/apps/api/src/services/autumn/firebill.ts+++ b/apps/api/src/services/autumn/firebill.ts@@ -1,13 +1,20 @@import { randomUUID } from "crypto";+import type { Job } from "bullmq";import { z } from "zod";import { config } from "../../config";import { logger } from "../../lib/logger";import { sampled } from "../../lib/rollout";+import {+ getFirebillTrackRetryQueue,+ type FirebillTrackRetryJobData,+} from "../queue-service";import type { LockDeniedReason, TrackParams } from "./types";import {firebillCheckTotal,firebillFailureCauseTotal,firebillRetryTotal,+ firebillTrackRetryExhaustedValueTotal,+ firebillTrackRetryTotal,firebillTrackTotal,} from "./metrics";@@ -54,6 +61,19 @@ const FIREBILL_GATED_LOCK_TIMEOUT_MS = 10000;const FIREBILL_ATTEMPTS = 2;const FIREBILL_RETRY_DELAY_MS = 150;+// The durable retry behind an unanswered track: first re-send after 30s, then+// 60s, 120s and doubling, so the eighth and last lands about two hours after+// the caller gave up. Long enough to outlast a firebill pod being rescheduled+// off a lost node.+export const FIREBILL_DURABLE_RETRY_ATTEMPTS = 8;+const FIREBILL_DURABLE_RETRY_FIRST_DELAY_MS = 30_000;+// BullMQ's exponential backoff waits base * 2^(n-1) after the nth failure, so+// a 60s base is what makes the second gap double the first.+const FIREBILL_DURABLE_RETRY_BACKOFF_MS = 60_000;+// The queue's Redis client retries a command forever while disconnected, so an+// enqueue is bounded here: a Redis outage must not hang the billing call.+const FIREBILL_DURABLE_RETRY_ENQUEUE_TIMEOUT_MS = 2000;+/*** Why a firebill call did not produce a usable answer, at a cardinality safe to* put on a counter. **`timeout` and `connection` are ours, not firebill's**:@@ -325,18 +345,21 @@ function firebillUrl(path: string): string {* itself, so the absolute value is sent either way.** Returns true when firebill accepted the event, mirroring the boolean- * contract of the direct Autumn track path. A `false` means firebill never- * took it: nothing is retrying, and the usage goes unbilled.+ * contract of the direct Autumn track path. A `false` means firebill did not+ * confirm it. An unanswered event is then handed to a durable retry that+ * re-sends the identical event under the same idempotency key, so it is billed+ * once whether or not the lost attempt landed; an explicit refusal is not.*/export async function firebillTrack(params: TrackParams): Promise<boolean> {- const operation = params.value < 0 ? "refund" : "track";+ const operation = trackOperation(params.value);const path = `/v1/${operation}`;// Both attempts must be the same event. Without a caller key firebill mints// one per request, so a retry after an accepted-but-lost first attempt would// be a second charge; minting here instead keeps one identity per call while// separate calls stay distinct, exactly as before.+ const { durableRetry = true, ...event } = params;const attempted = {- ...params,+ ...event,idempotencyKey: params.idempotencyKey ?? randomUUID(),};@@ -369,6 +392,10 @@ export async function firebillTrack(params: TrackParams): Promise<boolean> {// counter rather than a throw: billing must not fail the customer's request,// and a log alone is too quiet to alert on.const outcome = last.reason === "not_success" ? "refused" : "ambiguous";+ const handedToRetry =+ outcome === "ambiguous" &&+ durableRetry &&+ (await enqueueFirebillTrackRetry(attempted));logger.error(outcome === "refused"? "firebill refused a usage event; it will not be billed"@@ -382,6 +409,7 @@ export async function firebillTrack(params: TrackParams): Promise<boolean> {callerSuppliedKey: params.idempotencyKey !== undefined,path,attempts: FIREBILL_ATTEMPTS,+ handedToRetry,reason: last.reason,cause: last.cause,...(last.status !== undefined ? { status: last.status } : {}),@@ -397,6 +425,128 @@ export async function firebillTrack(params: TrackParams): Promise<boolean> {return false;}+function trackOperation(value: number): "track" | "refund" {+ return value < 0 ? "refund" : "track";+}++/**+ * Hands an unanswered event to the durable retry queue. The job carries the+ * whole event, key included, so every re-send is byte-for-byte the event the+ * caller sent. Keyed by the idempotency key, so the same event enqueued twice+ * (a stalled job re-running its charge) is one job.+ */+async function enqueueFirebillTrackRetry(+ event: FirebillTrackRetryJobData,+): Promise<boolean> {+ const operation = trackOperation(event.value);+ const context = {+ customerId: event.customerId,+ entityId: event.entityId,+ featureId: event.featureId,+ value: event.value,+ idempotencyKey: event.idempotencyKey,+ };+ const timedOut = Symbol("enqueue timed out");+ let timer: NodeJS.Timeout | undefined;+ try {+ const added = await Promise.race([+ getFirebillTrackRetryQueue().add(operation, event, {+ jobId: `firebill|${encodeURIComponent(event.idempotencyKey)}`,+ delay: FIREBILL_DURABLE_RETRY_FIRST_DELAY_MS,+ attempts: FIREBILL_DURABLE_RETRY_ATTEMPTS,+ backoff: {+ type: "exponential",+ delay: FIREBILL_DURABLE_RETRY_BACKOFF_MS,+ },+ }),+ new Promise<typeof timedOut>(resolve => {+ timer = setTimeout(+ () => resolve(timedOut),+ FIREBILL_DURABLE_RETRY_ENQUEUE_TIMEOUT_MS,+ );+ }),+ ]);+ // The add is still in flight and may land: unknown, not lost.+ if (added === timedOut) {+ logger.error(+ "firebill durable retry enqueue timed out; the retry may or may not have been queued",+ { ...context, timeoutMs: FIREBILL_DURABLE_RETRY_ENQUEUE_TIMEOUT_MS },+ );+ firebillTrackRetryTotal.labels(operation, "enqueue_timeout").inc();+ return false;+ }+ firebillTrackRetryTotal.labels(operation, "enqueued").inc();+ return true;+ } catch (error) {+ logger.error(+ "firebill durable retry could not be enqueued; the event will not be billed unless replayed",+ { ...context, error },+ );+ firebillTrackRetryTotal.labels(operation, "enqueue_failed").inc();+ return false;+ } finally {+ clearTimeout(timer);+ }+}++/**+ * One durable re-send of an event firebill never confirmed. Throws on any+ * answer but accepted so the queue schedules the next attempt with backoff;+ * the last failed attempt logs and counts the event as exhausted first.+ *+ * Any non-accepted answer is retried, a refusal included: an earlier attempt+ * may still have landed, and the shared key makes a late duplicate a no-op.+ */+export async function processFirebillTrackRetry(+ job: Job<FirebillTrackRetryJobData>,+): Promise<void> {+ const event = job.data;+ const operation = trackOperation(event.value);+ const attempt = job.attemptsMade + 1;+ const attempts = job.opts.attempts ?? 1;++ firebillTrackRetryTotal.labels(operation, "retried").inc();+ const result = await firebillAttempt(`/v1/${operation}`, event);++ const context = {+ customerId: event.customerId,+ entityId: event.entityId,+ featureId: event.featureId,+ value: event.value,+ idempotencyKey: event.idempotencyKey,+ attempt,+ attempts,+ };++ if (result.ok) {+ firebillTrackRetryTotal.labels(operation, "settled").inc();+ logger.info("firebill accepted a usage event on durable retry", context);+ return;+ }++ const failure = {+ ...context,+ reason: result.reason,+ cause: result.cause,+ ...(result.status !== undefined ? { status: result.status } : {}),+ };+ if (attempt >= attempts) {+ firebillTrackRetryTotal.labels(operation, "exhausted").inc();+ firebillTrackRetryExhaustedValueTotal+ .labels(operation, event.featureId)+ .inc(Math.abs(event.value));+ logger.error(+ "firebill durable retry exhausted; the event may not have been billed",+ failure,+ );+ } else {+ logger.warn("firebill durable retry attempt failed; will retry", failure);+ }+ throw new Error(+ `firebill ${operation} retry ${attempt}/${attempts} failed: ${result.cause}`,+ );+}+type AttemptResult =| { ok: true }| {diff --git a/apps/api/src/services/autumn/metrics.ts b/apps/api/src/services/autumn/metrics.tsindex 37244df6b..65ec216f1 100644--- a/apps/api/src/services/autumn/metrics.ts+++ b/apps/api/src/services/autumn/metrics.ts@@ -59,6 +59,37 @@ export const firebillFailureCauseTotal = new Counter({labelNames: ["operation", "cause"] as const,});+/**+ * The durable retry behind a track or refund that firebill never confirmed.+ * Counted where each step happens: the `enqueue*` outcomes by the+ * caller that gave up, `retried`, `settled` and `exhausted` by the+ * retry worker.+ *+ * - `enqueued` β handed to the retry queue instead of being dropped.+ * - `enqueue_failed` β the queue rejected the hand-off; the event is+ * unbilled unless someone replays it from the log line.+ * - `enqueue_timeout` β the hand-off did not confirm in time and may still+ * land; check the queue for the key before treating it as lost.+ * - `retried` β one re-send under the same idempotency key.+ * - `settled` β firebill accepted a re-send.+ * - `exhausted` β every attempt failed; see the exhausted value counter+ * and the "firebill durable retry exhausted" log for the key and amount.+ */+export const firebillTrackRetryTotal = new Counter({+ name: "firecrawl_firebill_track_retry_total",+ help: "Durable retries of usage events firebill did not confirm",+ // operation: track|refund+ // outcome: enqueued|enqueue_failed|enqueue_timeout|retried|settled|exhausted+ labelNames: ["operation", "outcome"] as const,+});++/** The amount, made positive, behind each exhausted durable retry. */+export const firebillTrackRetryExhaustedValueTotal = new Counter({+ name: "firecrawl_firebill_track_retry_exhausted_value_total",+ help: "Usage value whose durable firebill retry was exhausted",+ labelNames: ["operation", "feature"] as const,+});+/** Retries of a firebill call that answered `false` or threw. */export const firebillRetryTotal = new Counter({name: "firecrawl_firebill_retry_total",diff --git a/apps/api/src/services/autumn/types.ts b/apps/api/src/services/autumn/types.tsindex 0d709bfc2..759f3cad6 100644--- a/apps/api/src/services/autumn/types.ts+++ b/apps/api/src/services/autumn/types.ts@@ -48,6 +48,13 @@ export type TrackParams = {* like a crawl id (every page shares it: collision = underbilling).*/idempotencyKey?: string;+ /**+ * firebill route only. `false` keeps an unanswered event out of the durable+ * retry, for a caller that treats `false` as "did not happen" and releases+ * something on it: a late retry landing would bill what it already undid.+ * Defaults to retrying.+ */+ durableRetry?: boolean;};export type EnsureOrgProvisionedParams = {@@ -131,6 +138,8 @@ export type TrackCreditsParams = {idempotencyKey?: string;/** See TrackParams.externalRequestId. */externalRequestId?: string | null;+ /** See TrackParams.durableRetry. */+ durableRetry?: boolean;/*** The team's org β the Autumn customer this usage bills against. The service* never looks it up: callers hold it already (a request's ACUC, a job'sdiff --git a/apps/api/src/services/queue-service.ts b/apps/api/src/services/queue-service.tsindex 1c3e56c49..722f19d3e 100644--- a/apps/api/src/services/queue-service.ts+++ b/apps/api/src/services/queue-service.ts@@ -5,6 +5,7 @@ import IORedis from "ioredis";import type { DeepResearchServiceOptions } from "../lib/deep-research/deep-research-service";import { addExtractJob, ExtractJobData } from "./extract-queue";import type { BillTeamJobData } from "./billing/types";+import type { TrackParams } from "./autumn/types";let loggingQueue: Queue;let indexQueue: Queue;@@ -12,6 +13,7 @@ let deepResearchQueue: Queue;let generateLlmsTxtQueue: Queue;let billingQueue: Queue<BillTeamJobData>;let precrawlQueue: Queue;+let firebillTrackRetryQueue: Queue<FirebillTrackRetryJobData>;let redisConnection: IORedis;export function getRedisConnection(): IORedis {@@ -30,6 +32,12 @@ const generateLlmsTxtQueueName = "{generateLlmsTxtQueue}";const deepResearchQueueName = "{deepResearchQueue}";const billingQueueName = "{billingQueue}";export const precrawlQueueName = "{precrawlQueue}";+const firebillTrackRetryQueueName = "{firebillTrackRetryQueue}";++/** A usage event firebill never confirmed, re-sent as the identical event. */+export type FirebillTrackRetryJobData = TrackParams & {+ idempotencyKey: string;+};export async function addExtractJobToQueue(extractId: string,@@ -92,6 +100,28 @@ export function getBillingQueue() {return billingQueue;}+export function getFirebillTrackRetryQueue() {+ if (!firebillTrackRetryQueue) {+ firebillTrackRetryQueue = new Queue<FirebillTrackRetryJobData>(+ firebillTrackRetryQueueName,+ {+ connection: getRedisConnection(),+ defaultJobOptions: {+ removeOnComplete: {+ age: 60 * 60, // 1 hour+ },+ // Exhausted retries stay inspectable for a week: each one is an+ // event that may not have been billed.+ removeOnFail: {+ age: 7 * 24 * 60 * 60, // 7 days+ },+ },+ },+ );+ }+ return firebillTrackRetryQueue;+}+export function getPrecrawlQueue() {if (!precrawlQueue) {precrawlQueue = new Queue(precrawlQueueName, {diff --git a/apps/api/src/services/worker/nuq-reconciler-worker.ts b/apps/api/src/services/worker/nuq-reconciler-worker.tsindex fadd39cf8..00c895e11 100644--- a/apps/api/src/services/worker/nuq-reconciler-worker.ts+++ b/apps/api/src/services/worker/nuq-reconciler-worker.ts@@ -7,6 +7,15 @@ import { repairCrawlJobDoneMarkers } from "../../lib/crawl-redis";import { Counter, register } from "prom-client";import Express from "express";import { startNodeRuntimeMetrics } from "../../lib/node-runtime-metrics";+import { Worker } from "bullmq";+import {+ getFirebillTrackRetryQueue,+ getRedisConnection,+} from "../queue-service";+import {+ firebillConfigured,+ processFirebillTrackRetry,+} from "../autumn/firebill";const RECONCILER_INTERVAL_MS = 60 * 1000;@@ -61,11 +70,27 @@ const reconcilerJobsRecoveredTotal = new Counter({},);+ // Re-sends usage events firebill never confirmed. Jobs live in Redis, so+ // one consumer is enough: if this pod goes, its delayed retries wait for+ // the next one rather than being lost.+ const firebillTrackRetryWorker = firebillConfigured()+ ? new Worker(getFirebillTrackRetryQueue().name, processFirebillTrackRetry, {+ connection: getRedisConnection(),+ concurrency: 16,+ maxStalledCount: 10,+ })+ : undefined;+ firebillTrackRetryWorker?.on("error", error => {+ _logger.error("firebill track retry worker error", { error });+ });+async function shutdown() {if (isShuttingDown) return;isShuttingDown = true;_logger.info("NuQ reconciler worker shutting down");+ await firebillTrackRetryWorker?.close();+while (reconcilerInFlight) {_logger.info("Waiting for in-flight reconciliation to complete...");await new Promise(resolve => setTimeout(resolve, 1000));