diff --git a/src/backend/util/aiCostFactor.test.ts b/src/backend/util/aiCostFactor.test.ts index 16ed2bc72..93709fba8 100644 --- a/src/backend/util/aiCostFactor.test.ts +++ b/src/backend/util/aiCostFactor.test.ts @@ -154,6 +154,28 @@ describe('AI cost factor', () => { expect(result.total).toBe(1040 + 2080); }); + it('records nothing for a count that is not a positive number', async () => { + const recorded = vi.spyOn(metering, 'batchIncrementUsages'); + + await scoped.utilRecordUsageObject( + { + input_tokens: 100, + output_tokens: '5', + cached_tokens: -1, + reasoning_tokens: NaN, + audio_tokens: 1e308, + } as unknown as Record, + actor, + 'claude:sonnet', + ); + + const amounts = recorded.mock.calls[0]![1].map( + ({ usageAmount }) => usageAmount, + ); + recorded.mockRestore(); + expect(amounts).toEqual([100, 0, 0, 0, 0]); + }); + it('records a usage object as it stood when recording began', async () => { listen(2); const recorded = vi.spyOn(metering, 'batchIncrementUsages'); diff --git a/src/backend/util/aiCostFactor.ts b/src/backend/util/aiCostFactor.ts index afcf5fdd4..60803174f 100644 --- a/src/backend/util/aiCostFactor.ts +++ b/src/backend/util/aiCostFactor.ts @@ -154,8 +154,7 @@ const PENDING_WRITES_KEY = 'aiPendingUsageWrites'; const trackWrite = (write: Promise): Promise => { if (!Context.current()) return write; let pending = Context.get(PENDING_WRITES_KEY) as - | Set> - | undefined; + Set> | undefined; if (!pending) { pending = new Set(); Context.set(PENDING_WRITES_KEY, pending); @@ -180,8 +179,7 @@ const outlastingWrites = (hold: CreditHold): CreditHold => { ...hold, release: async () => { const pending = Context.get(PENDING_WRITES_KEY) as - | Set> - | undefined; + Set> | undefined; if (!pending?.size) return hold.release(); void Promise.all([...pending]) .then(() => hold.release()) @@ -296,11 +294,23 @@ export function withAiCostFactor( }; const utilRecordUsageObject = >( - trackedUsageObject: T, + reportedUsageObject: T, actor: Actor, modelPrefix: string, costsOverrides?: Partial>, ): Promise => { + // Counts come from the provider's answer. One that isn't a positive + // number records nothing, instead of the ledger's one-unit fallback. + const trackedUsageObject = Object.fromEntries( + Object.entries(reportedUsageObject).map(([key, amount]) => [ + key, + typeof amount === 'number' && + amount > 0 && + amount <= Number.MAX_SAFE_INTEGER + ? amount + : 0, + ]), + ) as T; noteRequestCosts( Object.entries(trackedUsageObject).map(([key, usageAmount]) => ({ usageType: key, @@ -316,8 +326,7 @@ export function withAiCostFactor( modelPrefix, costsOverrides, ); - // Recorded after the lookup; callers may add keys to theirs meanwhile. - const usageObject = { ...trackedUsageObject }; + const usageObject = trackedUsageObject; const scaleOverrides = (factor: number) => factor === 1 ? costsOverrides