Files
OmniRoute/open-sse/services/comboConfig.ts
ViFigueiredo 577bbf3e47 [defer] feat(combo): universal cooldown-aware retry & auto-strategy combo-ref guard (#7301)
* feat(combo): universal cooldown-aware retry & auto-strategy combo-ref guard

Two changes:

1. Universal cooldown-aware retry (combo.ts):
   - Remove strategy==="quota-share" gate from comboCooldownWaitEnabled
   - Enables all 18 combo strategies (priority, weighted, round-robin, etc.)
     to wait out a short transient cooldown and retry the full set
   - Non-quota-share strategies use shouldWaitForComboCooldown directly
     with earliestRetryAfter and reason="rate_limit" (no per-model lockout)
   - quota-share retains its existing per-target model lockout logic

2. Auto-strategy combo-ref guard (autoStrategy.ts):
   - expandAutoComboCandidatePool now detects kind==="combo-ref" entries
   - When present, returns eligibleTargets without expanding to ALL providers
   - Fixes scenario where an "auto" combo with combo-ref delegates to a
     sub-combo but pulls in every model from every active provider

* feat(combo): global comboTimeoutMs + aggregated error diagnostics

Adds two features to improve combo resilience and debuggability:

1. Global combo timeout (comboTimeoutMs)
   - Configurable per-combo via DEFAULT_COMBO_CONFIG (default 0 = disabled)
   - After each target completes, checks if total elapsed time exceeds limit
   - When exceeded, stops trying further targets and returns 504 immediately
   - Backward-compatible: 0 preserves legacy unlimited-iteration behavior

2. Aggregated error diagnostics
   - comboErrors array accumulates per-model failure details (model, status, error)
   - On combo timeout or all-models-exhausted, returns a message listing the
     first (up to 5) model-level errors with their HTTP status codes
   - Enables operators to see WHICH models failed and WHY without digging
     through individual server logs

* test(combo): cover universal cooldown-aware retry, comboTimeoutMs, and combo-ref guard

Adds/updates automated coverage for this PR's production changes (PR Test
Policy requires tests alongside src/open-sse/electron/bin changes):

- Update the "preserves the first failure status" expectation in
  combo-routing-engine.test.ts: the aggregated per-model error-diagnostics
  suffix is new intended output, not a regression.
- Add two new tests for the global comboTimeoutMs feature: the combo stops
  dispatching further targets and returns 504/COMBO_TIMEOUT with aggregated
  diagnostics once the ceiling trips, and comboTimeoutMs=0 (default) never
  trips it.
- Rewrite the non-quota-share (priority) cooldown-wait scenario in
  combo-quota-share-cooldown-wait-timing.test.ts: comboCooldownWait is no
  longer gated on strategy === "quota-share", so a priority combo now waits
  out a short 429 and re-dispatches too (via shouldWaitForComboCooldown with
  reason "rate_limit"), instead of propagating immediately as before. Also
  adds the disabled-flag counterpart for parity with the quota-share suite.
- Add coverage for the #COMBO-REF guard in expandAutoComboCandidatePool:
  a combo whose models array contains a kind:"combo-ref" entry must not be
  expanded to every model of every active provider.

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* test(combo): keep the new comboTimeoutMs tests free of no-explicit-any

The two new tests initially copied the neighbouring tests' `any`-typed
handleSingleModel params / json() casts. Those neighbours are pre-existing
violations frozen in config/quality/eslint-suppressions.json at a count of 261
for this file, so the 7 new occurrences pushed it to 268 and broke `npm run
lint` (no-explicit-any is an error in tests/ since #6218; new violations must
be fixed, not re-frozen).

Type the new tests properly instead: `unknown`/`string` params, a
ComboErrorPayload interface for the parsed body, and drop the unused
`relayOptions: null as any` (the sibling combo cooldown suites already omit
it). Back to exactly 261 — the suppression file is untouched.

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* fix(combo): gate the universal cooldown retry on the REAL lock reason, not a hardcoded "rate_limit"

The universal cooldown-aware retry kept the quota-share path on
resolveComboCooldownWaitDecision but gave every OTHER strategy a shortcut that
hardcoded `reason: "rate_limit"` and fed shouldWaitForComboCooldown the
earliestRetryAfter directly.

comboCooldownRetry.ts documents TWO deliberate barriers ("SECURITY —
quota_exhausted must be excluded"): (1) the reason allow-list, and (2) the
maxWaitMs ceiling, explicitly called the SECOND barrier. Hardcoding the reason
removed barrier 1 for 17 of the 18 strategies and left only the ceiling — which
does NOT cover a quota_exhausted lock whose wait lands under maxWaitMs. In that
case the combo waits, redispatches against a model that is locked until the
quota resets, and burns the retry budget for nothing.

The shortcut's premise ("non-quota-share combos have no per-connection model
lockout tracking") is also false: recordModelLockoutFailure in the target loop
is not gated on quota-share, so every strategy records model lockouts and the
real reason is always available.

Fix: one decision path for every strategy, always through
resolveComboCooldownWaitDecision, so the reason always crosses the allow-list.
The lock lookup is now keyed on each TARGET's own model (via a new third
`target` arg on lookupLock) — quota-share combos are single-model/multi-account
so this is identical to the previous orderedTargets[0] behavior, but
heterogeneous combos (priority, weighted, round-robin, …) carry a different
model per target and would otherwise miss every lock but the first.

Regression guard (tests/unit/serial/combo-quota-share-cooldown-wait-timing.test.ts):
a priority combo where modelLockout.errorCodes=[403] leaves the 403's
quota_exhausted lock as the only one in play while a 429 crystallizes the
status, and the resulting wait is short enough that the ceiling lets it through
— so only the allow-list can stop it. Verified failing-then-passing: with the
hardcoded reason the combo makes 6 dispatches (wait+redispatch x2); with the
real reason it makes 2 and propagates the 429.

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* chore(quality): rebaseline file-size for PR #7301 own growth (combo +91, combo-routing-engine test +68)

---------

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>
2026-07-21 16:30:37 -03:00

265 lines
10 KiB
TypeScript

/**
* Combo Configuration Resolver
*
* Implements 3-layer cascade: Global Defaults → Provider Overrides → Per-Combo Config
* Most specific wins.
*/
import { MAX_TIMER_TIMEOUT_MS } from "../../src/shared/utils/runtimeTimeouts.ts";
import type { ResponseValidationConfig } from "./combo/responseValidation.ts";
/**
* Maximum number of concurrent pre-screen checks (provider profile + availability)
* when running parallel pre-screening for priority strategy combos.
*/
export const PRE_SCREEN_CONCURRENCY = 5;
/**
* Default per-target timeout for combo fallback when a combo does not set its own
* `targetTimeoutMs`. Combos exist to fail over fast, so inheriting the full upstream
* request timeout (FETCH_TIMEOUT_MS, 600s by default) made a single hung target stall
* the whole combo for up to 10 minutes before falling through to the next model
* (escalated cmqlrhd7c). For STREAMING requests this only bounds the time-to-first-headers
* — token generation streams after the response resolves, so it is NOT cut short. Operators
* can still raise it per-combo via `targetTimeoutMs` (capped at the upstream ceiling), or set
* a longer value for slow non-streaming reasoning combos.
*/
export const DEFAULT_COMBO_TARGET_TIMEOUT_MS = 120_000;
/**
* Default pre-cascade semaphore queue depth for round-robin combos (#3872). When a
* combo member's concurrency slot is saturated, this many requests wait in the
* member's queue before `SEMAPHORE_QUEUE_FULL` triggers a cascade to the next member.
* Kept at 20 for backward compatibility; operators wanting faster failover can lower
* it (0 = never queue, fail over to the next member immediately).
*/
export const DEFAULT_COMBO_QUEUE_DEPTH = 20;
/** Upper bound for the configurable combo queue depth (defensive clamp). */
export const MAX_COMBO_QUEUE_DEPTH = 100;
const DEFAULT_COMBO_CONFIG = {
strategy: "priority",
maxRetries: 1,
retryDelayMs: 2000,
fallbackDelayMs: 0,
concurrencyPerModel: 3, // max simultaneous requests per model (round-robin)
queueTimeoutMs: 30000, // max wait time in semaphore queue (round-robin)
queueDepth: DEFAULT_COMBO_QUEUE_DEPTH, // pre-cascade semaphore queue depth (round-robin, #3872)
handoffThreshold: 0.85,
handoffModel: "",
handoffProviders: ["codex"],
maxMessagesForSummary: 30,
maxComboDepth: 3,
nestedComboMode: "flatten",
trackMetrics: true,
reasoningTokenBufferEnabled: true,
manifestRouting: false,
// Complexity-aware auto routing (2026): when on, the auto router scores
// candidates by how well their tier matches the request's classified
// difficulty (feeds tierAffinity/specificityMatch). Opt-in — off by default.
complexityAwareRouting: false,
resetAwareSessionWeight: 0.35,
resetAwareWeeklyWeight: 0.65,
resetAwareTieBandPercent: 5,
resetAwareExhaustionGuardPercent: 10,
failoverBeforeRetry: true,
// Feature 4985: configurable response-body validation predicate (per-combo). When set,
// a 200 OK whose body fails the predicate fails over to the next target.
responseValidation: undefined as ResponseValidationConfig | undefined,
maxSetRetries: 0,
setRetryDelayMs: 2000,
// Zero-latency optimizations are opt-in because some modes can race targets or
// mutate fallback request bodies for lower tail latency.
zeroLatencyOptimizationsEnabled: false,
// Hedging (Speculative Execution) defaults
hedging: false,
hedgeDelayMs: 500,
// Mid-Stream Fallback Compression defaults
fallbackCompressionMode: "lite",
fallbackCompressionThreshold: 1000,
// Predictive TTFT Circuit Breaker defaults
predictiveTtftMs: 0,
// Pipeline defaults
pipeline_enabled: false,
task_detection: "pattern",
max_reflection_loops: 1,
skip_pipeline_for_tokens_under: 50,
pipeline_fallback: "single-provider",
resetAwareQuotaCacheTtlMs: 0,
resetAwareQuotaCacheMaxStaleMs: 0,
// Global combo timeout (0 = disabled). When set, limits the total wall-clock time
// the combo spends iterating through targets. After each target completes, if the
// elapsed time exceeds comboTimeoutMs, remaining targets are skipped and a 504 with
// aggregated error diagnostics is returned. Backward-compatible: 0 preserves the
// legacy unlimited-iteration behavior.
comboTimeoutMs: 0,
shadowRouting: {
enabled: false,
targets: [],
sampleRate: 1,
maxTargets: 2,
timeoutMs: 30000,
},
evalRouting: {
enabled: false,
suiteIds: [],
maxAgeHours: 720,
minCases: 1,
qualityWeight: 0.85,
latencyWeight: 0.15,
cacheTtlMs: 60000,
},
// Context window requirements for combo target filtering/sorting (undefined by
// default — declared here so resolveComboSetupConfig's inferred return type
// includes the key; combo.ts reads config.contextRequirements).
contextRequirements: undefined as
| {
minContextWindow?: number;
preferLargeContext?: boolean;
contextFilterMode?: "strict" | "lenient";
}
| undefined,
};
const LEGACY_COMBO_RESILIENCE_KEYS = new Set([
"timeoutMs",
"healthCheckEnabled",
"healthCheckTimeoutMs",
]);
type ComboConfigRecord = Record<string, unknown>;
type ComboConfigLike =
| {
config?: ComboConfigRecord | null;
}
| null
| undefined;
type ComboSettingsLike =
| {
comboDefaults?: ComboConfigRecord | null;
providerOverrides?: Record<string, ComboConfigRecord | null | undefined> | null;
}
| null
| undefined;
function isRecord(value: unknown): value is ComboConfigRecord {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function normalizePositiveTimeoutMs(value: unknown): number {
const numericValue = Number(value);
if (!Number.isFinite(numericValue) || numericValue <= 0) return 0;
return Math.min(Math.floor(numericValue), MAX_TIMER_TIMEOUT_MS);
}
export function resolveComboTargetTimeoutMs(
config: Record<string, unknown> | null | undefined,
upstreamTimeoutMs: number,
defaultTimeoutMs: number = 0
): number {
const ceilingTimeoutMs = normalizePositiveTimeoutMs(upstreamTimeoutMs);
const configuredTimeoutMs = isRecord(config)
? normalizePositiveTimeoutMs(config.targetTimeoutMs)
: 0;
// Explicit per-combo config: honour it, but never extend past the upstream ceiling.
if (configuredTimeoutMs > 0) {
if (ceilingTimeoutMs <= 0) return configuredTimeoutMs;
return Math.min(configuredTimeoutMs, ceilingTimeoutMs);
}
// Unset config: fall back to the saner combo default (when provided) so a hung target
// fails over fast instead of inheriting the full upstream timeout. Never exceed the
// ceiling. When no default is given OR the upstream timeout is disabled (0 = unbounded),
// preserve the legacy "inherit the upstream ceiling" behavior.
const fallbackDefaultMs = normalizePositiveTimeoutMs(defaultTimeoutMs);
if (ceilingTimeoutMs <= 0) return ceilingTimeoutMs;
if (fallbackDefaultMs <= 0) return ceilingTimeoutMs;
return Math.min(fallbackDefaultMs, ceilingTimeoutMs);
}
/**
* Resolve the effective pre-cascade semaphore queue depth for a round-robin combo
* (#3872). Falls back to `DEFAULT_COMBO_QUEUE_DEPTH` for missing/invalid/negative
* values and clamps to `MAX_COMBO_QUEUE_DEPTH`. `0` is valid and meaningful: it makes
* a saturated combo member fail over to the next member immediately instead of queueing.
*/
export function resolveComboQueueDepth(config: Record<string, unknown> | null | undefined): number {
const raw = isRecord(config) ? Number(config.queueDepth) : Number.NaN;
if (!Number.isFinite(raw) || raw < 0) return DEFAULT_COMBO_QUEUE_DEPTH;
return Math.min(Math.floor(raw), MAX_COMBO_QUEUE_DEPTH);
}
/**
* Resolve effective config for a combo, applying cascade:
* DEFAULT_COMBO_CONFIG → settings.comboDefaults → settings.providerOverrides[provider] → combo.config
*
* @param {Object} combo - The combo object { config, ... }
* @param {Object} settings - App settings from localDb
* @param {string} [provider] - Optional provider to apply provider-level overrides
* @returns {Object} Resolved config
*/
export function resolveComboConfig(
combo: ComboConfigLike,
settings: ComboSettingsLike,
provider?: string | null
) {
const global = settings?.comboDefaults || {};
const providerOverride = provider ? settings?.providerOverrides?.[provider] || {} : {};
const comboConfig = combo?.config || {};
// Clean undefined values before spreading
const clean = (obj: ComboConfigRecord) =>
Object.fromEntries(
Object.entries(obj).filter(
([key, value]) =>
value !== undefined && value !== null && !LEGACY_COMBO_RESILIENCE_KEYS.has(key)
)
);
const merged = {
...DEFAULT_COMBO_CONFIG,
...clean(global),
...clean(providerOverride),
...clean(comboConfig),
};
return {
...merged,
shadowRouting: {
...DEFAULT_COMBO_CONFIG.shadowRouting,
...(isRecord(global.shadowRouting) ? clean(global.shadowRouting) : {}),
...(isRecord(providerOverride.shadowRouting) ? clean(providerOverride.shadowRouting) : {}),
...(isRecord(comboConfig.shadowRouting) ? clean(comboConfig.shadowRouting) : {}),
},
evalRouting: {
...DEFAULT_COMBO_CONFIG.evalRouting,
...(isRecord(global.evalRouting) ? clean(global.evalRouting) : {}),
...(isRecord(providerOverride.evalRouting) ? clean(providerOverride.evalRouting) : {}),
...(isRecord(comboConfig.evalRouting) ? clean(comboConfig.evalRouting) : {}),
},
};
}
/**
* Get the default combo config (used when no overrides exist)
*/
export function getDefaultComboConfig() {
return { ...DEFAULT_COMBO_CONFIG };
}
/**
* Resolve the effective combo config the same way handleComboChat does: cascade via
* resolveComboConfig when settings exist, else the defaults merged with the combo's own
* config. Encapsulated here so the ternary lives in one place (DRY) and its inferred union
* return type is the single source of truth for ComboContext.config (combo/context.ts).
*/
export function resolveComboSetupConfig(combo: ComboConfigLike, settings: ComboSettingsLike) {
return settings
? resolveComboConfig(combo, settings)
: { ...getDefaultComboConfig(), ...((combo?.config as Record<string, unknown>) || {}) };
}