From 3d300fae5c5ced63373a8f3ae9b3ff97d8a3680b 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:12 +0100 Subject: [PATCH] fix(ai): answer an unreadable 2xx JSON body from Mistral with a 502 (#4720) Co-authored-by: Claude Fable 5.2 --- .../mistral/chat/MistralAiProvider.ts | 6 +- .../ai/providers/mistral/inputError.ts | 6 ++ .../mistral/ocr/MistralOcrProvider.ts | 12 ++- .../ai/shared/jsonCheckedFetch.test.ts | 93 +++++++++++++++++++ .../drivers/ai/shared/jsonCheckedFetch.ts | 54 +++++++++++ .../drivers/util/upstreamErrors.test.ts | 27 ++++++ src/backend/drivers/util/upstreamErrors.ts | 30 +++++- src/docs/src/rate-limits-and-quotas.md | 3 + 8 files changed, 223 insertions(+), 8 deletions(-) create mode 100644 src/backend/drivers/ai/shared/jsonCheckedFetch.test.ts create mode 100644 src/backend/drivers/ai/shared/jsonCheckedFetch.ts diff --git a/src/backend/drivers/ai/providers/mistral/chat/MistralAiProvider.ts b/src/backend/drivers/ai/providers/mistral/chat/MistralAiProvider.ts index 9997eb765..be926414c 100644 --- a/src/backend/drivers/ai/providers/mistral/chat/MistralAiProvider.ts +++ b/src/backend/drivers/ai/providers/mistral/chat/MistralAiProvider.ts @@ -36,6 +36,7 @@ import { unsupportedMediaTextPart, } from '../../../interfaces/chat/utils/mediaParts.js'; import * as OpenAIUtil from '../../../protocols/openaiCompatible/OpenAIUtil.js'; +import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js'; import { isMistralInputError } from '../inputError.js'; import { MISTRAL_MODELS } from './models.js'; import { shouldPresentAsOpenAI } from '../../../interfaces/chat/utils/normalizeToOpenAI.js'; @@ -102,8 +103,7 @@ const MISTRAL_FINISH_REASON_MAP: Record = { // totals include cache hits, which must be removed before billing input. const coerceMistralUsage = (usage: UsageInfo) => { const details = usage.additionalProperties?.prompt_tokens_details as - | { cached_tokens?: number } - | undefined; + { cached_tokens?: number } | undefined; const cachedTokens = details?.cached_tokens ?? 0; return { prompt_tokens: (usage.promptTokens ?? 0) - cachedTokens, @@ -119,7 +119,7 @@ export class MistralAIProvider implements IChatProvider { #meteringService: MeteringService; constructor(config: { apiKey: string }, meteringService: MeteringService) { - const httpClient = new HTTPClient(); + const httpClient = new HTTPClient({ fetcher: jsonCheckedFetch }); // The SDK strips service_tier during body serialization. httpClient.addHook('beforeRequest', async (request) => { const tier = request.headers.get('x-puter-service-tier'); diff --git a/src/backend/drivers/ai/providers/mistral/inputError.ts b/src/backend/drivers/ai/providers/mistral/inputError.ts index 48610d152..9fb0e497e 100644 --- a/src/backend/drivers/ai/providers/mistral/inputError.ts +++ b/src/backend/drivers/ai/providers/mistral/inputError.ts @@ -27,3 +27,9 @@ import { SDKValidationError } from '@mistralai/mistralai/models/errors/sdkvalida */ export const isMistralInputError = (error: unknown): boolean => error instanceof SDKValidationError && !(error instanceof MistralError); + +/** True when Mistral answered 2xx with a body the SDK couldn't use. */ +export const isMistralUnusableAnswer = (error: unknown): boolean => + error instanceof MistralError && + error.statusCode >= 200 && + error.statusCode < 300; diff --git a/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts b/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts index e997b0272..d837e6f36 100644 --- a/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts +++ b/src/backend/drivers/ai/providers/mistral/ocr/MistralOcrProvider.ts @@ -37,7 +37,10 @@ import { OCR_MAX_PAGES, type OcrModel, } from '../../../interfaces/ocr/models.js'; -import { isMistralInputError } from '../inputError.js'; +import { HTTPClient } from '@mistralai/mistralai/lib/http.js'; +import { jsonCheckedFetch } from '../../../shared/jsonCheckedFetch.js'; +import { isMistralInputError, isMistralUnusableAnswer } from '../inputError.js'; +import { malformedUpstreamResponse } from '../../../../util/upstreamErrors.js'; import type { IOcrProvider, OcrBlock, @@ -81,8 +84,7 @@ const toMistralResponseFormat = ( ): Record => { const format = value as Record | null; const jsonSchema = (format?.jsonSchema ?? format?.json_schema) as - | Record - | undefined; + Record | undefined; const schema = jsonSchema?.schemaDefinition ?? jsonSchema?.schema; if ( !format || @@ -122,6 +124,7 @@ export class MistralOcrProvider implements IOcrProvider { config: { apiKey: string }, ) { this.#client = new Mistral({ + httpClient: new HTTPClient({ fetcher: jsonCheckedFetch }), apiKey: config.apiKey, }) as unknown as MistralOcrClient; } @@ -210,6 +213,9 @@ export class MistralOcrProvider implements IOcrProvider { legacyCode: 'bad_request', }); } + if (isMistralUnusableAnswer(e)) { + throw malformedUpstreamResponse('mistral', 'Mistral OCR'); + } throw e; } finally { await hold.release(); diff --git a/src/backend/drivers/ai/shared/jsonCheckedFetch.test.ts b/src/backend/drivers/ai/shared/jsonCheckedFetch.test.ts new file mode 100644 index 000000000..9f75389ee --- /dev/null +++ b/src/backend/drivers/ai/shared/jsonCheckedFetch.test.ts @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Puter is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Puter. If not, see . + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { jsonCheckedFetch } from './jsonCheckedFetch.js'; + +const answer = (response: Response) => + vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('jsonCheckedFetch', () => { + it('passes a JSON answer through with its status and headers', async () => { + answer(Response.json({ a: 1 }, { headers: { 'x-request-id': 'r1' } })); + const response = await jsonCheckedFetch('https://x.test'); + expect(response.status).toBe(200); + expect(response.headers.get('x-request-id')).toBe('r1'); + expect(await response.json()).toEqual({ a: 1 }); + }); + + it.each(['{"id":"x","choices":[{"mess', '', '502'])( + 'turns a 2xx JSON answer with the body %j into a 502', + async (body) => { + answer( + new Response(body, { + headers: { 'content-type': 'application/json' }, + }), + ); + const response = await jsonCheckedFetch('https://x.test'); + expect(response.status).toBe(502); + expect(await response.json()).toEqual({ + error: { message: expect.any(String) }, + }); + }, + ); + + it('rejects a declared JSON body over the cap before reading it', async () => { + const cancel = vi.fn(); + answer(new Response(new ReadableStream({ cancel }), { + headers: { + 'content-type': 'application/json', + 'content-length': String(64 * 1024 * 1024 + 1), + }, + })); + expect((await jsonCheckedFetch('https://x.test')).status).toBe(502); + expect(cancel).toHaveBeenCalledOnce(); + }); + + it('rejects an undeclared JSON body that exceeds the cap', async () => { + answer(new Response(new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(64 * 1024 * 1024 + 1).fill(32)); + controller.enqueue(new TextEncoder().encode('{}')); + controller.close(); + }, + }), { headers: { 'content-type': 'application/json' } })); + expect((await jsonCheckedFetch('https://x.test')).status).toBe(502); + }); + + it('leaves streams, binary bodies and error answers alone', async () => { + for (const original of [ + new Response('data: {', { + headers: { 'content-type': 'text/event-stream' }, + }), + new Response('RIFF', { headers: { 'content-type': 'audio/wav' } }), + new Response('{', { + status: 400, + headers: { 'content-type': 'application/json' }, + }), + ]) { + answer(original); + expect(await jsonCheckedFetch('https://x.test')).toBe(original); + } + }); +}); diff --git a/src/backend/drivers/ai/shared/jsonCheckedFetch.ts b/src/backend/drivers/ai/shared/jsonCheckedFetch.ts new file mode 100644 index 000000000..ec1734c1a --- /dev/null +++ b/src/backend/drivers/ai/shared/jsonCheckedFetch.ts @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Puter is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Puter. If not, see . + */ + +import { readBoundedBody } from '../../util/fileInput.js'; + +const MAX_JSON_RESPONSE_BYTES = 64 * 1024 * 1024; + +/** + * `fetch` for a vendor SDK client. A 2xx answer labelled JSON whose body + * doesn't parse comes back as a 502, which the SDK raises with a status. Left + * alone, the SDKs throw a bare SyntaxError, and Mistral's leaves a rejected + * promise nobody handles. + */ +export const jsonCheckedFetch = async ( + input: string | URL | Request, + init?: RequestInit, +): Promise => { + const response = await (init == null ? fetch(input) : fetch(input, init)); + const type = response.headers?.get('content-type') ?? ''; + if (!response.ok || !/^application\/json\b/i.test(type)) return response; + let text: string; + try { + text = ( + await readBoundedBody(response, MAX_JSON_RESPONSE_BYTES) + ).toString('utf8'); + JSON.parse(text); + } catch { + return Response.json( + { + error: { + message: 'The provider returned an unreadable response', + }, + }, + { status: 502 }, + ); + } + return new Response(text, response); +}; diff --git a/src/backend/drivers/util/upstreamErrors.test.ts b/src/backend/drivers/util/upstreamErrors.test.ts index b9af47bcf..dbeb403ba 100644 --- a/src/backend/drivers/util/upstreamErrors.test.ts +++ b/src/backend/drivers/util/upstreamErrors.test.ts @@ -35,6 +35,7 @@ import { sanitizeUpstreamMessage, upstreamBodyStream, upstreamFetch, + upstreamJson, UpstreamResponseError, } from './upstreamErrors.js'; @@ -224,6 +225,12 @@ describe('sanitizeUpstreamMessage', () => { ).toBe('Bad gateway'); }); + it('reads a message that is not text as empty', () => { + for (const value of [undefined, null, 5, { message: 'x' }, ['x']]) { + expect(sanitizeUpstreamMessage(value)).toBe(''); + } + }); + it('bounds the length', () => { const out = sanitizeUpstreamMessage('x'.repeat(1000)); expect(out.length).toBe(300); @@ -245,6 +252,26 @@ describe('sanitizeUpstreamMessage', () => { }); }); +describe('upstreamJson', () => { + it('returns the parsed body', async () => { + expect( + await upstreamJson('acme', 'Acme', Response.json({ a: 1 })), + ).toEqual({ a: 1 }); + }); + + it('raises a 502 naming the provider when the body is not JSON', async () => { + const error = await upstreamJson( + 'acme', + 'Acme', + new Response('Bad gateway'), + ).catch((e) => e); + expect(error).toBeInstanceOf(HttpError); + expect(error.statusCode).toBe(502); + expect(error.legacyCode).toBe('upstream_failed'); + expect(error.fields).toEqual({ provider: 'acme' }); + }); +}); + describe('upstreamFetch', () => { // A provider stand-in: `/status/` answers with that status and the // request body echoed back as the response body; `/hang` never answers; diff --git a/src/backend/drivers/util/upstreamErrors.ts b/src/backend/drivers/util/upstreamErrors.ts index 99db87277..b47119a20 100644 --- a/src/backend/drivers/util/upstreamErrors.ts +++ b/src/backend/drivers/util/upstreamErrors.ts @@ -20,6 +20,8 @@ import { Readable } from 'node:stream'; import type { ReadableStream as WebReadableStream } from 'node:stream/web'; +import { HttpError } from '../../core/http/HttpError.js'; + // -- Transport failures -- // Transport timeouts carry no HTTP status. The Stainless SDKs (OpenAI, @@ -170,10 +172,11 @@ export const isCreditExhaustion = ( * routes) can ask for more room. */ export const sanitizeUpstreamMessage = ( - raw: string, + raw: unknown, maxLength: number = MAX_UPSTREAM_MESSAGE_LENGTH, ): string => { - const text = raw + // A provider can put an object where its docs promise a message. + const text = (typeof raw === 'string' ? raw : '') .replace(/<(style|script)[\s\S]*?<\/\1>/gi, ' ') .replace(/<[^>]*>/g, ' ') .replace(/https?:\/\/\S+/gi, ' ') @@ -296,6 +299,29 @@ export async function upstreamFetch( } } +/** A provider answered 2xx with a body the driver can't use. */ +export const malformedUpstreamResponse = ( + provider: string, + providerLabel: string, +): HttpError => + new HttpError(502, `${providerLabel} returned an unexpected response`, { + legacyCode: 'upstream_failed', + fields: { provider }, + }); + +/** The JSON body of a provider's 2xx answer. */ +export const upstreamJson = async ( + provider: string, + providerLabel: string, + response: Response, +): Promise => { + try { + return await response.json(); + } catch { + throw malformedUpstreamResponse(provider, providerLabel); + } +}; + /** * A provider's response body as a stream to hand straight to the caller. A * failure mid-body (a reset, or undici's body timeout) errors the stream, which diff --git a/src/docs/src/rate-limits-and-quotas.md b/src/docs/src/rate-limits-and-quotas.md index acaf36f45..a033a588b 100644 --- a/src/docs/src/rate-limits-and-quotas.md +++ b/src/docs/src/rate-limits-and-quotas.md @@ -953,6 +953,9 @@ An account can also hold at most **150** open connections from one origin, so a Every driver call also counts toward **8,000 calls/min**, before the per-API limits above. It only exists to catch runaway loops; a client that hits it is looping. +JSON replies validated by the Mistral, OpenAI image and transcription, BytePlus image, Together image and video, and xAI image clients are capped at 64 MiB. Larger replies fail with `502 upstream_failed`. + + ## Storage quota Every account has a filesystem quota (200 MiB free; paid plans add more). It counts bytes stored, not bytes transferred, and deleting files frees space immediately. At the limit, writes fail with `413 input_too_large`; reads keep working. `puter.fs.space()` returns `{ capacity, used }`.