Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
18 changes: 12 additions & 6 deletions open-sse/services/autoCombo/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

import {
scorePool,
validateWeights,
DEFAULT_WEIGHTS,
normalizeScoringWeights,
type ScoringWeights,
type ProviderCandidate,
type ScoredProvider,
Expand Down Expand Up @@ -110,12 +110,15 @@ class ScoreTierRotator {
const tiers = groupIntoTiers(candidates);
const best = candidates[0].score;
const worst = candidates[candidates.length - 1].score;
if (tiers.top.length > 0 && (best - worst) >= CLEAR_WINNER_THRESHOLD) {
if (tiers.top.length > 0 && best - worst >= CLEAR_WINNER_THRESHOLD) {
return this.pickFromPool(tiers.top);
}
const prefs = tierPreferencesForName(this.comboName);
const chosen = chooseTierWeighted(tiers, prefs, (pool) => this.pickFromPool(pool), () =>
this.advance(tiers, prefs, candidates)
const chosen = chooseTierWeighted(
tiers,
prefs,
(pool) => this.pickFromPool(pool),
() => this.advance(tiers, prefs, candidates)
);
return chosen;
}
Expand Down Expand Up @@ -248,7 +251,7 @@ export function selectProvider(
const pack = getModePack(config.modePack);
if (pack) weights = pack;
}
if (!validateWeights(weights)) weights = DEFAULT_WEIGHTS;
weights = normalizeScoringWeights(weights);

// Filter out excluded providers
const excluded: string[] = [];
Expand Down Expand Up @@ -322,7 +325,10 @@ export function selectProvider(
(a, b) => estimatedCostFor(a) - estimatedCostFor(b)
)[0];
if (config.budgetFallback === "strict") {
throw new BudgetExceededError(config.budgetCap, cheapest ? estimatedCostFor(cheapest) : 0);
throw new BudgetExceededError(
config.budgetCap,
cheapest ? estimatedCostFor(cheapest) : 0
);
}
if (cheapest) selected = cheapest;
}
Expand Down
2 changes: 2 additions & 0 deletions open-sse/services/autoCombo/routerStrategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export interface RoutingDecision {
reason: string;
candidatesConsidered: number;
finalScore: number;
connectionId?: string;
}

export interface RouterStrategy {
Expand Down Expand Up @@ -103,6 +104,7 @@ class RulesStrategyImpl implements RouterStrategy {
reason: `RulesStrategy: score=${best.score.toFixed(3)} (quota=${best.factors.quota.toFixed(2)}, health=${best.factors.health.toFixed(2)}, cost=${best.factors.costInv.toFixed(2)}, taskFit=${best.factors.taskFit.toFixed(2)})`,
candidatesConsidered: ranked.length,
finalScore: best.score,
connectionId: best.connectionId,
};
}
}
Expand Down
26 changes: 26 additions & 0 deletions open-sse/services/autoCombo/scoring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface ScoringFactors {
tierAffinity: number;
specificityMatch: number;
contextAffinity: number;
cacheAffinity?: number;
resetWindowAffinity: number;
connectionDensity: number;
}
Expand All @@ -34,6 +35,7 @@ export interface ScoringWeights {
tierAffinity: number;
specificityMatch: number;
contextAffinity: number;
cacheAffinity?: number;
resetWindowAffinity: number;
connectionDensity: number;
}
Expand All @@ -49,10 +51,30 @@ export const DEFAULT_WEIGHTS: ScoringWeights = {
tierAffinity: 0.05,
specificityMatch: 0.05,
contextAffinity: 0.05,
cacheAffinity: 0,
resetWindowAffinity: 0,
connectionDensity: 0.05,
};

/** Normalize independently configured UI weights into a scoring distribution. */
export function normalizeScoringWeights(
weights: Partial<ScoringWeights> | null | undefined
): ScoringWeights {
if (!weights) return { ...DEFAULT_WEIGHTS };
const entries = Object.keys(DEFAULT_WEIGHTS) as Array<keyof ScoringWeights>;
const sanitized = Object.fromEntries(
entries.map((key) => {
const value = Number(weights?.[key]);
return [key, Number.isFinite(value) && value >= 0 ? value : 0];
})
) as unknown as ScoringWeights;
const total = entries.reduce((sum, key) => sum + Number(sanitized[key] ?? 0), 0);
if (total <= 0) return { ...DEFAULT_WEIGHTS };
return Object.fromEntries(
entries.map((key) => [key, Number(sanitized[key] ?? 0) / total])
) as unknown as ScoringWeights;
}

export interface ProviderCandidate {
provider: string;
model: string;
Expand All @@ -77,6 +99,8 @@ export interface ProviderCandidate {
quotaResetIntervalSecs?: number;
/** Score [0..1] for staying on the current session's provider/account/model path. */
contextAffinity?: number;
/** Score [0..1] for the account selected by the stable prompt-cache key. */
cacheAffinity?: number;
/** Score [0..1] for quota reset-window preference; sooner selected reset windows score higher. */
resetWindowAffinity?: number;
connectionPoolSize?: number;
Expand Down Expand Up @@ -110,6 +134,7 @@ export function calculateScore(factors: ScoringFactors, weights: ScoringWeights)
(weights.tierAffinity ?? 0) * factors.tierAffinity +
(weights.specificityMatch ?? 0) * factors.specificityMatch +
(weights.contextAffinity ?? 0) * factors.contextAffinity +
(weights.cacheAffinity ?? 0) * (factors.cacheAffinity ?? 0) +
(weights.resetWindowAffinity ?? 0) * factors.resetWindowAffinity +
(weights.connectionDensity ?? 0) * factors.connectionDensity
);
Expand Down Expand Up @@ -207,6 +232,7 @@ export function calculateFactors(
tierAffinity: calculateTierAffinity(candidate, manifestHint),
specificityMatch: calculateSpecificityMatch(candidate, manifestHint),
contextAffinity: clamp01(candidate.contextAffinity ?? 0.5),
cacheAffinity: clamp01(candidate.cacheAffinity ?? 0),
resetWindowAffinity: clamp01(candidate.resetWindowAffinity ?? 0.5),
connectionDensity: clamp01(((candidate.connectionPoolSize ?? 1) - 1) / 10),
};
Expand Down
110 changes: 95 additions & 15 deletions open-sse/services/combo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import { selectQuotaShareTarget } from "./combo/quotaShareStrategy.ts";
import { makeConnectionConcurrencyResolver, lookupPositiveCap } from "./combo/concurrencyCaps.ts";
import { acquireQuotaShareConcurrencySlot } from "./combo/quotaShareConcurrency.ts";
import { orderTargetsByEvalScores } from "./evalRouting.ts";
import { applyPromptCacheAffinity } from "./combo/promptCacheAffinity.ts";
import type { CompressionMode } from "./compression/types.ts";
import { getCachedProviderConnections } from "../../src/lib/db/readCache";
import {
Expand Down Expand Up @@ -387,7 +388,10 @@ export async function buildAutoCandidates(
await Promise.all(
uniqueProviders.map(async (provider) => {
try {
const connections = (await getCachedProviderConnections({ provider, isActive: true })) as Array<Record<string, unknown>>;
const connections = (await getCachedProviderConnections({
provider,
isActive: true,
})) as Array<Record<string, unknown>>;
const active = Array.isArray(connections) ? connections : [];
connectionPoolCounts.set(provider, active.length);
connectionsByProvider.set(provider, active);
Expand Down Expand Up @@ -1298,14 +1302,21 @@ export async function handleComboChat({
apiKeyAllowedConnections,
});
}
// An explicit cache-optimized combo outranks the global cache-affinity default,
// but only protects its ordering when this request actually produced a reusable
// cache key. Cache misses retain the normal session/eval routing behavior.
const cacheStrategyAffinityApplied =
strategy === "cache-optimized" && applyPromptCacheAffinity(orderedTargets, body).applied;
// #6168: session stickiness opt-out. Per-combo `config.disableSessionStickiness`
// overrides the global `settings.disableSessionStickiness` fallback (default false,
// preserving the #3825 prompt-cache/504 fix). When disabled, skip the reorder and
// treat the result as a no-op so the recordStickyBinding write-back below is skipped.
const disableSessionStickiness = resolveDisableSessionStickiness(
config as Record<string, unknown> | null | undefined,
settings as Record<string, unknown> | null | undefined
);
const disableSessionStickiness =
cacheStrategyAffinityApplied ||
resolveDisableSessionStickiness(
config as Record<string, unknown> | null | undefined,
settings as Record<string, unknown> | null | undefined
);
const _sticky = disableSessionStickiness
? ({ targets: orderedTargets, messageHash: null, stuck: false } as const)
: await applySessionStickiness(
Expand All @@ -1315,7 +1326,9 @@ export async function handleComboChat({
normalizeStickinessMessages(body as { messages?: unknown; input?: unknown })
);
orderedTargets = _sticky.targets;
orderedTargets = orderTargetsByEvalScores(orderedTargets, config.evalRouting, log);
if (!cacheStrategyAffinityApplied) {
orderedTargets = orderTargetsByEvalScores(orderedTargets, config.evalRouting, log);
}
orderedTargets = filterTargetsByRequestCompatibility(orderedTargets, body, log);
orderedTargets = applyContextRequirements(orderedTargets, config.contextRequirements, log);

Expand Down Expand Up @@ -1347,6 +1360,48 @@ export async function handleComboChat({
orderedTargets = nextOrder;
}

// Prompt-cache locality is applied after request eligibility and task routing.
// Session stickiness and explicit auto-router pins remain stronger continuity
// decisions; quota, health, and circuit-breaker gates still run per attempt.
const autoConfigForCacheWeight =
strategy === "auto"
? ((combo.autoConfig ||
((config as Record<string, unknown>).auto &&
typeof (config as Record<string, unknown>).auto === "object"
? (config as Record<string, unknown>).auto
: null) ||
config) as Record<string, unknown>)
: null;
const autoWeightsForCache =
autoConfigForCacheWeight?.weights && typeof autoConfigForCacheWeight.weights === "object"
? (autoConfigForCacheWeight.weights as Record<string, unknown>)
: null;
const autoUsesCacheScore = Number(autoWeightsForCache?.cacheAffinity) > 0;
const promptCacheAffinity = applyPromptCacheAffinity(
orderedTargets,
body,
settings?.promptCacheAffinityEnabled !== false && !autoUsesCacheScore
);
if (promptCacheAffinity.applied) {
const protectedFirst =
(_sticky.stuck ||
autoUsedExplicitRouter ||
strategy === "quota-share" ||
strategy === "weighted") &&
orderedTargets[0];
orderedTargets = protectedFirst
? [
protectedFirst,
...promptCacheAffinity.targets.filter((target) => target !== protectedFirst),
]
: promptCacheAffinity.targets;
log.debug?.("COMBO", "Prompt-cache affinity applied", {
source: promptCacheAffinity.source,
fingerprint: promptCacheAffinity.fingerprint,
targetCount: orderedTargets.length,
});
}

// Parallel pre-screen: check provider profiles and model availability for all targets
// Only runs for priority strategy where sequential checking causes latency
const preScreenMap =
Expand Down Expand Up @@ -2251,7 +2306,11 @@ export async function handleComboChat({
});
recordedAttempts++;
lastError = errorText || String(result.status);
comboErrors.push({ model: modelStr, status: result.status, error: errorText || String(result.status) });
comboErrors.push({
model: modelStr,
status: result.status,
error: errorText || String(result.status),
});
if (!lastStatus) lastStatus = result.status;
if (i > 0) fallbackCount++;
log.warn("COMBO", `Model ${modelStr} failed with body-specific error, stopping combo`);
Expand Down Expand Up @@ -2345,7 +2404,11 @@ export async function handleComboChat({
});
recordedAttempts++;
lastError = errorText || String(result.status);
comboErrors.push({ model: modelStr, status: result.status, error: errorText || String(result.status) });
comboErrors.push({
model: modelStr,
status: result.status,
error: errorText || String(result.status),
});
if (!lastStatus) lastStatus = result.status;
if (i > 0) fallbackCount++;
// Wire combo failures into the resilience dashboard (model-level lockout)
Expand Down Expand Up @@ -2510,12 +2573,10 @@ export async function handleComboChat({
latencyMs,
fallbackCount,
});
return errorResponseWithComboDiagnostics(
504,
msg,
buildComboDiag("combo_timeout"),
{ code: "COMBO_TIMEOUT", type: "server_error" }
);
return errorResponseWithComboDiagnostics(504, msg, buildComboDiag("combo_timeout"), {
code: "COMBO_TIMEOUT",
type: "server_error",
});
}

// All models failed in this set try
Expand Down Expand Up @@ -2770,7 +2831,7 @@ async function handleRoundRobinCombo({
{ code: "context_length_exceeded", type: "invalid_request_error" }
);
}
const filteredTargets = filterTargetsByRequestCompatibility(
let filteredTargets = filterTargetsByRequestCompatibility(
evalRankedTargets,
body,
log,
Expand Down Expand Up @@ -2897,7 +2958,26 @@ async function handleRoundRobinCombo({
// stickiness engages on the /v1/responses surface, not just Chat Completions.
normalizeStickinessMessages(body as { messages?: unknown; input?: unknown })
);
const rrAffinity = applyPromptCacheAffinity(
filteredTargets,
body,
settings?.promptCacheAffinityEnabled !== false
);
if (rrAffinity.applied) {
const stickyFirst = _rrSessionSticky.stuck ? _rrSessionSticky.targets[0] : null;
filteredTargets = stickyFirst
? [stickyFirst, ...rrAffinity.targets.filter((target) => target !== stickyFirst)]
: rrAffinity.targets;
log.debug?.("COMBO-RR", "Prompt-cache affinity applied", {
source: rrAffinity.source,
fingerprint: rrAffinity.fingerprint,
targetCount: filteredTargets.length,
});
}
let rrStartIndex = startIndex;
if (rrAffinity.applied) {
rrStartIndex = 0;
}
if (_rrSessionSticky.stuck) {
const stickyIdx = filteredTargets.findIndex(
(t) => t.connectionId === _rrSessionSticky.targets[0]?.connectionId
Expand Down
8 changes: 8 additions & 0 deletions open-sse/services/combo/applyStrategyOrdering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { generateRoutingHints } from "../manifestAdapter";
import { resolveMaxConcurrentByConnection } from "./concurrencyCaps.ts";
import { sortTargetsByContextSize } from "./comboStructure.ts";
import { selectQuotaShareTarget } from "./quotaShareStrategy.ts";
import { applyPromptCacheAffinity } from "./promptCacheAffinity.ts";
import {
orderTargetsByHeadroom,
orderTargetsByResetAwareQuota,
Expand Down Expand Up @@ -196,6 +197,13 @@ export async function applyStrategyOrdering(
} else if (strategy === "context-optimized") {
orderedTargets = sortTargetsByContextSize(orderedTargets);
log.info("COMBO", `Context-optimized ordering: largest first (${orderedTargets[0]?.modelStr})`);
} else if (strategy === "cache-optimized") {
const affinity = applyPromptCacheAffinity(orderedTargets, body);
orderedTargets = affinity.targets;
Comment thread
JxnLexn marked this conversation as resolved.
Resolved
log.info(
"COMBO",
`Cache-optimized ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} first`
);
} else if (strategy === "headroom") {
orderedTargets = await orderTargetsByHeadroom(
orderedTargets,
Expand Down
10 changes: 8 additions & 2 deletions open-sse/services/combo/autoConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { DEFAULT_WEIGHTS, type ScoringWeights } from "../autoCombo/scoring.ts";
import {
DEFAULT_WEIGHTS,
normalizeScoringWeights,
type ScoringWeights,
} from "../autoCombo/scoring.ts";
import { getModePack } from "../autoCombo/modePacks.ts";
import { isRecord } from "./comboData.ts";
import { resolveResetWindowConfig, resolveSlaRoutingPolicy } from "./quotaScoring.ts";
Expand Down Expand Up @@ -53,7 +57,9 @@ export function parseAutoConfig(combo: ComboLike, eligibleTargets: ResolvedCombo
: undefined;
const modePack =
typeof autoConfigSource.modePack === "string" ? autoConfigSource.modePack : undefined;
const weights = modePack ? getModePack(modePack) || configuredWeights : configuredWeights;
const weights = normalizeScoringWeights(
modePack ? getModePack(modePack) || configuredWeights : configuredWeights
);
const resetWindowConfig = resolveResetWindowConfig(autoConfigSource);
const slaPolicy = resolveSlaRoutingPolicy(autoConfigSource);

Expand Down
Loading
Loading