Files
OmniRoute/scripts/router-eval/compare.ts
KooshaPari f8e56e4615 fix(router-eval): retained-optimization gate cleanup (#7318)
* feat(eval): add router-eval harness (AIQ scoring, regression gate, Pareto search)

Extracts a standalone router-eval evaluation tool that replays routing
decisions (from NDJSON corpora or the usage_history/call_logs SQLite
tables) into an AIQ (success/latency/cost) score, compares baseline vs.
candidate router configs with a retained-run regression gate, and ranks
Pareto-optimal candidates across a search space — a sibling to the
existing eval:compression harness.

New scripts: scripts/router-eval/{index,compare,patch-compare,search,
trends}.ts, scripts/check/check-router-eval-regression.ts, and
src/lib/routerEval/index.ts, wired via 6 new package.json entries
(eval:router, eval:router:compare, eval:router:patch-compare,
eval:router:search, eval:router:trends, check:router-eval).

Reconstructed onto current release/v3.8.49 from the original ~142-commit
stale PR branch: only the genuinely new router-eval payload (17 files)
was extracted — the other ~560 changed files in the original diff were
base-drift already present on release in newer form. The new package.json
scripts now invoke `node --import tsx` instead of `bun`, matching the
`eval:compression` precedent (Bun is reserved for a closed 5-script
allowlist). The runtime-detection shim (`"Bun" in globalThis`) already
present in the harness gracefully falls back to better-sqlite3 under
Node, so no logic changes were needed there; the retained-run manifest's
previously-hardcoded `runtime: "bun"` field and matching CLI help text
were corrected to reflect the actual invocation.

All 27 existing router-eval unit tests pass unchanged.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* refactor(router-eval): decompose toRouterObservation below complexity gate

toRouterObservation had cyclomatic complexity 18 (gate max is 15). Extract
the per-field parsing/normalization into pure helpers (sampleId, model
fields, latency, cost derivation, success) so the entry point is a plain
sequential assembly of a RouterObservation. Behavior is unchanged — same
tests pass, same fallbacks, same precedence between input aliases.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
2026-07-18 15:13:39 -03:00

136 lines
4.0 KiB
JavaScript

#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
type Args = {
baseline: string;
candidate: string;
baselineName: string;
candidateName: string;
artifactDir: string;
runId: string;
maxAiqDrop: string;
maxCostIncrease: string;
failOnRegression: boolean;
};
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const isBunRuntime = "Bun" in globalThis;
function runTypeScriptScript(args: string[]) {
return spawnSync(process.execPath, isBunRuntime ? args : ["--import", "tsx", ...args], {
cwd: repoRoot,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
}
function getArgValue(name: string): string | undefined {
const index = process.argv.indexOf(`--${name}`);
if (index < 0) return undefined;
const value = process.argv[index + 1];
return value && !value.startsWith("--") ? value : undefined;
}
function usage(): string {
return [
"Usage:",
" npm run eval:router:compare -- --baseline <baseline.ndjson> --candidate <candidate.ndjson>",
" [--baseline-name <name>] [--candidate-name <name>] [--artifact-dir <dir>]",
" [--run-id <id>] [--max-aiq-drop <n>] [--max-cost-increase <n>] [--fail-on-regression]",
"",
"Runs a named baseline-vs-candidate router-eval comparison and retains artifacts.",
].join("\n");
}
function requireArg(name: string): string {
const value = getArgValue(name);
if (!value) {
console.error(`Missing required --${name}`);
process.exit(2);
}
return value;
}
function readArgs(): Args {
const baselineName = getArgValue("baseline-name") ?? "baseline";
const candidateName = getArgValue("candidate-name") ?? "candidate";
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
return {
baseline: requireArg("baseline"),
candidate: requireArg("candidate"),
baselineName,
candidateName,
artifactDir: getArgValue("artifact-dir") ?? "artifacts/router-eval/comparisons",
runId: getArgValue("run-id") ?? `${baselineName}-vs-${candidateName}-${timestamp}`,
maxAiqDrop: getArgValue("max-aiq-drop") ?? "1",
maxCostIncrease: getArgValue("max-cost-increase") ?? "0.05",
failOnRegression: process.argv.includes("--fail-on-regression"),
};
}
function ensureReadable(filePath: string, label: string): void {
if (!fs.existsSync(filePath)) {
console.error(`[router-eval:compare] ${label} missing: ${filePath}`);
process.exit(2);
}
}
function main(): void {
if (process.argv.includes("--help") || process.argv.includes("-h")) {
console.log(usage());
return;
}
const args = readArgs();
ensureReadable(args.baseline, "baseline corpus");
ensureReadable(args.candidate, "candidate corpus");
const checkArgs = [
"scripts/check/check-router-eval-regression.ts",
"--baseline",
args.baseline,
"--candidate",
args.candidate,
"--artifact-dir",
args.artifactDir,
"--run-id",
args.runId,
"--max-aiq-drop",
args.maxAiqDrop,
"--max-cost-increase",
args.maxCostIncrease,
];
const result = runTypeScriptScript(checkArgs);
if (result.error) {
console.error(`[router-eval:compare] failed to launch comparison: ${result.error.message}`);
process.exit(1);
}
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
const runDir = path.resolve(args.artifactDir, args.runId);
const labels = {
baselineName: args.baselineName,
candidateName: args.candidateName,
baseline: path.relative(runDir, path.resolve(args.baseline)),
candidate: path.relative(runDir, path.resolve(args.candidate)),
};
fs.mkdirSync(runDir, { recursive: true });
fs.writeFileSync(path.join(runDir, "comparison.json"), `${JSON.stringify(labels, null, 2)}\n`);
if (result.status === 0 || !args.failOnRegression) {
console.log(`[router-eval:compare] artifacts: ${runDir}`);
return;
}
process.exit(result.status ?? 1);
}
main();