Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions open-sse/services/accountFallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ import {
getCircuitBreaker,
STATE,
} from "../../src/shared/utils/circuitBreaker";
import {
classify429FromError,
type FailureKind,
} from "../../src/shared/utils/classify429";
import { resolveUseUpstream429BreakerHints } from "../../src/shared/utils/providerHints";


type ProviderProfile = {
baseCooldownMs: number;
Expand Down Expand Up @@ -532,9 +538,24 @@ function configureProviderBreaker(
if (!provider) return null;

const resolvedProfile = { ...getProviderProfile(provider), ...(profile ?? {}) };
// Issue #2100 follow-up: resolve useUpstream429BreakerHints from the
// provider profile (stored override) or fall back to per-provider default.
// Stored value type is `boolean | undefined` — never `null` after PATCH.
const userValue = (resolvedProfile as { useUpstream429BreakerHints?: boolean })
.useUpstream429BreakerHints;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The useUpstream429BreakerHints field is missing from the ProviderProfile type definition (line 32) and is not being populated in the buildProviderProfile helper (line 180). Consequently, resolvedProfile.useUpstream429BreakerHints will always be undefined here, causing the circuit breaker to ignore user-configured overrides and always fall back to the per-provider default. Please ensure both the type and the builder are updated to include this field.

const useHints = resolveUseUpstream429BreakerHints(provider, userValue);
return getCircuitBreaker(provider, {
failureThreshold: resolvedProfile.failureThreshold ?? resolvedProfile.circuitBreakerThreshold,
resetTimeout: resolvedProfile.resetTimeoutMs ?? resolvedProfile.circuitBreakerReset,
...(useHints
? {
cooldownByKind: {
rate_limit: 60_000,
quota_exhausted: 3_600_000,
} satisfies Partial<Record<FailureKind, number>>,
classifyError: classify429FromError,
}
: {}),
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type RequestQueueSettings = {
type ConnectionCooldownProfileSettings = {
baseCooldownMs: number;
useUpstreamRetryHints: boolean;
// Issue #2100 follow-up. Optional / undefined when unset; the per-provider
// default in src/shared/utils/providerHints.ts resolves at runtime.
useUpstream429BreakerHints?: boolean;
maxBackoffSteps: number;
};

Expand Down Expand Up @@ -360,6 +363,48 @@ function ConnectionCooldownCard({
}))
}
/>
<div className="flex flex-col gap-1">
<label className="flex items-center justify-between gap-2 text-sm">
<span className="text-text-muted">
Use upstream 429 hints for breaker cooldown
</span>
<select
className="rounded border border-border-default bg-surface-1 px-2 py-1 text-sm font-mono"
value={
current.useUpstream429BreakerHints === true
? "on"
: current.useUpstream429BreakerHints === false
? "off"
: "default"
}
onChange={(e) => {
const v = e.target.value;
const next: boolean | undefined =
v === "on" ? true : v === "off" ? false : undefined;
setDraft((prev) => {
const profile = { ...prev[key] };
if (next === undefined) {
delete (profile as { useUpstream429BreakerHints?: boolean }).useUpstream429BreakerHints;
} else {
(profile as { useUpstream429BreakerHints?: boolean }).useUpstream429BreakerHints = next;
}
return { ...prev, [key]: profile };
});
}}
>
<option value="default">Default (per provider)</option>
<option value="on">Always on</option>
<option value="off">Always off</option>
</select>
</label>
<p className="text-xs text-text-muted">
Apply Retry-After / quota-exhausted signals from 429 responses to
circuit-breaker cooldown duration. Default uses a per-provider
policy: direct cloud providers default on; reverse-proxy /
self-hosted / CLI-backed providers default off. Independent of
&quot;Use upstream retry hints&quot;.
</p>
</div>
<NumberField
label="Max backoff steps"
value={current.maxBackoffSteps}
Expand All @@ -381,6 +426,16 @@ function ConnectionCooldownCard({
{current.useUpstreamRetryHints ? "Yes" : "No"}
</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-text-muted">Use upstream 429 hints (breaker)</span>
<span className="font-mono text-text-main">
{current.useUpstream429BreakerHints === true
? "Yes"
: current.useUpstream429BreakerHints === false
? "No"
: "Default"}
</span>
</div>
<div className="flex items-center justify-between text-sm">
<span className="text-text-muted">Max backoff steps</span>
<span className="font-mono text-text-main">{current.maxBackoffSteps}</span>
Expand Down Expand Up @@ -414,7 +469,26 @@ function ConnectionCooldownCard({
setEditing(false);
}}
onSave={async () => {
await onSave(draft);
// Build PATCH-ready payload: convert undefined useUpstream429BreakerHints
// to explicit null sentinel so the server treats it as unset (not as
// partial-merge "leave unchanged"). JSON.stringify drops undefined keys.
const payload = {
oauth: {
...draft.oauth,
useUpstream429BreakerHints:
draft.oauth.useUpstream429BreakerHints === undefined
? (null as unknown as boolean | undefined)
: draft.oauth.useUpstream429BreakerHints,
},
apikey: {
...draft.apikey,
useUpstream429BreakerHints:
draft.apikey.useUpstream429BreakerHints === undefined
? (null as unknown as boolean | undefined)
: draft.apikey.useUpstream429BreakerHints,
},
};
await onSave(payload as typeof draft);
setEditing(false);
}}
/>
Expand Down
15 changes: 15 additions & 0 deletions src/app/api/resilience/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from "@/lib/resilience/settings";
import { updateResilienceSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { resetAllCircuitBreakers } from "@/shared/utils/circuitBreaker";

type JsonRecord = Record<string, unknown>;

Expand Down Expand Up @@ -196,6 +197,20 @@ export async function PATCH(request) {
});
await syncRuntimeSettings(nextResilience);

// Issue #2100 follow-up: detect transitions in useUpstream429BreakerHints
// and reset breakers so the registry stops serving cached options.
// Compared on STORED override transition (boolean | undefined) so that
// `null` (PATCH input) → undefined (stored) is correctly detected as
// "unset request" when the previous stored value was a boolean.
const breakerHintsChanged =
currentResilience.connectionCooldown.oauth.useUpstream429BreakerHints !==
nextResilience.connectionCooldown.oauth.useUpstream429BreakerHints ||
currentResilience.connectionCooldown.apikey.useUpstream429BreakerHints !==
nextResilience.connectionCooldown.apikey.useUpstream429BreakerHints;
if (breakerHintsChanged) {
resetAllCircuitBreakers();
}

return NextResponse.json({
ok: true,
requestQueue: nextResilience.requestQueue,
Expand Down
40 changes: 39 additions & 1 deletion src/lib/resilience/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ export interface RequestQueueSettings {
export interface ConnectionCooldownProfileSettings {
baseCooldownMs: number;
useUpstreamRetryHints: boolean;
/**
* Issue #2100 follow-up: opt-in toggle for upstream 429 hint trust at the
* circuit-breaker cooldown layer (independent of `useUpstreamRetryHints`
* which controls retry scheduling).
*
* Stored shape is intentionally optional / `boolean | undefined`: when
* unset, the per-provider default from `providerHints.ts` applies.
* Normalize/merge MUST preserve `undefined` — do not coerce via
* `toBoolean(value, fallback)`.
*/
useUpstream429BreakerHints?: boolean;
maxBackoffSteps: number;
}

Expand Down Expand Up @@ -155,7 +166,29 @@ function normalizeConnectionCooldownProfile(
fallback: ConnectionCooldownProfileSettings
): ConnectionCooldownProfileSettings {
const record = asRecord(next);
return {
// useUpstream429BreakerHints uses a 3-state input contract:
// - boolean → user override, store as-is
// - null → explicit unset sentinel, drop key so the per-provider
// default in `providerHints.ts` resolves at runtime
// - omitted → leave existing fallback value unchanged (partial-merge)
// Never coerce via `toBoolean(value, fallback)` because that would
// collapse the unset state.
const hasHintsKey = Object.prototype.hasOwnProperty.call(
record,
"useUpstream429BreakerHints",
);
const rawHints = record.useUpstream429BreakerHints;
let useUpstream429BreakerHints: boolean | undefined;
if (!hasHintsKey) {
useUpstream429BreakerHints = fallback.useUpstream429BreakerHints;
} else if (rawHints === null) {
useUpstream429BreakerHints = undefined;
} else if (typeof rawHints === "boolean") {
useUpstream429BreakerHints = rawHints;
} else {
useUpstream429BreakerHints = fallback.useUpstream429BreakerHints;
}
const out: ConnectionCooldownProfileSettings = {
baseCooldownMs: toInteger(record.baseCooldownMs, fallback.baseCooldownMs, {
min: 0,
max: 24 * 60 * 60 * 1000,
Expand All @@ -166,6 +199,11 @@ function normalizeConnectionCooldownProfile(
max: 32,
}),
};
// Only attach the key when defined — preserves omission across round-trips.
if (useUpstream429BreakerHints !== undefined) {
out.useUpstream429BreakerHints = useUpstream429BreakerHints;
}
return out;
}

function normalizeLegacyConnectionCooldownProfile(
Expand Down
60 changes: 60 additions & 0 deletions src/shared/utils/classify429.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,63 @@ export function retryAfterFromResponse(response: {
}): number | null {
return parseRetryAfter(getHeader(response.headers, "retry-after"));
}

/**
* Adapter that takes an error thrown by an HTTP client (fetch wrapper, axios,
* upstream SDK, etc.) and produces a {@link FailureKind} suitable for the
* `classifyError` option of the circuit breaker.
*
* Recognises the common error shapes:
* - `err.status` + `err.headers` + `err.body` (low-level fetch wrapper)
* - `err.response.status` + `err.response.headers` + `err.response.data` (axios-style)
* - `err.message` (last-resort body for keyword scan)
*
* Returns `undefined` when the error doesn't carry enough information to
* classify, so the breaker can decide what to do without a kind tag.
*
* Companion to issue #2100 follow-up.
*/
export function classify429FromError(err: unknown): FailureKind | undefined {
if (err === null || typeof err !== "object") return undefined;
const e = err as Record<string, unknown>;

let status: number | undefined;
let headers: Record<string, string> | undefined;
let body: unknown;

if (typeof e.status === "number") {
status = e.status;
}
if (typeof e.statusCode === "number" && status === undefined) {
status = e.statusCode;
}

if (e.response && typeof e.response === "object") {
const resp = e.response as Record<string, unknown>;
if (typeof resp.status === "number" && status === undefined) {
status = resp.status;
}
if (resp.headers && typeof resp.headers === "object") {
headers = resp.headers as Record<string, string>;
}
Comment on lines +222 to +224

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Blindly casting resp.headers to Record<string, string> is risky if the HTTP client returns a Headers object (common in native fetch or certain middleware). Object.entries(), which is used by getHeader in this module, does not work on Headers instances. It's safer to normalize the headers to a plain object if a Headers-like interface is detected.

    if (resp.headers && typeof resp.headers === "object") {
      headers = (typeof (resp.headers as any).entries === "function")
        ? Object.fromEntries((resp.headers as any).entries())
        : resp.headers as Record<string, string>;
    }

if (resp.data !== undefined) {
body = resp.data;
} else if (typeof resp.body !== "undefined") {
body = resp.body;
}
}

if (headers === undefined && e.headers && typeof e.headers === "object") {
headers = e.headers as Record<string, string>;
}
Comment on lines +232 to +234

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to the resp.headers check above, e.headers should also be normalized if it's a Headers object to ensure compatibility with getHeader.

  if (headers === undefined && e.headers && typeof e.headers === "object") {
    headers = (typeof (e.headers as any).entries === "function")
      ? Object.fromEntries((e.headers as any).entries())
      : e.headers as Record<string, string>;
  }

if (body === undefined) {
if (typeof e.body !== "undefined") {
body = e.body;
} else if (typeof e.message === "string") {
body = e.message;
}
}

if (typeof status !== "number") return undefined;
return classify429({ status, headers, body });
}
73 changes: 73 additions & 0 deletions src/shared/utils/providerHints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* Per-provider default policy for upstream 429 hint trust.
*
* @see Issue #2100 follow-up — surface a user-overridable per-profile toggle
* that decides whether the circuit breaker uses upstream 429 body / Retry-After
* hints (`classify429`, `cooldownByKind`) to differentiate rate-limit from
* quota-exhausted failure cooldowns.
*
* This helper returns the **default** answer for a given provider. The actual
* runtime decision is the user override (if any) OR this default. See
* `accountFallback.ts` / `chat.ts` / `chatHelpers.ts` for the resolution
* call sites:
*
* ```ts
* const userValue = providerProfile.useUpstream429BreakerHints; // boolean | undefined
* const useHints = userValue !== undefined
* ? userValue
* : defaultUseUpstream429BreakerHints(provider);
* ```
*
* Default policy: direct cloud providers default `true` because their 429
* bodies and `Retry-After` headers are authoritative. Reverse-proxy /
* self-hosted / CLI-backed providers default `false` because forwarded 429
* metadata is often unreliable or fabricated by the proxy.
*
* @module shared/utils/providerHints
*/

import {
UPSTREAM_PROXY_PROVIDERS,
SELF_HOSTED_CHAT_PROVIDER_IDS,
isLocalProvider,
isClaudeCodeCompatibleProvider,
} from "../constants/providers";

/**
* Conservative per-provider default for `useUpstream429BreakerHints`.
*
* Returns `false` for any provider whose 429 metadata may be forwarded by
* an intermediary (proxy, self-hosted runtime, CLI wrapper). Returns `true`
* for direct cloud providers where the upstream response is authoritative.
*/
export function defaultUseUpstream429BreakerHints(providerId: string): boolean {
if (Object.prototype.hasOwnProperty.call(UPSTREAM_PROXY_PROVIDERS, providerId)) {
return false;
}
if (isLocalProvider(providerId)) {
return false;
}
if (SELF_HOSTED_CHAT_PROVIDER_IDS.has(providerId)) {
return false;
}
if (isClaudeCodeCompatibleProvider(providerId)) {
return false;
}
return true;
}

/**
* Resolve the effective `useHints` decision: the user override wins if set,
* otherwise fall back to the per-provider default.
*
* `undefined` means "not user-set" and triggers the default lookup.
*/
export function resolveUseUpstream429BreakerHints(
providerId: string,
userValue: boolean | undefined,
): boolean {
if (userValue !== undefined) {
return userValue;
}
return defaultUseUpstream429BreakerHints(providerId);
}
5 changes: 5 additions & 0 deletions src/shared/validation/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,11 @@ const connectionCooldownProfileSchema = z
.object({
baseCooldownMs: z.number().int().min(0).optional(),
useUpstreamRetryHints: z.boolean().optional(),
// Issue #2100 follow-up: per-profile toggle for upstream 429 hint trust.
// `null` is an explicit unset sentinel — PATCH handler deletes the key
// from stored settings so the per-provider default resolves at runtime.
// `undefined` (key omitted) means "leave existing value unchanged".
useUpstream429BreakerHints: z.boolean().nullable().optional(),
maxBackoffSteps: z.number().int().min(0).optional(),
})
.strict();
Expand Down
Loading