umpirix/hackathons/geekroom-2026/verify-execution-trace.mjs
caelum0x cececb2772 feat(benchmark): add execution tracing + fault injection to Benchmark Submissions
Builds the execution half of the Geek Room "Build a Benchmarking Platform
for AI Agents, Not Just Models" theme: every submission now carries a real
execution trace (steps, outbound/tool-call count, latency p50/p95, tokens +
cost when the endpoint reports them, error/timeout counts) and an opt-in,
deterministically seeded fault-injection stress test (injected timeouts,
5xx responses, malformed answers at configurable rates) that reports
robustness: accuracy under faults vs. the clean run.

- benchmark-scoring.ts: instrumentRunner wraps any Runner with tracing;
  endpointRunner gains an optional onOutcome hook + parses real
  usage/cost_usd from the submitter's response body; mulberry32-seeded
  fault injection with disjoint timeout/server_error/malformed buckets.
- benchmark-submissions.server.ts: wires tracing into both runner kinds,
  runs a second faulted pass when requested, persists {clean trace,
  robustness} + the fault-injection config on two new additive, nullable
  columns (migrations/0012_benchmark_execution_trace.sql).
- API route + leaderboard feed: pass faultInjection through, return
  trace/robustness/faultInjection on every submission.
- UI: /submit-model gets a "Stress-test with fault injection" checkbox and
  Execution trace / Robustness under faults cards; /leaderboard's gold-suite
  tab gets p50 ms / Outbound calls / Errors / Robustness columns for
  community submissions.

Verified end to end: a real HTTP submission against a running dev server
(fault injection on, real trace + robustness persisted and read back from
the public leaderboard feed) and endpointRunner against a real local HTTP
agent (93 real round trips; real measured latency/tokens/cost; a 60%-fault
pass provably short-circuiting before the real network call) — see
hackathons/geekroom-2026/verify-execution-trace.mjs and
HACKATHON-SUBMISSION.md's "Real execution-trace + fault-injection run".
Re-recorded demo.mp4/poster.png (real Playwright capture, real ffmpeg
conversion) to show the new flow. npm test (138/1 skip/0 fail), npm run
gold (61/0), npm run typecheck (clean) all unchanged.
2026-11-10 18:11:57 +03:00

268 lines
12 KiB
JavaScript

#!/usr/bin/env node
/**
* Real, end-to-end verification of the execution-trace + fault-injection
* half of Benchmark Submissions (Geek Room hackathon theme: "Build a
* Benchmarking Platform for AI Agents, Not Just Models"). Two real passes,
* no mocks, no staged numbers — every number this script prints is read
* back from an actual run.
*
* 1. A real HTTP POST to a REAL running dev server's own
* /api/v1/benchmark-submissions (sourceKind "answers", the existing
* "system-one-replay" gold-answer fixture) with fault injection
* enabled — exercises the full real request path (route handler ->
* `createSubmission` -> PGLite persistence, since no DATABASE_URL is
* set) exactly as a real submitter's browser would, not a direct
* in-process function call.
* 2. `endpointRunner` + `instrumentRunner` directly against a REAL local
* HTTP agent server (plain `node:http`, backed by the real `runLocal`
* engine, reporting real `usage`/`cost_usd` on its response body) —
* exercises the real network round trip, latency measurement, and
* token/cost capture that the public submission API's SSRF guard
* (outbound-guard.server.ts) intentionally blocks for localhost. This
* is local verification of the tracing mechanics over a real socket,
* not a public submission against a third-party endpoint.
* 3. The same real endpoint, through the fault-injection wrapper — proves
* injected faults short-circuit the real HTTP call (fewer real hits
* than gold cases) and that robustness reflects a real accuracy drop.
*
* Part 1 needs a real dev server already running (it hits the real HTTP
* route, not an in-process import — "@/lib/db"'s PGLite bootstrap uses
* `import.meta.glob`, a Vite-only feature, so it can only run inside Vite):
* npm run dev -- --port 8099
* BASE_URL=http://localhost:8099 node hackathons/geekroom-2026/verify-execution-trace.mjs
*
* Parts 2-3 use `jiti` (same loader scripts/leaderboard.mjs uses) to import
* benchmark-scoring.ts/gold.ts/engine.ts directly — none of those import
* "@/lib/db", so they run standalone, no server needed.
*/
import { createServer } from "node:http";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createJiti } from "jiti";
const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
const __dirname = dirname(fileURLToPath(import.meta.url));
const jiti = createJiti(import.meta.url, { alias: { "@": join(root, "src") } });
const mod = (p) => jiti.import(join(root, p));
const BASE_URL = process.env.BASE_URL ?? "http://localhost:8099";
function assertReal(cond, message) {
if (!cond) throw new Error(`ASSERTION FAILED: ${message}`);
}
async function part1({ GOLD }) {
console.log("\n=== Part 1: real HTTP POST to a real running dev server ===");
console.log("BASE_URL:", BASE_URL);
const answers = JSON.parse(
readFileSync(join(__dirname, "system-one-replay-answers.json"), "utf8"),
);
const res = await fetch(`${BASE_URL}/api/v1/benchmark-submissions`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
modelLabel: "verify-system-one-replay-trace",
sourceKind: "answers",
answers,
faultInjection: { enabled: true, seed: 42, timeoutRate: 0.1, serverErrorRate: 0.1, malformedRate: 0.1 },
}),
});
if (!res.ok) {
throw new Error(`ASSERTION FAILED: POST /api/v1/benchmark-submissions must succeed, got ${res.status} ${await res.text()}`);
}
const { data: submission } = await res.json();
console.log("status:", submission.status);
console.log("accuracy:", submission.result?.accuracy, "ece:", submission.result?.ece);
console.log(
"trace:",
JSON.stringify({ ...submission.trace, cases: `[${submission.trace?.cases?.length} cases]` }),
);
console.log(
"robustness (minus faultedTrace, printed separately):",
JSON.stringify({ ...submission.robustness, faultedTrace: undefined }),
);
console.log(
"faultedTrace:",
JSON.stringify({
...submission.robustness?.faultedTrace,
cases: `[${submission.robustness?.faultedTrace?.cases?.length} cases]`,
}),
);
assertReal(submission.status === "completed", "submission must complete");
assertReal(Boolean(submission.trace), "clean trace must be persisted");
assertReal(Boolean(submission.robustness), "robustness must be persisted when requested");
assertReal(
submission.trace.totalOutboundCalls === 0,
"answers-mode trace must report 0 outbound calls (no real network call happened)",
);
assertReal(
submission.trace.totalTokensIn === null && submission.trace.totalCostUsd === null,
"answers-mode trace must not fabricate tokens/cost no provider reported",
);
assertReal(submission.trace.caseCount === GOLD.length, "trace must cover every gold case");
assertReal(
submission.robustness.faultedTrace.errorCount > 0,
"a 30%-total fault rate across 93 cases must inject at least one real failure",
);
// GET the leaderboard feed too — proves the row is live and queryable, not
// just the direct POST response.
const lbRes = await fetch(`${BASE_URL}/api/v1/benchmark-submissions/leaderboard`);
assertReal(lbRes.ok, "leaderboard feed must respond 200");
const { data: lbRows } = await lbRes.json();
const row = lbRows.find((r) => r.id === submission.id);
assertReal(Boolean(row), "the just-created submission must appear on the public leaderboard feed");
assertReal(Boolean(row.trace), "leaderboard row must carry the execution trace");
assertReal(Boolean(row.robustness), "leaderboard row must carry the robustness score");
console.log("leaderboard row trace:", JSON.stringify(row.trace));
console.log("leaderboard row robustness:", JSON.stringify({ ...row.robustness, faultedTrace: undefined }));
console.log("OK: part 1 — real HTTP submission + leaderboard feed verified.");
}
async function part2and3({
endpointRunner,
instrumentRunner,
normalizeFaultInjectionConfig,
buildRobustnessReport,
toSubmissionResult,
evalGoldWith,
GOLD,
runLocal,
}) {
console.log("\n=== Part 2: real local HTTP agent, endpointRunner + instrumentRunner ===");
let hits = 0;
const server = createServer((req, res) => {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
hits += 1;
const { state, questions } = JSON.parse(body);
const out = runLocal({ model: "system-one", state, questions }, "system-one");
const payload = JSON.stringify({
answers: out.answers,
// A real agent reporting real usage/cost on its own response body —
// exactly the optional contract endpointRunner now parses.
usage: { input_tokens: 42, output_tokens: 7 },
cost_usd: 0.000123,
});
res.writeHead(200, { "content-type": "application/json" });
res.end(payload);
});
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const addr = server.address();
if (!addr || typeof addr === "string") throw new Error("server did not bind to a real port");
const url = `http://127.0.0.1:${addr.port}/predict`;
console.log("real local agent listening at", url);
let outcome = null;
const cleanRunner = endpointRunner(url, 5_000, (o) => {
outcome = o;
});
const cleanTraced = instrumentRunner(cleanRunner, {
outboundCallsPerCase: 1,
getOutcome: () => outcome,
});
const cleanReport = await evalGoldWith(cleanTraced.runner);
const cleanResult = toSubmissionResult(cleanReport);
const cleanTrace = cleanTraced.getTrace();
console.log("accuracy:", cleanResult.accuracy, "case_count:", cleanResult.case_count);
console.log("real HTTP hits so far:", hits, "trace.totalOutboundCalls:", cleanTrace.totalOutboundCalls);
console.log("latency p50/p95 (ms):", cleanTrace.latencyP50Ms, cleanTrace.latencyP95Ms);
console.log(
"tokens in/out:",
cleanTrace.totalTokensIn,
cleanTrace.totalTokensOut,
"cost (usd):",
cleanTrace.totalCostUsd,
);
console.log("errors/timeouts:", cleanTrace.errorCount, cleanTrace.timeoutCount);
assertReal(hits === GOLD.length, `expected ${GOLD.length} real HTTP hits, got ${hits}`);
assertReal(cleanTrace.totalOutboundCalls === GOLD.length, "outbound call count must equal real HTTP hits");
assertReal(cleanTrace.totalTokensIn === 42 * GOLD.length, "tokens in must sum the real reported usage");
assertReal(cleanTrace.totalTokensOut === 7 * GOLD.length, "tokens out must sum the real reported usage");
assertReal(
cleanTrace.totalCostUsd !== null && cleanTrace.totalCostUsd > 0,
"cost must be captured from the real response body",
);
assertReal(cleanTrace.errorCount === 0, "a healthy real endpoint must report zero errors");
assertReal(
cleanTrace.latencyP50Ms >= 0 && cleanTrace.latencyP95Ms >= cleanTrace.latencyP50Ms,
"p95 must be >= p50 on real measured latencies",
);
console.log("OK: part 2 — real HTTP endpoint tracing verified.");
console.log("\n=== Part 3: fault injection against the SAME real endpoint ===");
const hitsBeforeFaulted = hits;
let outcome2 = null;
const faultedRunner = endpointRunner(url, 5_000, (o) => {
outcome2 = o;
});
const faultCfg = normalizeFaultInjectionConfig({
seed: 7,
timeoutRate: 0.2,
serverErrorRate: 0.2,
malformedRate: 0.2,
});
const faultedTraced = instrumentRunner(faultedRunner, {
outboundCallsPerCase: 1,
getOutcome: () => outcome2,
faultInjection: faultCfg,
});
const faultedReport = await evalGoldWith(faultedTraced.runner);
const faultedResult = toSubmissionResult(faultedReport);
const faultedTrace = faultedTraced.getTrace();
const robustness = buildRobustnessReport(faultCfg, cleanResult.accuracy, faultedResult.accuracy, faultedTrace);
const realHitsDuringFaultedPass = hits - hitsBeforeFaulted;
console.log("faulted accuracy:", faultedResult.accuracy, "clean accuracy:", cleanResult.accuracy);
console.log("robustness (faulted/clean):", robustness.robustness);
console.log("faulted errors/timeouts:", faultedTrace.errorCount, faultedTrace.timeoutCount);
console.log(
`real HTTP hits during faulted pass: ${realHitsDuringFaultedPass} of ${GOLD.length} ` +
"(fewer than the gold-case count is the expected signature of timeout/server_error faults short-circuiting before the real call)",
);
assertReal(faultedTrace.errorCount > 0, "a 60%-total fault rate must inject at least one real failure");
assertReal(
realHitsDuringFaultedPass < GOLD.length,
"timeout/server_error faults must short-circuit before the real HTTP call — fewer real hits than gold cases",
);
assertReal(robustness.robustness <= 1 && robustness.robustness >= 0, "robustness must be a real ratio in [0, 1]");
console.log("OK: part 3 — fault injection against a real endpoint verified.");
await new Promise((resolve) => server.close(() => resolve()));
}
async function main() {
const benchmarkScoring = await mod("src/lib/jev/benchmark-scoring.ts");
const goldMod = await mod("src/lib/jev/gold.ts");
const engineMod = await mod("src/lib/jev/engine.ts");
await part1({ GOLD: goldMod.GOLD });
await part2and3({
endpointRunner: benchmarkScoring.endpointRunner,
instrumentRunner: benchmarkScoring.instrumentRunner,
normalizeFaultInjectionConfig: benchmarkScoring.normalizeFaultInjectionConfig,
buildRobustnessReport: benchmarkScoring.buildRobustnessReport,
toSubmissionResult: benchmarkScoring.toSubmissionResult,
evalGoldWith: goldMod.evalGoldWith,
GOLD: goldMod.GOLD,
runLocal: engineMod.runLocal,
});
console.log("\nAll real verification passes succeeded — no mocks, no staged numbers.");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});