Repository navigation
Combo + quota-shared deep audit: 5 fixes + strategy validation + E2E + complexity routing (2026) #3779
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Combo + quota-shared deep audit: 5 fixes + strategy validation + E2E + complexity routing (2026) #3779
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5ffe69b
fix(combo,quota): repair 5 dead/broken rules with TDD
diegosouzapw d17576e
test(combo): validate router strategies + predictive-TTFT decision
diegosouzapw 74c21bb
test(combo): add E2E coverage for 3-hop failover, per-target timeout,…
diegosouzapw c589912
feat(combo): complexity-aware auto routing (2026) + revive dead tier …
diegosouzapw 0d34581
refactor(combo): extract complexity-hint builder + re-baseline file-s…
diegosouzapw 94b47d2
chore(file-size): reconcile base.ts baseline drift from #3780
diegosouzapw 187e17f
fix(scoring): clamp connectionDensity via clamp01 (NaN-safe + consist…
diegosouzapw f23de7e
Merge release/v3.8.24 into audit/combo-quota-validation
diegosouzapw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| /** | ||
| * complexityRouter.ts — Request-complexity classification for tier-aware routing. | ||
| * | ||
| * 2026 strategy: route by the intrinsic difficulty of the *request* (not only by | ||
| * provider stats), so trivial prompts can use cheap models and hard/reasoning | ||
| * prompts escalate to capable ones. Built on the existing specificity detector | ||
| * (codeComplexity / mathComplexity / reasoningDepth / contextSize / toolCalling | ||
| * / domainSpecificity), adding an explicit tool-use → minimum-tier escalation: | ||
| * a request carrying tool/function schemas (or agentic tool-calling signals) | ||
| * should not be routed below the "cheap" tier even when the prose looks | ||
| * trivial, because function-calling reliability matters more than raw cost. | ||
| * | ||
| * The classification maps to a `recommendedTier` that feeds the auto-router's | ||
| * tier-affinity / specificity-match scoring factors (see scoreAutoTargets, | ||
| * gated by config.complexityAwareRouting). | ||
| */ | ||
| import { | ||
| analyzeSpecificity, | ||
| getSpecificityLevel, | ||
| getRecommendedMinTier, | ||
| } from "../specificityDetector"; | ||
| import type { RuleInput, SpecificityLevel } from "../specificityTypes"; | ||
| import { generateRoutingHints, type RoutingHint } from "../manifestAdapter"; | ||
|
|
||
| export type ComplexityTier = "free" | "cheap" | "premium"; | ||
|
|
||
| export interface ComplexityClassification { | ||
| /** 0..100 specificity / difficulty score. */ | ||
| score: number; | ||
| /** trivial | simple | moderate | complex | expert */ | ||
| level: SpecificityLevel; | ||
| /** Minimum provider tier recommended for this request. */ | ||
| recommendedTier: ComplexityTier; | ||
| /** True when the request carries tool/function schemas or agentic tool signals. */ | ||
| hasToolUse: boolean; | ||
| /** Names of the specificity rules that fired (for the inspector / dashboard). */ | ||
| signals: string[]; | ||
| } | ||
|
|
||
| const TIER_ORDER: ComplexityTier[] = ["free", "cheap", "premium"]; | ||
|
|
||
| /** Raise `tier` to at least `floor`; never lowers it. */ | ||
| export function escalateTier(tier: ComplexityTier, floor: ComplexityTier): ComplexityTier { | ||
| return TIER_ORDER.indexOf(tier) >= TIER_ORDER.indexOf(floor) ? tier : floor; | ||
| } | ||
|
|
||
| /** | ||
| * Classify a request's complexity and recommend a minimum provider tier. | ||
| * Pure + dependency-light (no DB / network); safe on the hot path. | ||
| */ | ||
| export function classifyRequestComplexity(input: RuleInput): ComplexityClassification { | ||
| const result = analyzeSpecificity(input); | ||
| const level = getSpecificityLevel(result.score); | ||
|
|
||
| const explicitTools = Array.isArray(input.tools) && input.tools.length > 0; | ||
| const hasToolUse = explicitTools || result.breakdown.toolCalling > 0; | ||
|
|
||
| let recommendedTier = getRecommendedMinTier(level) as ComplexityTier; | ||
| // Tool-using / agentic requests need reliable function calling — floor at "cheap". | ||
| if (hasToolUse) recommendedTier = escalateTier(recommendedTier, "cheap"); | ||
|
|
||
| return { | ||
| score: result.score, | ||
| level, | ||
| recommendedTier, | ||
| hasToolUse, | ||
| signals: result.rulesTriggered, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Build the opt-in complexity-aware routing hint for the auto-router. Returns a | ||
| * RoutingHint whose `recommendedMinTier` is escalated to the request's intrinsic | ||
| * complexity (and floored at "cheap" for tool-using requests), or `null` on any | ||
| * failure — fail-open, so scoring stays tier-neutral. Extracted from combo.ts to | ||
| * keep the complexity-routing logic in one module. | ||
| */ | ||
| export function buildComplexityRoutingHint( | ||
| modelTargets: Parameters<typeof generateRoutingHints>[0], | ||
| body: { messages?: unknown; tools?: unknown; model?: unknown } | null | undefined, | ||
| log: { info: (tag: string, message: string) => void } | ||
| ): RoutingHint | null { | ||
| try { | ||
| const ruleInput = { | ||
| messages: Array.isArray(body?.messages) | ||
| ? (body.messages as Array<{ role?: string; content?: string | unknown }>) | ||
| : [], | ||
| tools: Array.isArray(body?.tools) | ||
| ? (body.tools as Array<{ | ||
| function?: { name: string; description?: string; parameters?: unknown }; | ||
| }>) | ||
| : undefined, | ||
| model: typeof body?.model === "string" ? body.model : undefined, | ||
| }; | ||
| const hint = generateRoutingHints(modelTargets, ruleInput); | ||
| // Tool-use escalation: floor the recommended tier at "cheap" so scoring | ||
| // favors function-calling-reliable models for agentic requests. | ||
| const classification = classifyRequestComplexity(ruleInput); | ||
| hint.recommendedMinTier = escalateTier( | ||
| hint.recommendedMinTier as ComplexityTier, | ||
| classification.recommendedTier | ||
| ) as typeof hint.recommendedMinTier; | ||
| log.info( | ||
| "COMBO", | ||
| `Complexity-aware routing: level=${classification.level} score=${classification.score} minTier=${hint.recommendedMinTier} tools=${classification.hasToolUse}` | ||
| ); | ||
| return hint; | ||
| } catch { | ||
| return null; // fail-open: scoring stays tier-neutral | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,8 @@ | |
| */ | ||
|
|
||
| import type { RoutingHint } from "../manifestAdapter"; | ||
| import { clamp01 } from "../../utils/number"; | ||
| import { classifyTier } from "../tierResolver"; | ||
|
|
||
| export interface ScoringFactors { | ||
| quota: number; | ||
|
|
@@ -86,19 +88,22 @@ export interface ScoredProvider { | |
| * Supports tierAffinity + specificityMatch weights when manifest routing is enabled. | ||
| */ | ||
| export function calculateScore(factors: ScoringFactors, weights: ScoringWeights): number { | ||
| return ( | ||
| // clamp01 bounds the result to [0,1] and maps a non-finite sum (a NaN factor) | ||
| // to 0, so a single bad input can't yield NaN (which sorts nondeterministically) | ||
| // or a score >1 from float drift in weights that nominally sum to 1. | ||
| return clamp01( | ||
| weights.quota * factors.quota + | ||
| weights.health * factors.health + | ||
| weights.costInv * factors.costInv + | ||
| weights.latencyInv * factors.latencyInv + | ||
| weights.taskFit * factors.taskFit + | ||
| weights.stability * factors.stability + | ||
| weights.tierPriority * factors.tierPriority + | ||
| (weights.tierAffinity ?? 0) * factors.tierAffinity + | ||
| (weights.specificityMatch ?? 0) * factors.specificityMatch + | ||
| (weights.contextAffinity ?? 0) * factors.contextAffinity + | ||
| (weights.resetWindowAffinity ?? 0) * factors.resetWindowAffinity + | ||
| (weights.connectionDensity ?? 0) * factors.connectionDensity | ||
| weights.health * factors.health + | ||
| weights.costInv * factors.costInv + | ||
| weights.latencyInv * factors.latencyInv + | ||
| weights.taskFit * factors.taskFit + | ||
| weights.stability * factors.stability + | ||
| weights.tierPriority * factors.tierPriority + | ||
| (weights.tierAffinity ?? 0) * factors.tierAffinity + | ||
| (weights.specificityMatch ?? 0) * factors.specificityMatch + | ||
| (weights.contextAffinity ?? 0) * factors.contextAffinity + | ||
| (weights.resetWindowAffinity ?? 0) * factors.resetWindowAffinity + | ||
| (weights.connectionDensity ?? 0) * factors.connectionDensity | ||
| ); | ||
| } | ||
|
|
||
|
|
@@ -131,7 +136,6 @@ function calculateTierAffinity( | |
| ): number { | ||
| if (!hint) return 0.5; | ||
| try { | ||
| const { classifyTier } = require("../tierResolver"); | ||
| const assignment = classifyTier(candidate.provider, candidate.model); | ||
| const tierOrder = ["free", "cheap", "premium"]; | ||
| const providerTierIdx = tierOrder.indexOf(assignment.tier); | ||
|
|
@@ -151,7 +155,6 @@ function calculateSpecificityMatch( | |
| ): number { | ||
| if (!hint) return 0.5; | ||
| try { | ||
| const { classifyTier } = require("../tierResolver"); | ||
| const assignment = classifyTier(candidate.provider, candidate.model); | ||
| const specificityScore = hint.specificity.score; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
|
|
@@ -176,24 +179,28 @@ export function calculateFactors( | |
| const maxLatency = Math.max(...pool.map((p) => p.p95LatencyMs), 1); | ||
| const maxStdDev = Math.max(...pool.map((p) => p.latencyStdDev), 0.001); | ||
|
|
||
| // Every factor is contractually [0,1]. clamp01 guards against bad telemetry | ||
| // (negative quota / cost / latency, NaN, out-of-range candidate-supplied | ||
| // affinities) so a single bad input can't produce a negative or >1 factor | ||
| // that distorts the weighted score. | ||
| return { | ||
| quota: Math.min(1, candidate.quotaRemaining / 100), | ||
| quota: clamp01(candidate.quotaRemaining / 100), | ||
| health: | ||
| candidate.circuitBreakerState === "CLOSED" | ||
| ? 1.0 | ||
| : candidate.circuitBreakerState === "HALF_OPEN" | ||
| ? 0.5 | ||
| : 0.0, | ||
| costInv: 1 - candidate.costPer1MTokens / maxCost, | ||
| latencyInv: 1 - candidate.p95LatencyMs / maxLatency, | ||
| taskFit: getTaskFitness(candidate.model, taskType), | ||
| stability: 1 - candidate.latencyStdDev / maxStdDev, | ||
| costInv: clamp01(1 - candidate.costPer1MTokens / maxCost), | ||
| latencyInv: clamp01(1 - candidate.p95LatencyMs / maxLatency), | ||
| taskFit: clamp01(getTaskFitness(candidate.model, taskType)), | ||
| stability: clamp01(1 - candidate.latencyStdDev / maxStdDev), | ||
| tierPriority: calculateTierScore(candidate.accountTier, candidate.quotaResetIntervalSecs), | ||
| tierAffinity: calculateTierAffinity(candidate, manifestHint), | ||
| specificityMatch: calculateSpecificityMatch(candidate, manifestHint), | ||
| contextAffinity: candidate.contextAffinity ?? 0.5, | ||
| resetWindowAffinity: candidate.resetWindowAffinity ?? 0.5, | ||
| connectionDensity: Math.min(1, Math.max(0, ((candidate.connectionPoolSize ?? 1) - 1) / 10)), | ||
| contextAffinity: clamp01(candidate.contextAffinity ?? 0.5), | ||
| resetWindowAffinity: clamp01(candidate.resetWindowAffinity ?? 0.5), | ||
| connectionDensity: clamp01(((candidate.connectionPoolSize ?? 1) - 1) / 10), | ||
| }; | ||
| } | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To prevent potential runtime
TypeErrorexceptions ifresult.breakdownis undefined, use optional chaining and nullish coalescing to safely accesstoolCalling.