Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions docs/guides/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -981,6 +981,12 @@ Combo target timeouts inherit the current request timeout by default. Use **Targ
(seconds)** on combo defaults or an individual combo only when a shorter per-target limit should
trigger faster fallback.

Zero-latency combo optimizations are opt-in. Leave **Zero-latency optimizations** disabled to
prevent these latency features from racing fallback targets, skipping targets based on TTFT
history, or compressing fallback requests; enabling it allows configured hedging, predictive TTFT
skips, and proactive fallback compression to trade routing/request fidelity for lower tail
latency.

---

### Health Dashboard
Expand Down
203 changes: 115 additions & 88 deletions open-sse/services/combo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2508,73 +2508,73 @@ export async function handleComboChat({

const transform = new TransformStream(
{
transform(chunk, controller) {
if (tagInjected) {
// Already injected — passthrough
controller.enqueue(chunk);
return;
}
transform(chunk, controller) {
if (tagInjected) {
// Already injected — passthrough
controller.enqueue(chunk);
return;
}

const text = decoder.decode(chunk, { stream: true });

// Fix #721: Look for either non-empty content OR tool_calls in the
// SSE data. Tool-call-only responses have content:null, so we inject
// the tag when we see a finish_reason approaching, or on first content.
const contentMatch = RegExp(/"content":"([^"]+)/).exec(text);
if (contentMatch) {
// Inject tag at the beginning of the first content value
const injected = text.replace(
/"content":"([^"]+)/,
`"content":"${tagContent.replaceAll("\\", "\\\\").replaceAll('"', String.raw`\"`)}$1`
);
tagInjected = true;
controller.enqueue(encoder.encode(injected));
return;
}
const text = decoder.decode(chunk, { stream: true });

// Fix #721: Look for either non-empty content OR tool_calls in the
// SSE data. Tool-call-only responses have content:null, so we inject
// the tag when we see a finish_reason approaching, or on first content.
const contentMatch = RegExp(/"content":"([^"]+)/).exec(text);
if (contentMatch) {
// Inject tag at the beginning of the first content value
const injected = text.replace(
/"content":"([^"]+)/,
`"content":"${tagContent.replaceAll("\\", "\\\\").replaceAll('"', String.raw`\"`)}$1`
);
tagInjected = true;
controller.enqueue(encoder.encode(injected));
return;
}

// Fix #721: For tool-call-only streams, inject the tag when we see
// the finish_reason chunk (before it reaches the client SDK which
// would close the connection). This ensures the tag roundtrips
// through the conversation history even when there's no text content.
if (text.includes('"finish_reason"') && !text.includes('"finish_reason":null')) {
// Inject a content chunk with the tag just before this finish chunk
const tagChunk = `data: ${JSON.stringify({
choices: [
{
delta: { content: tagContent },
index: 0,
finish_reason: null,
},
],
})}\n\n`;
tagInjected = true;
controller.enqueue(encoder.encode(tagChunk));
controller.enqueue(chunk);
return;
}
// Fix #721: For tool-call-only streams, inject the tag when we see
// the finish_reason chunk (before it reaches the client SDK which
// would close the connection). This ensures the tag roundtrips
// through the conversation history even when there's no text content.
if (text.includes('"finish_reason"') && !text.includes('"finish_reason":null')) {
// Inject a content chunk with the tag just before this finish chunk
const tagChunk = `data: ${JSON.stringify({
choices: [
{
delta: { content: tagContent },
index: 0,
finish_reason: null,
},
],
})}\n\n`;
tagInjected = true;
controller.enqueue(encoder.encode(tagChunk));
controller.enqueue(chunk);
return;
}

// No content yet — passthrough
controller.enqueue(chunk);
},
flush(controller) {
// If stream ends without ever finding content (edge case),
// inject tag as a standalone chunk before the stream closes
if (!tagInjected) {
const tagChunk = `data: ${JSON.stringify({
choices: [
{
delta: { content: tagContent },
index: 0,
finish_reason: null,
},
],
})}\n\n`;
controller.enqueue(encoder.encode(tagChunk));
}
// No content yet — passthrough
controller.enqueue(chunk);
},
flush(controller) {
// If stream ends without ever finding content (edge case),
// inject tag as a standalone chunk before the stream closes
if (!tagInjected) {
const tagChunk = `data: ${JSON.stringify({
choices: [
{
delta: { content: tagContent },
index: 0,
finish_reason: null,
},
],
})}\n\n`;
controller.enqueue(encoder.encode(tagChunk));
}
},
},
},
{ highWaterMark: 16384 },
{ highWaterMark: 16384 }
{ highWaterMark: 16384 },
{ highWaterMark: 16384 }
);

const transformedStream = res.body.pipeThrough(transform);
Expand Down Expand Up @@ -3157,20 +3157,29 @@ export async function handleComboChat({
let recordedAttempts = 0;

let globalResolve: ((res: Response) => void) | null = null;
const globalPromise = new Promise<Response>((res) => { globalResolve = res; });
const globalPromise = new Promise<Response>((res) => {
globalResolve = res;
});
const runningTasks = new Set<Promise<void>>();
let anySuccess = false;
const abortControllers = new Map<number, AbortController>();
const zeroLatencyOptimizationsEnabled = config.zeroLatencyOptimizationsEnabled === true;

const executeTarget = async (i: number): Promise<{ ok: boolean; response?: Response } | null> => {
const executeTarget = async (
i: number
): Promise<{ ok: boolean; response?: Response } | null> => {
const target = orderedTargets[i];
const modelStr = target.modelStr;
const provider = target.provider;
const profile = await getRuntimeProviderProfile(provider);
const allowRateLimitedConnection =
Boolean(provider && provider !== "unknown") && transientRateLimitedProviders.has(provider);
const targetForAttempt = allowRateLimitedConnection
? { ...target, allowRateLimitedConnection: true, modelAbortSignal: abortControllers.get(i)!.signal }
? {
...target,
allowRateLimitedConnection: true,
modelAbortSignal: abortControllers.get(i)!.signal,
}
: { ...target, modelAbortSignal: abortControllers.get(i)!.signal };

// #1731: Skip targets from a provider that already signaled full quota exhaustion this request.
Expand All @@ -3189,7 +3198,7 @@ export async function handleComboChat({
if (!available) {
log.info("COMBO", `Skipping ${modelStr} — no credentials available or model excluded`);
if (i > 0) fallbackCount++;
return null;
return null;
}
}

Expand All @@ -3200,7 +3209,7 @@ export async function handleComboChat({
if (gateResult.allowed === false) {
logCredentialSkip(log, modelStr, gateResult.reason || "Credential gate blocked");
if (i > 0) fallbackCount++;
return null;
return null;
}
}

Expand All @@ -3221,15 +3230,23 @@ export async function handleComboChat({
}

// Predictive TTFT Circuit Breaker (skip slow models)
if (config.predictiveTtftMs && config.predictiveTtftMs > 0 && retry === 0) {
if (
zeroLatencyOptimizationsEnabled &&
config.predictiveTtftMs &&
config.predictiveTtftMs > 0 &&
retry === 0
) {
const cMetrics = getComboMetrics(combo.name);
if (cMetrics) {
const targetKey = orderedTargets[i].executionKey || modelStr;
const m = cMetrics.byTarget[targetKey] || cMetrics.byModel[modelStr];
if (m && m.requests >= 5 && m.avgLatencyMs > config.predictiveTtftMs) {
log.warn("COMBO", `Predictive TTFT Circuit Breaker: skipping ${modelStr} (avg ${m.avgLatencyMs}ms > max ${config.predictiveTtftMs}ms)`);
return null;
}
const targetKey = orderedTargets[i].executionKey || modelStr;
const m = cMetrics.byTarget[targetKey] || cMetrics.byModel[modelStr];
if (m && m.requests >= 5 && m.avgLatencyMs > config.predictiveTtftMs) {
log.warn(
"COMBO",
`Predictive TTFT Circuit Breaker: skipping ${modelStr} (avg ${m.avgLatencyMs}ms > max ${config.predictiveTtftMs}ms)`
);
return null;
}
}
}

Expand Down Expand Up @@ -3273,14 +3290,26 @@ export async function handleComboChat({
let attemptBody = JSON.parse(JSON.stringify(body));

// Proactive Context Compression for fallbacks (Zero-Latency optimization)
if (i > 0 && config.fallbackCompressionMode && config.fallbackCompressionMode !== "off") {
if (
zeroLatencyOptimizationsEnabled &&
i > 0 &&
config.fallbackCompressionMode &&
config.fallbackCompressionMode !== "off"
) {
const { estimateTokens } = await import("./contextManager.ts");
const estimatedTokens = estimateTokens(JSON.stringify(attemptBody));
if (estimatedTokens > (config.fallbackCompressionThreshold ?? 1000)) {
const { applyCompression } = await import("./compression/strategySelector.ts");
const compressionResult = applyCompression(attemptBody, config.fallbackCompressionMode as CompressionMode, { model: modelStr });
const compressionResult = applyCompression(
attemptBody,
config.fallbackCompressionMode as CompressionMode,
{ model: modelStr }
);
if (compressionResult.compressed) {
log.info("COMBO", `Proactive fallback compression applied (${config.fallbackCompressionMode}): ${estimatedTokens} -> ${compressionResult.stats?.compressedTokens} tokens`);
log.info(
"COMBO",
`Proactive fallback compression applied (${config.fallbackCompressionMode}): ${estimatedTokens} -> ${compressionResult.stats?.compressedTokens} tokens`
);
attemptBody = compressionResult.body;
}
}
Expand Down Expand Up @@ -3522,8 +3551,7 @@ export async function handleComboChat({
isStreamReadinessFailureErrorBody(errorBody);

// FIX 5: a local per-API-key token-limit 429 must not cool shared accounts.
const isTokenLimitBreach =
result.status === 429 && isTokenLimitBreachErrorBody(errorBody);
const isTokenLimitBreach = result.status === 429 && isTokenLimitBreachErrorBody(errorBody);

// Fix #1681: Status 499 means client disconnected — stop combo loop immediately.
// There is no point trying fallback models when nobody is listening.
Expand Down Expand Up @@ -3598,10 +3626,10 @@ export async function handleComboChat({
result.status === 400 &&
fallbackResult.shouldFallback &&
(fallbackResult.reason === RateLimitReason.MODEL_CAPACITY ||
errorText.toLowerCase().includes('context') ||
errorText.toLowerCase().includes('malformed') ||
errorText.toLowerCase().includes('invalid') ||
errorText.toLowerCase().includes('bad request'))
errorText.toLowerCase().includes("context") ||
errorText.toLowerCase().includes("malformed") ||
errorText.toLowerCase().includes("invalid") ||
errorText.toLowerCase().includes("bad request"))
) {
log.warn(
"COMBO",
Expand Down Expand Up @@ -3695,7 +3723,7 @@ export async function handleComboChat({

for (let i = 0; i < orderedTargets.length; i++) {
if (anySuccess) break;

const abortController = new AbortController();
abortControllers.set(i, abortController);
const onClientAbort = () => abortController.abort();
Expand Down Expand Up @@ -3728,7 +3756,7 @@ export async function handleComboChat({
runningTasks.add(task);
task.finally(() => runningTasks.delete(task));

if (config.hedging && i + 1 < orderedTargets.length) {
if (zeroLatencyOptimizationsEnabled && config.hedging && i + 1 < orderedTargets.length) {
const hedgeDelay = resolveDelayMs(config.hedgeDelayMs, 500);
let timeoutResolve: () => void;
const timeoutPromise = new Promise<void>((r) => {
Expand Down Expand Up @@ -4077,8 +4105,7 @@ async function handleRoundRobinCombo({
isStreamReadinessFailureErrorBody(errorBody);

// FIX 5: a local per-API-key token-limit 429 must not cool shared accounts.
const isTokenLimitBreach =
result.status === 429 && isTokenLimitBreachErrorBody(errorBody);
const isTokenLimitBreach = result.status === 429 && isTokenLimitBreachErrorBody(errorBody);

// Round-robin uses the same target-level fallback rule as other combo
// strategies: non-ok target responses fall through to the next target.
Expand Down
3 changes: 3 additions & 0 deletions open-sse/services/comboConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ const DEFAULT_COMBO_CONFIG = {
failoverBeforeRetry: true,
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export default function ComboDefaultsTab() {
stickyRoundRobinLimit: 3,
resetAwareQuotaCacheTtlMs: 0,
resetAwareQuotaCacheMaxStaleMs: 0,
zeroLatencyOptimizationsEnabled: false,
});
const [codexSessionAffinityTtlMs, setCodexSessionAffinityTtlMs] = useState(0);
const [providerOverrides, setProviderOverrides] = useState<any>({});
Expand Down Expand Up @@ -555,6 +556,29 @@ export default function ComboDefaultsTab() {
}
/>
</div>
<div className="flex items-center justify-between">
<div>
<p className="font-medium text-sm">
{translateOrFallback(t, "zeroLatencyOptimizations", "Zero-latency optimizations")}
</p>
<p className="text-xs text-text-muted">
{translateOrFallback(
t,
"zeroLatencyOptimizationsDesc",
"Opt in to hedging, predictive TTFT skips, and proactive fallback compression. Leave off to prevent these latency features from racing targets or compressing fallback requests."
)}
</p>
</div>
<Toggle
checked={comboDefaults.zeroLatencyOptimizationsEnabled === true}
onChange={() =>
setComboDefaults((prev) => ({
...prev,
zeroLatencyOptimizationsEnabled: prev.zeroLatencyOptimizationsEnabled !== true,
}))
}
/>
</div>
</div>

{/* Provider Overrides */}
Expand Down
1 change: 1 addition & 0 deletions src/app/api/settings/combo-defaults/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export async function GET(request: Request) {
maxMessagesForSummary: 30,
maxComboDepth: 3,
trackMetrics: true,
zeroLatencyOptimizationsEnabled: false,
},
providerOverrides,
});
Expand Down
Loading