Skip to content

Commit 69cfff0

Browse files
committed
Merge remote-tracking branch 'origin/release/v3.8.50' into feat/imagetotext-service-kinds
2 parents ddcb840 + 0bd2be0 commit 69cfff0

9 files changed

Lines changed: 290 additions & 5 deletions

File tree

open-sse/config/constants.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,24 @@ export const HTTP_STATUS = {
179179
SERVICE_UNAVAILABLE: 503,
180180
GATEWAY_TIMEOUT: 504,
181181
};
182+
183+
/**
184+
* #10360 — stable error code for an INTERNAL violation of the executor
185+
* `execute()` result contract (`normalizeExecutorResult` received something
186+
* that is neither a Response nor `{ response: Response }`).
187+
*
188+
* This is our own bug, never a provider/account health signal, so every
189+
* resilience layer must treat it as request-scoped and terminal: no connection
190+
* cooldown, no provider circuit-breaker trip, no retry. It rides on the error's
191+
* `.code` (read by `getUpstreamErrorIdentifier`) and therefore reaches
192+
* `checkFallbackError` as `structuredError.code` and the chat/combo predicates
193+
* as `result.errorCode`.
194+
*
195+
* Lives here (leaf config module) so both `open-sse/handlers/` and
196+
* `open-sse/services/` can import it without creating a cycle.
197+
*/
198+
export const EXECUTOR_CONTRACT_VIOLATION_CODE = "executor_contract_violation";
199+
182200
export {
183201
BACKOFF_CONFIG,
184202
COOLDOWN_MS,

open-sse/handlers/chatCore/upstreamTimeouts.ts

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { FETCH_TIMEOUT_MS } from "../../config/constants.ts";
1+
import {
2+
EXECUTOR_CONTRACT_VIOLATION_CODE,
3+
FETCH_TIMEOUT_MS,
4+
HTTP_STATUS,
5+
} from "../../config/constants.ts";
26
import { getModelTimeoutMs } from "../../config/providerModels.ts";
37
import {
48
getLoggedInputTokens,
@@ -98,23 +102,79 @@ export function getExecutorTimeoutMs(executor: unknown, provider?: string, model
98102
return resolveProviderTimeoutMs(executor);
99103
}
100104

105+
/**
106+
* Cross-realm Response detection (#10360).
107+
*
108+
* `instanceof Response` is a NOMINAL check against `globalThis.Response`, and
109+
* OmniRoute's default egress does not use the global one: `proxyFetch.ts`
110+
* dispatches through the npm `undici` package's `fetch`, whose `Response` is a
111+
* different class from the Node built-in. A bare `instanceof` therefore
112+
* rejected virtually every real upstream response as a "contract violation".
113+
*
114+
* Accept the built-in fast path first, then fall back to a structural probe:
115+
* the `Symbol.toStringTag` brand plus the members the pipeline actually reads
116+
* (`status`/`ok`/`headers.get`/`text`/`clone`). A plain `{ status, ok }` bag
117+
* still fails, so the guard keeps its value.
118+
*/
119+
export function isResponseLike(value: unknown): value is Response {
120+
if (value instanceof Response) return true;
121+
if (!value || typeof value !== "object") return false;
122+
const candidate = value as {
123+
status?: unknown;
124+
ok?: unknown;
125+
headers?: { get?: unknown } | null;
126+
text?: unknown;
127+
clone?: unknown;
128+
};
129+
return (
130+
Object.prototype.toString.call(value) === "[object Response]" &&
131+
typeof candidate.status === "number" &&
132+
typeof candidate.ok === "boolean" &&
133+
!!candidate.headers &&
134+
typeof candidate.headers.get === "function" &&
135+
typeof candidate.text === "function" &&
136+
typeof candidate.clone === "function"
137+
);
138+
}
139+
140+
/**
141+
* Builds the terminal error thrown on a genuine contract violation (#10360).
142+
*
143+
* Carries `status = 500` and `code = EXECUTOR_CONTRACT_VIOLATION_CODE` so the
144+
* failure is classified as an INTERNAL, non-retryable defect instead of falling
145+
* through chatCore's `BAD_GATEWAY` default. A 502 made every layer treat our own
146+
* bug as a flaky provider: the connection was cooled down as "rate limited", the
147+
* provider breaker counted it, and the batch runner (which retries 429/502/504)
148+
* span for its full 24h window on an error that can never resolve itself.
149+
*/
150+
export function createExecutorContractError(): Error & { status: number; code: string } {
151+
const err = new TypeError("Executor result must contain a Response") as TypeError & {
152+
status: number;
153+
code: string;
154+
};
155+
err.name = "ExecutorContractError";
156+
err.status = HTTP_STATUS.SERVER_ERROR;
157+
err.code = EXECUTOR_CONTRACT_VIOLATION_CODE;
158+
return err;
159+
}
160+
101161
export function normalizeExecutorResult(result: unknown): {
102162
response: Response;
103163
url: string;
104164
headers: Record<string, string>;
105165
transformedBody: unknown;
106166
transport?: string;
107167
} {
108-
if (result instanceof Response) {
168+
if (isResponseLike(result)) {
109169
return { response: result, url: "", headers: {}, transformedBody: null };
110170
}
111171
if (
112172
!result ||
113173
typeof result !== "object" ||
114174
!("response" in result) ||
115-
!(result.response instanceof Response)
175+
!isResponseLike(result.response)
116176
) {
117-
throw new TypeError("Executor result must contain a Response");
177+
throw createExecutorContractError();
118178
}
119179
const normalized = result as {
120180
response: Response;

open-sse/services/accountFallback.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
BACKOFF_STEPS_MS,
3+
EXECUTOR_CONTRACT_VIOLATION_CODE,
34
PROVIDER_PROFILES,
45
RateLimitReason,
56
HTTP_STATUS,
@@ -1458,6 +1459,21 @@ export function checkFallbackError(
14581459
* caller can persist an explicit reset window instead of the engine's scaled cooldown. */
14591460
configuredCooldownMs?: number;
14601461
} {
1462+
// #10360: an executor-result contract violation is OUR bug, not the provider's.
1463+
// Retrying reproduces it verbatim, and cooling the connection down (or tripping
1464+
// the provider breaker) punishes a healthy account for an internal defect. Must
1465+
// run before every other classification — the surfaced status is a plain 500,
1466+
// which the retryable set below would otherwise treat as a transient upstream
1467+
// failure and hand a backoff cooldown.
1468+
if (structuredError?.code === EXECUTOR_CONTRACT_VIOLATION_CODE) {
1469+
return {
1470+
shouldFallback: false,
1471+
cooldownMs: 0,
1472+
reason: EXECUTOR_CONTRACT_VIOLATION_CODE,
1473+
skipProviderBreaker: true,
1474+
};
1475+
}
1476+
14611477
const svc = serviceSupervisorCooldown(status, headers);
14621478
if (svc) return svc;
14631479
const rg = rot.gateFor(status, rotation?.account);

open-sse/services/combo/comboPredicates.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* predicates are re-exported from combo.ts for backward compatibility.
77
*/
88

9+
import { EXECUTOR_CONTRACT_VIOLATION_CODE } from "../../config/constants.ts";
910
import { errorResponse } from "../../utils/error.ts";
1011
import { parseModel } from "../model.ts";
1112
import { isSelfInflictedUpstreamTimeout } from "../../handlers/chatCore/cooldownClassification.ts";
@@ -201,6 +202,9 @@ const REQUEST_SCOPED_UPSTREAM_ERROR_CODES: Record<string, true> = {
201202
rate_limit_queue_timeout: true,
202203
rate_limit_queue_full: true,
203204
rate_limit_queue_wedged: true,
205+
// #10360: our own executor-result contract violation. An internal defect, not
206+
// a provider/account fault — it must never cool a connection or trip a breaker.
207+
[EXECUTOR_CONTRACT_VIOLATION_CODE]: true,
204208
};
205209

206210
/** Request/model-specific failures must not poison provider-wide resilience state. */

src/app/api/v1/models/catalogHelpers.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export interface CustomModelEntry {
1616
apiFormat?: string;
1717
supportedEndpoints?: string[];
1818
inputTokenLimit?: number;
19+
outputTokenLimit?: number;
1920
isHidden?: boolean;
2021
// User-set "vision-capable" flag (persisted by addCustomModel / replaceCustomModels
2122
// in src/lib/db/models.ts). Surfaced into `/v1/models` via

stryker.conf.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@
219219
"tests/unit/edgetts-provider.test.ts",
220220
"tests/unit/embeddings-auth.test.ts",
221221
"tests/unit/error-classification.test.ts",
222+
"tests/unit/executor-contract-violation-terminal.test.ts",
222223
"tests/unit/error-message-sanitization.test.ts",
223224
"tests/unit/error-sensitive-redaction.test.ts",
224225
"tests/unit/execute-chat-resource-pressure-breaker.test.ts",
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
/**
2+
* #10360 — the executor-result contract guard must not hot-loop the router.
3+
*
4+
* Two defects, one symptom (`tests/unit/batch_api.test.ts` hanging forever):
5+
*
6+
* 1. CROSS-REALM FALSE POSITIVE. The guard added in #10256 used a bare
7+
* `result.response instanceof Response`. OmniRoute's default egress
8+
* (`open-sse/utils/proxyFetch.ts`) is the npm `undici` package's `fetch`,
9+
* whose `Response` class is NOT `globalThis.Response` — so every ordinary
10+
* upstream response arrived as a "contract violation". The guard must
11+
* recognize a structurally valid Response from any realm.
12+
*
13+
* 2. TRANSIENT MISCLASSIFICATION. A genuine contract violation is an INTERNAL
14+
* bug, not a flaky upstream. It carried no `.status`, so chatCore's default
15+
* mapped it to 502 → the connection got cooled down as "rate limited", the
16+
* provider breaker counted it, and `processSingleItemWithRetry` (which
17+
* retries 429/502/504 up to 200×/24h) span forever. It must surface as a
18+
* terminal internal 500 carrying a stable error code, and every resilience
19+
* layer must treat that code as request-scoped: no cooldown, no breaker.
20+
*/
21+
import test from "node:test";
22+
import assert from "node:assert/strict";
23+
import { Response as UndiciResponse } from "undici";
24+
25+
import { normalizeExecutorResult } from "../../open-sse/handlers/chatCore/upstreamTimeouts.ts";
26+
import { EXECUTOR_CONTRACT_VIOLATION_CODE } from "../../open-sse/config/constants.ts";
27+
import {
28+
isRequestScopedUpstreamFailure,
29+
shouldSkipConnDisable,
30+
} from "../../open-sse/services/combo/comboPredicates.ts";
31+
import { shouldTripProviderBreakerForResult } from "../../src/sse/handlers/chatPredicates.ts";
32+
import { checkFallbackError } from "../../open-sse/services/accountFallback.ts";
33+
34+
// ─── 1. Cross-realm Response acceptance ──────────────────────────────────────
35+
36+
test("undici's Response is a different class than the global one (premise)", () => {
37+
assert.notEqual(
38+
UndiciResponse as unknown,
39+
globalThis.Response as unknown,
40+
"if these ever become the same class the cross-realm guard below is moot"
41+
);
42+
assert.equal(
43+
new UndiciResponse("x", { status: 200 }) instanceof globalThis.Response,
44+
false,
45+
"premise: an undici Response fails a bare `instanceof Response`"
46+
);
47+
});
48+
49+
test("normalizeExecutorResult accepts a cross-realm Response in the capture-object arm", () => {
50+
const response = new UndiciResponse(JSON.stringify({ ok: true }), { status: 401 });
51+
52+
const normalized = normalizeExecutorResult({
53+
response,
54+
url: "https://api.openai.com/v1/chat/completions",
55+
headers: { "x-req": "1" },
56+
transformedBody: { a: 1 },
57+
});
58+
59+
assert.equal(normalized.response, response as unknown);
60+
assert.equal(normalized.response.status, 401);
61+
assert.equal(normalized.url, "https://api.openai.com/v1/chat/completions");
62+
assert.deepEqual(normalized.headers, { "x-req": "1" });
63+
assert.deepEqual(normalized.transformedBody, { a: 1 });
64+
});
65+
66+
test("normalizeExecutorResult accepts a bare cross-realm Response", () => {
67+
const response = new UndiciResponse("body", { status: 503 });
68+
69+
const normalized = normalizeExecutorResult(response);
70+
71+
assert.equal(normalized.response, response as unknown);
72+
assert.equal(normalized.response.status, 503);
73+
assert.equal(normalized.url, "");
74+
assert.deepEqual(normalized.headers, {});
75+
assert.equal(normalized.transformedBody, null);
76+
});
77+
78+
// ─── 2. A genuine violation is terminal, not a transient provider failure ────
79+
80+
function captureThrow(run: () => unknown): Error & { status?: unknown; code?: unknown } {
81+
try {
82+
run();
83+
} catch (err) {
84+
return err as Error & { status?: unknown; code?: unknown };
85+
}
86+
throw new assert.AssertionError({ message: "expected normalizeExecutorResult to throw" });
87+
}
88+
89+
test("a genuinely malformed executor result still throws", () => {
90+
assert.throws(() => normalizeExecutorResult({}), /must contain a Response/);
91+
assert.throws(() => normalizeExecutorResult(undefined), /must contain a Response/);
92+
assert.throws(() => normalizeExecutorResult({ response: "not-a-response" }), /must contain a/);
93+
// A partial look-alike (no body readers) must NOT slip past the duck-type.
94+
assert.throws(
95+
() => normalizeExecutorResult({ response: { status: 200, ok: true } }),
96+
/must contain a Response/
97+
);
98+
});
99+
100+
test("the contract-violation error carries an internal-terminal status + stable code", () => {
101+
const err = captureThrow(() => normalizeExecutorResult({ response: "not-a-response" }));
102+
103+
assert.equal(err.status, 500, "an internal contract violation is a 500, never a provider 502");
104+
assert.equal(
105+
err.code,
106+
EXECUTOR_CONTRACT_VIOLATION_CODE,
107+
"chatCore reads `.code` (getUpstreamErrorIdentifier) to tag the surfaced error"
108+
);
109+
assert.equal(EXECUTOR_CONTRACT_VIOLATION_CODE, "executor_contract_violation");
110+
});
111+
112+
test("the contract-violation code is classified as a request-scoped failure", () => {
113+
assert.equal(isRequestScopedUpstreamFailure({ code: EXECUTOR_CONTRACT_VIOLATION_CODE }), true);
114+
});
115+
116+
test("a contract violation must not cool the connection down", () => {
117+
assert.equal(
118+
shouldSkipConnDisable(
119+
{
120+
status: 500,
121+
errorCode: EXECUTOR_CONTRACT_VIOLATION_CODE,
122+
errorType: null,
123+
error: "Executor result must contain a Response",
124+
},
125+
false,
126+
false,
127+
"openai"
128+
),
129+
true,
130+
"our own bug must never mark the operator's account as rate-limited/unavailable"
131+
);
132+
});
133+
134+
test("a contract violation must not trip the provider circuit breaker", () => {
135+
assert.equal(
136+
shouldTripProviderBreakerForResult(
137+
{
138+
status: 500,
139+
errorCode: EXECUTOR_CONTRACT_VIOLATION_CODE,
140+
errorType: null,
141+
error: "Executor result must contain a Response",
142+
},
143+
false,
144+
false
145+
),
146+
false,
147+
"500 is a breaker-failure status, but this one never reached the provider"
148+
);
149+
});
150+
151+
test("checkFallbackError treats the contract violation as terminal — no retry, no cooldown", () => {
152+
const decision = checkFallbackError(
153+
500,
154+
"[500]: Executor result must contain a Response",
155+
0,
156+
"gpt-4o-mini",
157+
"openai",
158+
null,
159+
null,
160+
{ code: EXECUTOR_CONTRACT_VIOLATION_CODE }
161+
);
162+
163+
assert.equal(decision.shouldFallback, false, "retrying our own bug just reproduces it");
164+
assert.equal(decision.cooldownMs, 0, "no connection cooldown for an internal defect");
165+
assert.equal(decision.skipProviderBreaker, true);
166+
});
167+
168+
test("a real provider 500 is still retryable (the terminal branch is not over-broad)", () => {
169+
const decision = checkFallbackError(500, "Internal server error", 0, null, "openai");
170+
171+
assert.equal(decision.shouldFallback, true);
172+
assert.ok(decision.cooldownMs > 0, "a genuine upstream 500 keeps its backoff cooldown");
173+
});

tests/unit/model-token-limit-catalog.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,11 @@ test("v1 model catalog overlays same-id custom metadata before final overrides",
251251
{ outputTokenLimit: 32000 },
252252
false
253253
);
254+
255+
const customProjected = await getModel(`${prefix}/${modelId}`);
256+
assert.ok(customProjected);
257+
assert.equal(customProjected.max_output_tokens, 32000);
258+
254259
assert.equal(
255260
capabilityOverrides.setModelCapabilityOverride(
256261
`${prefix}/${modelId}`,

tests/unit/models-catalog-route.test.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1398,8 +1398,15 @@ test("v1 models catalog skips duplicate built-ins and custom models from inactiv
13981398
const duplicateBuiltins = body.data.filter((item) => item.id === "openai/gpt-4o-2024-11-20");
13991399

14001400
assert.equal(response.status, 200);
1401+
// Still exactly one entry: the custom row overlays the built-in, it does not duplicate it.
14011402
assert.equal(duplicateBuiltins.length, 1);
1402-
assert.equal(duplicateBuiltins[0].custom === true, false);
1403+
// #10248 changed the contract: a custom row for an id that already exists is the
1404+
// operator-owned overlay for that model (catalog.ts:1330) — its explicitly stored
1405+
// fields win over the discovered metadata, and the merged entry is flagged `custom`.
1406+
// Before #10248 the duplicate was skipped outright, so this asserted `false`.
1407+
assert.equal(duplicateBuiltins[0].custom, true);
1408+
// The overlay must keep the catalog identity rather than becoming a detached entry.
1409+
assert.equal(duplicateBuiltins[0].id, "openai/gpt-4o-2024-11-20");
14031410
assert.equal(
14041411
body.data.some((item) => item.id === "cl/inactive-only" || item.id === "cline/inactive-only"),
14051412
false

0 commit comments

Comments
 (0)