From 414090bb3675baaa24b4298cb0f069ffe6e589ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filip=20Kujund=C5=BEi=C4=87?= <51266541+404oops@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:52:17 +0100 Subject: [PATCH] fix(ai): bill Mistral OCR for a page count a document can have (#4734) * fix(ai): bill Mistral OCR for a page count a document can have Co-Authored-By: Claude Fable 5.2 * fix(ai): retry a chat credit hold apart from lost headroom when the balance changed A conditional hold refused because the balance changed since it was read is now reported as 'stale', separately from one that no longer fits. The chat gate reads the balance again for it, up to five times with a short randomized wait, without spending the tries a lost headroom gets, and refuses with a plain 429 rather than credits_reserved if it never holds still. --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: Daniel Salazar --- .../ChatCompletionDriver.metering.test.ts | 64 +++++++++++++++++++ .../interfaces/chat/ChatCompletionDriver.ts | 36 +++++++++++ .../ai/interfaces/ocr/OCRDriver.test.ts | 25 ++++++++ .../mistral/ocr/MistralOcrProvider.ts | 21 ++++-- .../services/metering/MeteringService.test.ts | 2 +- .../services/metering/MeteringService.ts | 13 ++-- src/backend/util/aiCostFactor.ts | 4 +- 7 files changed, 151 insertions(+), 14 deletions(-) diff --git a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.metering.test.ts b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.metering.test.ts index a549e08a0..f783d75f2 100644 --- a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.metering.test.ts +++ b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.metering.test.ts @@ -455,6 +455,70 @@ describe('ChatCompletionDriver credit gate against real metering', () => { completeSpy.mockRestore(); }); + describe('a balance that changes while the gate reads it', () => { + const okCompletion = { + message: { + role: 'assistant', + content: [{ type: 'text', text: 'ok' }], + }, + usage: { input_tokens: 1, output_tokens: 1 }, + finish_reason: 'stop', + }; + const complete = (actor: never) => + withTestActor( + () => + driver.complete({ + model: 'priced', + messages: [{ role: 'user', content: 'hello' }], + }), + actor, + ); + + it('is read again, beyond the tries a lost headroom gets', async () => { + const actor = freeUser() as never; + const completeSpy = vi + .spyOn(FakeChatProvider.prototype, 'complete') + .mockResolvedValue(okCompletion as never); + const reserve = vi.spyOn(server.stores.creditHold, 'reserve'); + reserve + .mockResolvedValueOnce({ outcome: 'stale' }) + .mockResolvedValueOnce({ outcome: 'stale' }) + .mockResolvedValueOnce({ outcome: 'stale' }); + + await complete(actor); + + expect(reserve).toHaveBeenCalledTimes(4); + expect(completeSpy).toHaveBeenCalledTimes(1); + }); + + it('refuses without naming holds once it never holds still', async () => { + const actor = freeUser() as never; + const completeSpy = vi.spyOn( + FakeChatProvider.prototype, + 'complete', + ); + const reserve = vi + .spyOn(server.stores.creditHold, 'reserve') + .mockResolvedValue({ outcome: 'stale' }); + + const error = await complete(actor).then( + () => null, + (e) => e, + ); + + expect(error).toMatchObject({ + statusCode: 429, + legacyCode: 'too_many_requests', + }); + expect(error.code).not.toBe('credits_reserved'); + expect(reserve).toHaveBeenCalledTimes(5); + expect(completeSpy).not.toHaveBeenCalled(); + expect( + await server.services.metering.getOutstandingHolds(actor), + ).toBe(0); + }); + }); + it('caps output to the balance left, so one call cannot run away with the month', async () => { const actor = freeUser() as never; const metering = server.services.metering; diff --git a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts index 9d44365a7..d116a808f 100644 --- a/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts +++ b/src/backend/drivers/ai/interfaces/chat/ChatCompletionDriver.ts @@ -207,6 +207,14 @@ const isModerationRefusal = (e: unknown): boolean => /** Times the credit gate sizes a request again after losing the headroom. */ const CREDIT_GATE_ATTEMPTS = 3; +/** + * Times the credit gate reads a balance that keeps changing under it, and the + * upper bound of the randomized wait before each new read, times the attempt. + * The same policy as a fixed-amount reservation's. + */ +const CREDIT_GATE_STALE_ATTEMPTS = 5; +const CREDIT_GATE_STALE_BACKOFF_MS = 20; + /** * The refusal for a request its funds can't cover. When what's missing is only * held by the account's own requests still in flight, waiting is the remedy, @@ -1837,6 +1845,7 @@ export class ChatCompletionDriver extends PuterDriver { pricingTime: Date; }, attempt = 1, + staleAttempt = 1, ): Promise<{ hold: CreditHold; fundsCap?: number; @@ -1993,6 +2002,32 @@ export class ChatCompletionDriver extends PuterDriver { Math.max(worstCaseCost, minimumCredits), { within: headroom }, ); + if (hold === 'stale') { + // The balance changed since it was read, which says nothing about + // what is held: counted apart from lost headroom, and read again + // after a short wait. + if (staleAttempt >= CREDIT_GATE_STALE_ATTEMPTS) { + throw new HttpError( + 429, + 'The account balance is changing too quickly to admit this request. Retry shortly.', + { legacyCode: 'too_many_requests' }, + ); + } + await new Promise((resolve) => + setTimeout( + resolve, + Math.random() * CREDIT_GATE_STALE_BACKOFF_MS * staleAttempt, + ), + ); + return this.#applyCreditGate( + actor, + model, + args, + estimates, + attempt, + staleAttempt + 1, + ); + } if (!hold) { if (attempt >= CREDIT_GATE_ATTEMPTS) throw fundsRefusal(true); return this.#applyCreditGate( @@ -2001,6 +2036,7 @@ export class ChatCompletionDriver extends PuterDriver { args, estimates, attempt + 1, + staleAttempt, ); } return { hold, fundsCap, costFactor, promptTokenEstimate }; diff --git a/src/backend/drivers/ai/interfaces/ocr/OCRDriver.test.ts b/src/backend/drivers/ai/interfaces/ocr/OCRDriver.test.ts index 5606289ca..2cb87097c 100644 --- a/src/backend/drivers/ai/interfaces/ocr/OCRDriver.test.ts +++ b/src/backend/drivers/ai/interfaces/ocr/OCRDriver.test.ts @@ -846,6 +846,31 @@ describe('OCRDriver.recognize (mistral)', () => { expect(mistralOcrProcessMock).not.toHaveBeenCalled(); }); + it.each([ + ['a count past the page limit', 5000, 1000], + ['a count that is not a number', '7', 2], + ['a negative count', -3, 2], + ])('bills %s as pages a document can have', async (_, reported, billed) => { + const { actor } = await makeUser(); + mistralOcrProcessMock.mockResolvedValueOnce({ + model: 'mistral-ocr-latest', + pages: [{ index: 0, markdown: 'a' }, { index: 1, markdown: 'b' }], + usageInfo: { pagesProcessed: reported }, + }); + + await withActor(actor, () => + driver.recognize({ + source: dataUrl(Buffer.from('imgdata'), 'image/png'), + provider: 'mistral', + }), + ); + + const [, , pages] = incrementUsageSpy.mock.calls.find( + ([, type]) => type === 'mistral-ocr:mistral-ocr-4-1:page', + )!; + expect(pages).toBe(billed); + }); + it('packages an image as an image_url chunk with a base64 data URL', async () => { const { actor } = await makeUser(); mistralOcrProcessMock.mockResolvedValueOnce({ diff --git a/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts b/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts index d837e6f36..81d7a2c3f 100644 --- a/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts +++ b/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts @@ -271,9 +271,19 @@ export class MistralOcrProvider implements IOcrProvider { annotations: boolean, ) { try { - const pagesProcessed = - response?.usageInfo?.pagesProcessed ?? - (Array.isArray(response?.pages) ? response.pages.length : 1); + const reported = response?.usageInfo?.pagesProcessed; + // The count Mistral reports, when it is one, and never more pages + // than a document may have. + const pagesProcessed = Math.min( + typeof reported === 'number' && + Number.isSafeInteger(reported) && + reported > 0 + ? reported + : Array.isArray(response?.pages) + ? response.pages.length + : 1, + OCR_MAX_PAGES[model.provider], + ); this.metering.incrementUsage( actor, model.pageUsageType, @@ -288,8 +298,9 @@ export class MistralOcrProvider implements IOcrProvider { OCR_COSTS[model.annotationUsageType] * pagesProcessed, ); } - } catch { - // Non-critical. + } catch (error) { + // The text is returned either way; an unrecorded charge is logged. + console.error('[mistral-ocr] recording usage failed:', error); } } } diff --git a/src/backend/services/metering/MeteringService.test.ts b/src/backend/services/metering/MeteringService.test.ts index 56e8d86be..abfbcbb0c 100644 --- a/src/backend/services/metering/MeteringService.test.ts +++ b/src/backend/services/metering/MeteringService.test.ts @@ -4414,7 +4414,7 @@ describe('MeteringService', () => { expect( await target.reserveCredits(actor, 1000, { within: headroom }), - ).toBeNull(); + ).toBe('stale'); expect(await target.getOutstandingHolds(actor)).toBe(0); }); diff --git a/src/backend/services/metering/MeteringService.ts b/src/backend/services/metering/MeteringService.ts index dc002dad7..205e2d30d 100644 --- a/src/backend/services/metering/MeteringService.ts +++ b/src/backend/services/metering/MeteringService.ts @@ -1602,9 +1602,9 @@ export class MeteringService extends PuterService { * prevent. * * With `within`, the headroom the caller sized the operation from, the hold - * is taken only if it still fits: null when another operation took the - * room, or the balance changed, since that read. The caller reads the - * headroom again and sizes the operation anew. + * is taken only if it still fits: null when another operation took the room + * since that read, `'stale'` when the balance changed. Either way the + * caller reads the headroom again and sizes the operation anew. */ async reserveCredits( actor: Actor, @@ -1615,12 +1615,12 @@ export class MeteringService extends PuterService { actor: Actor, amount: number, opts: { ttlMs?: number; within: UsageHeadroom }, - ): Promise; + ): Promise; async reserveCredits( actor: Actor, amount: number, opts: { ttlMs?: number; within?: UsageHeadroom } = {}, - ): Promise { + ): Promise { const userId = actor?.user?.uuid; if (!userId || isSystemActor(actor) || !(amount > 0)) { return NO_CREDIT_HOLD; @@ -1643,7 +1643,8 @@ export class MeteringService extends PuterService { if (result.outcome === 'accepted') { return this.#holdHandle(userId, result.member, opts.ttlMs); } - return result.outcome === 'unavailable' ? NO_CREDIT_HOLD : null; + if (result.outcome === 'unavailable') return NO_CREDIT_HOLD; + return result.outcome === 'stale' ? 'stale' : null; } const member = await this.stores.creditHold.take( diff --git a/src/backend/util/aiCostFactor.ts b/src/backend/util/aiCostFactor.ts index 4ce29b4eb..b0e3cebff 100644 --- a/src/backend/util/aiCostFactor.ts +++ b/src/backend/util/aiCostFactor.ts @@ -376,13 +376,13 @@ export function withAiCostFactor( actor: Actor, amount: number, opts?: { ttlMs?: number; within?: UsageHeadroom }, - ): Promise => { + ): Promise => { const hold = await metering.reserveCredits( actor, amount, opts as { within: UsageHeadroom }, ); - return hold && outlastingWrites(hold); + return hold && hold !== 'stale' ? outlastingWrites(hold) : hold; }; // For a cost the caller has already factored.