mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(sdk): throw typed proxy 4xx errors from compress instead of retrying (#4751)
## Description `HeadroomClient.compress` only stopped retrying on a `HeadroomCompressError` below 500. When the proxy's error body has a typed `error.type`, `mapProxyError` returns `ConfigurationError`, `ValidationError` and so on, so those 4xx responses were retried and, with the default `fallback: true`, turned into an uncompressed result. The caller never saw the 400. `mapProxyError` also indexed a plain object with the untrusted `error.type`, so `constructor`, `toString` or `__proto__` hit inherited properties (a `String` object returned, or `TypeError: ErrorClass is not a constructor`). Closes #4742 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `sdk/typescript/src/client.ts`: new `isClientError()` reads the status from any `HeadroomError` (`statusCode` on `HeadroomCompressError`, `details.statusCode` on the typed classes, which `mapProxyError` already sets). `compress` rethrows when it is below 500, the same threshold as before. 5xx and connection errors still retry and fall back. - `sdk/typescript/src/errors.ts`: `mapProxyError` looks up `error.type` with `Object.hasOwn`, so inherited keys fall through to `HeadroomCompressError`. - Tests: `test/client.test.ts` checks that typed 400s (`configuration_error`, `validation_error`) are thrown as their class after one request with `retries: 1, fallback: true`, and that a typed 502 (`provider_error`) is still retried. `test/errors.test.ts` checks that `constructor`, `toString`, `__proto__` and `hasOwnProperty` map to `HeadroomCompressError`. ## Testing - [ ] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed TypeScript-only change, so I ran the `sdk-typescript.yml` steps instead of the Python ones: `npm test`, `npm run typecheck` and `npm run build` in `sdk/typescript` all pass. No Python files changed. ### Test Output Before the fix (new tests only, `src/` at `1da8930a`): ```text $ npx vitest run test/client.test.ts test/errors.test.ts × ignores inherited object keys such as constructor × ignores inherited object keys such as toString × ignores inherited object keys such as __proto__ × ignores inherited object keys such as hasOwnProperty × throws typed configuration_error 4xx errors without retry or fallback × throws typed validation_error 4xx errors without retry or fallback Tests 6 failed | 41 passed (47) ``` After the fix: ```text $ npm test Test Files 19 passed | 5 skipped (24) Tests 456 passed | 33 skipped (489) $ npm run typecheck # tsc --noEmit, exit 0 $ npm run build # tsup, exit 0 ``` ## Real Behavior Proof - Environment: Ubuntu Linux, Node v24.22.2, `sdk/typescript` built with `npm run build`, `main` at `1da8930a` plus this change. A local Node `http` server on `127.0.0.1` answers `POST /v1/compress` with `{"error":{"type":T,"message":"msg-T"}}` and counts requests. No proxy or provider credentials. - Exact command / steps: build the SDK, start the stub, call `new HeadroomClient({ baseUrl }).compress([{ role: "user", content: "hello" }])` (defaults: `retries: 1`, `fallback: true`) for each status/type, then call `mapProxyError(400, T, "x")` for the inherited keys. Same script against the build of `1da8930a` for comparison. - Observed result: with this change, typed 4xx errors (`validation_error`, `configuration_error`) throw their typed error after 1 request, prototype keys (`constructor`, `toString`, `__proto__`) map to `HeadroomCompressError`, and 5xx still retries then falls back. Before, those 4xx types retried and silently fell back, and `toString` crashed with `TypeError`. Full output: After: ```text status=400 type=bad_request threw HeadroomCompressError: msg-bad_request requests=1 status=400 type=validation_error threw ValidationError: msg-validation_error requests=1 status=400 type=configuration_error threw ConfigurationError: msg-configuration_error requests=1 status=400 type=constructor threw HeadroomCompressError: msg-constructor requests=1 status=400 type=toString threw HeadroomCompressError: msg-toString requests=1 status=400 type=__proto__ threw HeadroomCompressError: msg-__proto__ requests=1 status=502 type=provider_error resolved compressed=false requests=2 mapProxyError(400,'constructor') -> HeadroomCompressError instanceof Error=true mapProxyError(400,'toString') -> HeadroomCompressError instanceof Error=true mapProxyError(400,'__proto__') -> HeadroomCompressError instanceof Error=true ``` Before (`1da8930a`): ```text status=400 type=bad_request threw HeadroomCompressError: msg-bad_request requests=1 status=400 type=validation_error resolved compressed=false requests=2 status=400 type=configuration_error resolved compressed=false requests=2 status=400 type=constructor resolved compressed=false requests=2 status=400 type=toString resolved compressed=false requests=2 status=400 type=__proto__ resolved compressed=false requests=2 status=502 type=provider_error resolved compressed=false requests=2 mapProxyError(400,'constructor') -> undefined instanceof Error=false TypeError: ErrorClass is not a constructor (at mapProxyError for 'toString') ``` - Not tested: a real Headroom proxy (I did not check which typed errors it sends with a 4xx); other SDK methods that use `rawFetch` (they do not retry, so only the lookup change affects them). With `fallback: false`, a typed 5xx that exhausts retries is still wrapped in `HeadroomConnectionError`, as before; this PR does not change that path. ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: n/a (TypeScript SDK client behavior only) - Stable/default behavior changed: yes, narrowly: `compress` now throws typed 4xx proxy errors (e.g. `ConfigurationError`, `ValidationError`) on the first attempt instead of retrying and returning the uncompressed fallback. This matches the existing behavior for untyped 4xx and the README's `err instanceof ConfigurationError` example. - Kill switch / disable path: none needed; callers that want the old result can catch the error and use the original messages. - Unsafe override required: no - Qualification impact: none - Rollback path: revert this commit ## Review Readiness - [x] I have performed a self-review - [ ] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) N/A ## Additional Notes - Documentation: no change needed; the README already shows `err instanceof ConfigurationError` after `compress`, which this makes reachable. - Python `pytest` / `ruff` / `mypy` boxes are unticked because no Python code changed; the TypeScript SDK CI steps were run instead (above). - The issue suggested both fixes are independent; they are in one small commit here but I can split them if you prefer. AI assistance: this change was prepared with Claude and Codex (AI coding assistants) and tested as described above. Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
JD Davis
parent
c05fbdddc8
commit
e602e4cfb5
@@ -16,7 +16,13 @@ import type {
|
||||
ProxyCompressResponse,
|
||||
ProxyErrorResponse,
|
||||
} from "./types.js";
|
||||
import { mapProxyError, HeadroomConnectionError, HeadroomAuthError, HeadroomCompressError } from "./errors.js";
|
||||
import {
|
||||
mapProxyError,
|
||||
HeadroomError,
|
||||
HeadroomConnectionError,
|
||||
HeadroomAuthError,
|
||||
HeadroomCompressError,
|
||||
} from "./errors.js";
|
||||
import { deepCamelCase, deepSnakeCase } from "./utils/case.js";
|
||||
import { parseSSE } from "./utils/stream.js";
|
||||
import type { CompressRequestConfig, HeadroomMode } from "./types/config.js";
|
||||
@@ -65,6 +71,20 @@ function makeFallbackResult(messages: OpenAIMessage[]): CompressResult {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* True for a proxy error response below 500, whichever class `mapProxyError`
|
||||
* picked. Typed classes carry the status in `details.statusCode`.
|
||||
*/
|
||||
function isClientError(error: unknown): boolean {
|
||||
const status =
|
||||
error instanceof HeadroomCompressError
|
||||
? error.statusCode
|
||||
: error instanceof HeadroomError
|
||||
? error.details?.statusCode
|
||||
: undefined;
|
||||
return typeof status === "number" && status < 500;
|
||||
}
|
||||
|
||||
// --- Headroom request params ---
|
||||
|
||||
export interface HeadroomParams {
|
||||
@@ -255,12 +275,7 @@ export class HeadroomClient implements HeadroomClientInterface {
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (error instanceof HeadroomAuthError) throw error;
|
||||
if (
|
||||
error instanceof HeadroomCompressError &&
|
||||
error.statusCode < 500
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
if (isClientError(error)) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -108,7 +108,8 @@ export function mapProxyError(
|
||||
message: string,
|
||||
): HeadroomError {
|
||||
if (status === 401) return new HeadroomAuthError(message);
|
||||
const ErrorClass = ERROR_TYPE_MAP[type];
|
||||
// `type` comes from the proxy response; ignore inherited keys like "constructor".
|
||||
const ErrorClass = Object.hasOwn(ERROR_TYPE_MAP, type) ? ERROR_TYPE_MAP[type] : undefined;
|
||||
if (ErrorClass) return new ErrorClass(message, { statusCode: status, errorType: type });
|
||||
return new HeadroomCompressError(status, type, message);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
HeadroomConnectionError,
|
||||
HeadroomAuthError,
|
||||
HeadroomCompressError,
|
||||
ConfigurationError,
|
||||
ValidationError,
|
||||
} from "../src/types.js";
|
||||
|
||||
const mockFetch = vi.fn();
|
||||
@@ -271,6 +273,50 @@ describe("HeadroomClient", () => {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1); // no retries
|
||||
});
|
||||
|
||||
it.each([
|
||||
["configuration_error", ConfigurationError],
|
||||
["validation_error", ValidationError],
|
||||
])(
|
||||
"throws typed %s 4xx errors without retry or fallback",
|
||||
async (type, ErrorClass) => {
|
||||
mockFetch.mockImplementation(async () =>
|
||||
errorResponse(400, { error: { type, message: "Bad request" } }),
|
||||
);
|
||||
|
||||
const client = new HeadroomClient({
|
||||
baseUrl: "http://localhost:8787",
|
||||
retries: 1,
|
||||
fallback: true, // fallback doesn't apply to client errors
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.compress(sampleMessages, { model: "gpt-4o" }),
|
||||
).rejects.toThrow(ErrorClass);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1); // no retries
|
||||
},
|
||||
);
|
||||
|
||||
it("still retries typed 5xx errors", async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce(
|
||||
errorResponse(502, {
|
||||
error: { type: "provider_error", message: "Upstream failed" },
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(okResponse(sampleProxyResponse));
|
||||
|
||||
const client = new HeadroomClient({
|
||||
baseUrl: "http://localhost:8787",
|
||||
retries: 1,
|
||||
fallback: false,
|
||||
});
|
||||
const result = await client.compress(sampleMessages, { model: "gpt-4o" });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
expect(result.compressed).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults model to gpt-4o when not provided", async () => {
|
||||
mockFetch.mockResolvedValueOnce(okResponse(sampleProxyResponse));
|
||||
|
||||
|
||||
@@ -166,4 +166,13 @@ describe("mapProxyError", () => {
|
||||
const err = mapProxyError(500, "unknown_error", "something broke");
|
||||
expect(err).toBeInstanceOf(HeadroomCompressError);
|
||||
});
|
||||
|
||||
it.each(["constructor", "toString", "__proto__", "hasOwnProperty"])(
|
||||
"ignores inherited object keys such as %s",
|
||||
(type) => {
|
||||
const err = mapProxyError(400, type, "bad");
|
||||
expect(err).toBeInstanceOf(HeadroomCompressError);
|
||||
expect((err as HeadroomCompressError).errorType).toBe(type);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user