-
Notifications
You must be signed in to change notification settings - Fork 597
feat(routing): add cost-aware policy scoring and limits #1015
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ca001a4
feat(routing): add cost-aware policy scoring and limits (RI-08) — syn…
Wibias d085779
test(routing): fold RI-08 unknown-cost penalty into score assertions;…
Wibias 18c4c3d
refactor(routing): drop unused providerConfig tier-inference from cos…
Wibias 2e9a5fe
fix(routing): address CodeRabbit round on cost scoring (RI-08)
Wibias aee4471
refactor(routing): drop unused excludedByLimit from cost evidence (RI…
Wibias 24e705e
Update docs-site/src/content/docs/reference/configuration/routing.md
Wibias 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
Some comments aren't visible on the classic Files Changed page.
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
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,77 @@ | ||
| /** | ||
| * Cost-aware policy scoring and limits (RI-08). | ||
| * | ||
| * Reuses the canonical price/cost normalization (`src/usage/cost.ts`). | ||
| * Evidence distinguishes estimated vs authoritative usage and registry vs | ||
| * expected prices. Unknown prices stay unknown (never free); the profile's | ||
| * `unknownEvidence.cost` policy decides how unknown evidence is handled. | ||
| * | ||
| * No billing, invoicing, or hidden budgets - a hard per-request ceiling | ||
| * (`limits.maxEstimatedCostUsd`) is evaluated deterministically. | ||
| */ | ||
|
|
||
| import type { OcxUsage } from "../types"; | ||
| import type { UsageStatus } from "../usage/log"; | ||
| import { estimateRequestCost, type ServiceTierInput } from "../usage/cost"; | ||
| import type { RouteCostEvidence } from "./trace"; | ||
|
|
||
| /** Reference cost (USD) for the relative cost score when no limit is set. */ | ||
| export const COST_SCORE_REFERENCE_USD = 1.0; | ||
|
|
||
| export interface CostEvidenceInput { | ||
| provider: string; | ||
| model: string; | ||
| usage?: OcxUsage; | ||
| usageStatus?: UsageStatus; | ||
| serviceTier?: ServiceTierInput; | ||
| limitUsd?: number; | ||
| } | ||
|
|
||
| /** | ||
| * Assemble cost evidence from the canonical price model. Returns unknown-ish | ||
| * evidence (`incomplete: true`, no estimate) when usage or a price is | ||
| * missing - never a fabricated zero. | ||
| */ | ||
| export function costEvidenceForCandidate(input: CostEvidenceInput): RouteCostEvidence { | ||
| const limitUsd = input.limitUsd; | ||
| if (!input.usage) { | ||
| return { | ||
| ...(limitUsd !== undefined ? { limitUsd } : {}), | ||
| incomplete: true, | ||
| }; | ||
| } | ||
| const estimate = estimateRequestCost({ | ||
| provider: input.provider, | ||
| model: input.model, | ||
| usage: input.usage, | ||
| usageStatus: input.usageStatus ?? "estimated", | ||
| ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), | ||
| }); | ||
| if (!estimate) { | ||
| return { | ||
| ...(limitUsd !== undefined ? { limitUsd } : {}), | ||
| incomplete: true, | ||
| priceSource: "unmatched", | ||
| }; | ||
| } | ||
| const priceSource = estimate.price?.source ?? "registry"; | ||
| return { | ||
| estimatedUsd: estimate.cost.total, | ||
| priceSource, | ||
| incomplete: estimate.estimated || priceSource === "expected", | ||
| ...(limitUsd !== undefined ? { limitUsd } : {}), | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Deterministic cost score in [0,1]: cheaper is better, relative to | ||
| * `COST_SCORE_REFERENCE_USD` (or the profile limit when set). Unknown | ||
| * estimates return null so the profile's unknownEvidence policy applies. | ||
| */ | ||
| export function costScore(evidence: RouteCostEvidence | undefined): number | null { | ||
| if (evidence?.estimatedUsd === undefined || !Number.isFinite(evidence.estimatedUsd)) return null; | ||
| const reference = typeof evidence.limitUsd === "number" && evidence.limitUsd > 0 | ||
| ? evidence.limitUsd | ||
| : COST_SCORE_REFERENCE_USD; | ||
| return Math.max(0, Math.min(1, 1 - evidence.estimatedUsd / reference)); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
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,178 @@ | ||
| import { afterEach, beforeEach, describe, expect, test } from "bun:test"; | ||
| import { mkdtempSync, rmSync } from "node:fs"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import { costEvidenceForCandidate, costScore } from "../src/routing/cost"; | ||
| import { evaluatePolicyProfile, COST_UNKNOWN_PENALTY_SCORE } from "../src/routing/evaluator"; | ||
| import type { OcxConfig } from "../src/types"; | ||
|
|
||
| let testDir = ""; | ||
| let previousHome: string | undefined; | ||
|
|
||
| beforeEach(() => { | ||
| previousHome = process.env.OPENCODEX_HOME; | ||
| testDir = mkdtempSync(join(tmpdir(), "ocx-cost-")); | ||
| process.env.OPENCODEX_HOME = testDir; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| if (previousHome === undefined) delete process.env.OPENCODEX_HOME; | ||
| else process.env.OPENCODEX_HOME = previousHome; | ||
| if (testDir) rmSync(testDir, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| function config(overrides: Partial<OcxConfig> = {}): OcxConfig { | ||
| return { | ||
| port: 10100, | ||
| defaultProvider: "a", | ||
| providers: { | ||
| a: { adapter: "openai-chat", baseUrl: "https://a.example/v1", apiKey: "ka", models: ["m1", "m2"] }, | ||
| anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com/v1", apiKey: "kan", models: ["claude-opus-5", "claude-sonnet-5"] }, | ||
| }, | ||
| routingProfiles: { | ||
| cost: { | ||
| candidates: [ | ||
| { provider: "anthropic", model: "claude-opus-5" }, | ||
| { provider: "anthropic", model: "claude-sonnet-5" }, | ||
| ], | ||
| optimize: { cost: 0.8 }, | ||
| }, | ||
| }, | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| const USAGE = { inputTokens: 1000, outputTokens: 100, estimated: true }; | ||
|
|
||
| describe("cost-aware scoring (RI-08)", () => { | ||
| test("known price produces an estimate with provenance", async () => { | ||
| const evidence = costEvidenceForCandidate({ | ||
| provider: "anthropic", | ||
| model: "claude-opus-5", | ||
| usage: { inputTokens: 1000, outputTokens: 100 }, | ||
| usageStatus: "reported", | ||
| }); | ||
| expect(evidence.estimatedUsd).toBeGreaterThan(0); | ||
| // Canonical jawcode pricing is authoritative; the expected-price overlay | ||
| // is the fallback. Both carry a stable source code. | ||
| expect(["jawcode", "expected"]).toContain(evidence.priceSource); | ||
| expect(evidence.incomplete).toBe(evidence.priceSource === "expected"); | ||
| expect(costScore(evidence)).not.toBeNull(); | ||
| }); | ||
|
|
||
| test("unknown price and missing usage stay unknown - never zero", async () => { | ||
| const noPrice = costEvidenceForCandidate({ provider: "a", model: "m1", usage: USAGE }); | ||
| expect(noPrice.estimatedUsd).toBeUndefined(); | ||
| expect(noPrice.priceSource).toBe("unmatched"); | ||
| expect(noPrice.incomplete).toBe(true); | ||
| expect(costScore(noPrice)).toBeNull(); | ||
|
|
||
| const noUsage = costEvidenceForCandidate({ provider: "anthropic", model: "claude-opus-5" }); | ||
| expect(noUsage.estimatedUsd).toBeUndefined(); | ||
| expect(noUsage.incomplete).toBe(true); | ||
| expect(costScore(noUsage)).toBeNull(); | ||
| }); | ||
|
|
||
| test("hard maximum estimated cost excludes candidates and records the limit", async () => { | ||
| const limited = config({ | ||
| routingProfiles: { | ||
| cost: { | ||
| candidates: [{ provider: "anthropic", model: "claude-opus-5" }], | ||
| optimize: { cost: 0.8 }, | ||
| limits: { maxEstimatedCostUsd: 0.000001 }, | ||
| unknownEvidence: { capability: "allow", health: "penalize", quota: "penalize", cost: "penalize" }, | ||
| }, | ||
| }, | ||
| }); | ||
| const evidence = costEvidenceForCandidate({ | ||
| provider: "anthropic", | ||
| model: "claude-opus-5", | ||
| usage: USAGE, | ||
| limitUsd: 0.000001, | ||
| }); | ||
| expect(evidence.limitUsd).toBe(0.000001); | ||
|
|
||
| const result = evaluatePolicyProfile(limited, "cost", {}, [ | ||
| { provider: "anthropic", model: "claude-opus-5", capability: { contextWindow: 200000 }, cost: evidence }, | ||
| ]); | ||
| expect(result.candidates[0]!.eligible).toBe(false); | ||
| expect(result.candidates[0]!.exclusions.some(exclusion => exclusion.code === "cost-limit")).toBe(true); | ||
| expect(result.selectedIndex).toBeNull(); | ||
| }); | ||
|
|
||
| test("unknown cost follows the profile policy (exclude / penalize / allow)", async () => { | ||
| const strict = config({ | ||
| routingProfiles: { | ||
| c: { | ||
| candidates: [{ provider: "a", model: "m1" }], | ||
| unknownEvidence: { capability: "allow", health: "penalize", quota: "penalize", cost: "exclude" }, | ||
| }, | ||
| }, | ||
| }); | ||
| const excluded = evaluatePolicyProfile(strict, "c", {}, [ | ||
| { provider: "a", model: "m1", capability: { contextWindow: 200000 } }, | ||
| ]); | ||
| expect(excluded.candidates[0]!.eligible).toBe(false); | ||
| expect(excluded.candidates[0]!.exclusions.some(exclusion => exclusion.code === "unknown-price")).toBe(true); | ||
|
|
||
| const penalizing = config({ | ||
| routingProfiles: { | ||
| c: { | ||
| candidates: [{ provider: "a", model: "m1" }], | ||
| unknownEvidence: { capability: "allow", health: "penalize", quota: "penalize", cost: "penalize" }, | ||
| }, | ||
| }, | ||
| }); | ||
| const penalized = evaluatePolicyProfile(penalizing, "c", {}, [ | ||
| { provider: "a", model: "m1", capability: { contextWindow: 200000 } }, | ||
| ]); | ||
| expect(penalized.candidates[0]!.eligible).toBe(true); | ||
| expect(penalized.candidates[0]!.score!.components.cost).toBe(COST_UNKNOWN_PENALTY_SCORE); | ||
|
|
||
| const allowing = config({ | ||
| routingProfiles: { | ||
| c: { | ||
| candidates: [{ provider: "a", model: "m1" }], | ||
| unknownEvidence: { capability: "allow", health: "penalize", quota: "penalize", cost: "allow" }, | ||
| }, | ||
| }, | ||
| }); | ||
| const allowed = evaluatePolicyProfile(allowing, "c", {}, [ | ||
| { provider: "a", model: "m1", capability: { contextWindow: 200000 } }, | ||
| ]); | ||
| expect(allowed.candidates[0]!.eligible).toBe(true); | ||
| // Allowed-unknown cost: no cost component, and the unspent cost weight | ||
| // folds back into priority instead of scoring unknown as zero. | ||
| expect(allowed.candidates[0]!.score!.components.cost).toBeUndefined(); | ||
| expect(allowed.candidates[0]!.score!.total).toBeGreaterThan(0); | ||
| }); | ||
|
Wibias marked this conversation as resolved.
|
||
|
|
||
| test("cheaper candidates win when cost is weighted", async () => { | ||
| const expensive = costEvidenceForCandidate({ | ||
| provider: "anthropic", | ||
| model: "claude-opus-5", | ||
| usage: { inputTokens: 200_000, outputTokens: 20_000, estimated: true }, | ||
| }); | ||
| const cheap = costEvidenceForCandidate({ | ||
| provider: "anthropic", | ||
| model: "claude-sonnet-5", | ||
| usage: { inputTokens: 2_000, outputTokens: 200, estimated: true }, | ||
| }); | ||
| const result = evaluatePolicyProfile(config(), "cost", {}, [ | ||
| { provider: "anthropic", model: "claude-opus-5", capability: { contextWindow: 200000 }, cost: expensive }, | ||
| { provider: "anthropic", model: "claude-sonnet-5", capability: { contextWindow: 200000 }, cost: cheap }, | ||
| ]); | ||
| expect(result.selectedIndex).toBe(1); | ||
| expect(result.candidates[1]!.score!.components.cost).toBeGreaterThan(result.candidates[0]!.score!.components.cost!); | ||
| }); | ||
|
|
||
| test("trace carries cost evidence and the cost component", async () => { | ||
| const evidence = costEvidenceForCandidate({ provider: "anthropic", model: "claude-opus-5", usage: USAGE }); | ||
| const result = evaluatePolicyProfile(config(), "cost", {}, [ | ||
| { provider: "anthropic", model: "claude-opus-5", capability: { contextWindow: 200000 }, cost: evidence }, | ||
| { provider: "anthropic", model: "claude-sonnet-5", capability: { contextWindow: 200000 } }, | ||
| ]); | ||
| expect(result.trace.candidates[0]!.cost).toBeDefined(); | ||
| expect(result.trace.candidates[0]!.score!.components.cost).toBeDefined(); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.