fix(ai): answer an unreadable 2xx JSON body from Mistral with a 502 (#4720)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Filip KujundžićandClaude Fable 5.2 authored and GitHub committed 2026-11-21 15:52:12 -07:00
1 parent 61c5186f4f
commit 3d300fae5c
8 files changed
+223 -8

No files matched your search

@@ -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<string, string> = {
// 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');
@@ -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;
@@ -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<string, unknown> => {
const format = value as Record<string, unknown> | null;
const jsonSchema = (format?.jsonSchema ?? format?.json_schema) as
| Record<string, unknown>
| undefined;
Record<string, unknown> | 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();
@@ -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 <https://www.gnu.org/licenses/>.
*/
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', '', '<html>502</html>'])(
'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);
}
});
});
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Response> => {
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);
};
@@ -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('<html>Bad gateway</html>'),
).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/<n>` answers with that status and the
// request body echoed back as the response body; `/hang` never answers;
+28 -2
View File
@@ -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<unknown> => {
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
+3
View File
@@ -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 }`.