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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>
Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
This commit is contained in:
authored and GitHub committed 2026-11-21 15:52:17 -07:00
1 parent 0dbf84bc3e
commit 414090bb36
7 files changed
+151 -14

No files matched your search

@@ -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;
@@ -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 };
@@ -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({
@@ -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);
}
}
}
@@ -4414,7 +4414,7 @@ describe('MeteringService', () => {
expect(
await target.reserveCredits(actor, 1000, { within: headroom }),
).toBeNull();
).toBe('stale');
expect(await target.getOutstandingHolds(actor)).toBe(0);
});
@@ -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<CreditHold | null>;
): Promise<CreditHold | 'stale' | null>;
async reserveCredits(
actor: Actor,
amount: number,
opts: { ttlMs?: number; within?: UsageHeadroom } = {},
): Promise<CreditHold | null> {
): Promise<CreditHold | 'stale' | null> {
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(
+2 -2
View File
@@ -376,13 +376,13 @@ export function withAiCostFactor(
actor: Actor,
amount: number,
opts?: { ttlMs?: number; within?: UsageHeadroom },
): Promise<CreditHold | null> => {
): Promise<CreditHold | 'stale' | null> => {
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.