Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(billing): label unresolvable apiKeyIds as Unknown in historical usage (#3727)

firecrawl-spring[bot]4283e8d34f00
diff --git a/apps/api/src/services/autumn/__tests__/usage.test.ts b/apps/api/src/services/autumn/__tests__/usage.test.ts
index 95e1d1f08..d5077811e 100644
--- a/apps/api/src/services/autumn/__tests__/usage.test.ts
+++ b/apps/api/src/services/autumn/__tests__/usage.test.ts
@@ -912,6 +912,33 @@ describe("getTeamHistoricalUsageByApiKey", () => {
);
});
+ it("labels unresolvable apiKeyIds as 'Unknown' instead of echoing raw values", async () => {
+ apiKeysData = [];
+
+ mockAggregate.mockResolvedValue({
+ list: [
+ {
+ period: Date.parse("2026-04-15T00:00:00.000Z"),
+ grouped_values: {
+ CREDITS: {
+ ba9045fffbd34fc8aabc2597df6ba044: 11,
+ "99999999": 7,
+ },
+ },
+ },
+ ],
+ });
+
+ await expect(getTeamHistoricalUsageByApiKey("team-1")).resolves.toEqual([
+ {
+ startDate: "2026-04-01T00:00:00.000Z",
+ endDate: null,
+ apiKey: "Unknown",
+ creditsUsed: 18,
+ },
+ ]);
+ });
+
it("uses the next calendar month as endDate for grouped data when a month has zero usage", async () => {
apiKeysData = [{ id: 101, name: "Default" }];
diff --git a/apps/api/src/services/autumn/usage.ts b/apps/api/src/services/autumn/usage.ts
index 82c1252a9..681a1b5aa 100644
--- a/apps/api/src/services/autumn/usage.ts
+++ b/apps/api/src/services/autumn/usage.ts
@@ -41,34 +41,36 @@ async function lookupOrgId(teamId: string): Promise<string> {
}
/**
- * Maps numeric API key IDs to their display names from the api_keys table.
- * Returns a map of id → name. Unknown IDs are mapped to their string representation.
+ * Maps API key identifiers from Autumn events to their display names.
+ *
+ * Autumn returns whatever value was sent as `properties.apiKeyId`. Current
+ * code sends the numeric `api_keys.id`, but the 90-day aggregation window can
+ * still include legacy events tagged with opaque non-numeric values. Anything
+ * we can't resolve is labeled "Unknown" so the response never surfaces raw
+ * identifiers.
*/
async function lookupApiKeyNames(
apiKeyIds: string[],
): Promise<Record<string, string>> {
const numericIds = apiKeyIds
.map(id => Number(id))
- .filter(n => !isNaN(n) && n > 0);
+ .filter(n => Number.isInteger(n) && n > 0);
const nameMap: Record<string, string> = {};
if (numericIds.length > 0) {
- const data = await dbRr
+ const rows = await dbRr
.select({ id: schema.api_keys.id, name: schema.api_keys.name })
.from(schema.api_keys)
.where(inArray(schema.api_keys.id, numericIds));
- for (const row of data) {
- nameMap[String(row.id)] = row.name ?? String(row.id);
+ for (const row of rows) {
+ nameMap[String(row.id)] = row.name ?? "Unknown";
}
}
- // Fall back to raw ID string for any keys not found
for (const id of apiKeyIds) {
- if (!nameMap[id]) {
- nameMap[id] = id;
- }
+ if (!nameMap[id]) nameMap[id] = "Unknown";
}
return nameMap;
@@ -157,13 +159,22 @@ async function aggregateHistoricalPeriodsByApiKeyMonth(
if (!monthTotals) continue;
- for (const [apiKeyId, creditsUsed] of [...monthTotals.entries()].sort(
- ([a], [b]) => a.localeCompare(b),
+ // Collapse rows whose IDs resolve to the same display name (e.g. multiple
+ // unresolved IDs all show as "Unknown") so the response has one row per
+ // name per month.
+ const byName = new Map<string, number>();
+ for (const [apiKeyId, creditsUsed] of monthTotals) {
+ const name = nameMap[apiKeyId];
+ byName.set(name, (byName.get(name) ?? 0) + creditsUsed);
+ }
+
+ for (const [apiKey, creditsUsed] of [...byName.entries()].sort(([a], [b]) =>
+ a.localeCompare(b),
)) {
results.push({
startDate,
endDate,
- apiKey: nameMap[apiKeyId],
+ apiKey,
creditsUsed,
});
}