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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
Expand Down Expand Up @@ -135,6 +135,7 @@ const keyEntry = (
api_key_id,
max_turns: 200,
stopped_at: null,
attempt_count: null,
key_alias: null,
key_name: null,
...overrides,
Expand Down Expand Up @@ -359,15 +360,19 @@ describe("ShadowEvalSection", () => {
expect(container).toBeEmptyDOMElement();
});

it("keeps the start button disabled until key, router, and judge model are picked, then submits the key as a list", async () => {
it("keeps the start button disabled until key, router, and judge model are picked, then submits every picked key", async () => {
const user = userEvent.setup();
const { start } = mockHooks({});
render(<ShadowEvalSection />);

expect(screen.getByText("Start shadow eval")).toBeDisabled();

await user.click(screen.getByPlaceholderText("Search keys by alias"));
await user.click(await screen.findByText("prod-alpha"));
const keyInput = screen.getByPlaceholderText("Search keys by alias");
await user.click(keyInput);
const keyList = await screen.findByTestId("paginated-multi-select-list");
await user.click(within(keyList).getByText("prod-alpha"));
await user.click(keyInput);
await user.click(within(keyList).getByText("staging-beta"));
await user.click(screen.getByPlaceholderText("Select an auto-router"));
await user.click(await screen.findByText("gpt-auto"));

Expand All @@ -378,7 +383,7 @@ describe("ShadowEvalSection", () => {
await user.click(screen.getByText("Start shadow eval"));

const expectedBody = {
api_key_ids: ["hash-alpha"],
api_key_ids: ["hash-alpha", "hash-beta"],
router_name: "gpt-auto",
direction: "forward",
shadow_percentage: 10,
Expand All @@ -399,7 +404,8 @@ describe("ShadowEvalSection", () => {
await user.click(screen.getByText("Adoption check: key's traffic vs the router"));
await user.click(await screen.findByText("Regression check: router's picks vs a baseline"));
await user.click(screen.getByPlaceholderText("Search keys by alias"));
await user.click(await screen.findByText("prod-alpha"));
const keyList = await screen.findByTestId("paginated-multi-select-list");
await user.click(within(keyList).getByText("prod-alpha"));
await user.click(screen.getByPlaceholderText("Select an auto-router"));
await user.click(await screen.findByText("gpt-auto"));
await user.click(screen.getByPlaceholderText("Select a judge model"));
Expand Down Expand Up @@ -451,6 +457,119 @@ describe("ShadowEvalSection", () => {
expect(shadowedKeyLabel(keyEntry("hashed-key-abc"))).toBe("hashed-key…");
});

it("breaks results down per key, so one key exhausting its own budget is visible while a sibling runs on", () => {
mockHooks({
jobs: [
job({
judged_count: 205,
keys: [
keyEntry("hash-spent", { max_turns: 200, stopped_at: "2026-08-08T00:00:00Z" }),
keyEntry("hash-hungry", { max_turns: 500 }),
],
results: {
by_tier: [],
by_current_model: [],
by_key: [
{
group: "hash-spent",
turn_count: 200,
real_win_rate_pct: 20.0,
shadow_win_rate_pct: 60.0,
tie_rate_pct: 20.0,
avg_judge_confidence: 0.9,
},
],
overall_shadow_win_rate_pct: 60.0,
overall_tie_rate_pct: 20.0,
},
}),
],
});
render(<ShadowEvalSection />);

const spent = screen.getByText("hash-spent…").closest("tr");
const hungry = screen.getByText("hash-hungr…").closest("tr");
if (!spent || !hungry) throw new Error("expected a table row per scoped key");

expect(within(spent).getByText("stopped")).toBeInTheDocument();
expect(within(spent).getByText("200 / 200")).toBeInTheDocument();
expect(within(spent).getByText("60.0%")).toBeInTheDocument();

expect(within(hungry).getByText("running")).toBeInTheDocument();
expect(within(hungry).getByText("0 / 500")).toBeInTheDocument();
expect(within(hungry).getByText("No verdicts yet")).toBeInTheDocument();

expect(screen.getByText(/205 of 700 turns judged/)).toBeInTheDocument();
expect(screen.getByText(/Shadowing 10% of/)).toBeInTheDocument();
expect(screen.getByText("2 keys")).toBeInTheDocument();
});

it("reads a key that spent its budget as completed even before the sweep stamps it", () => {
mockHooks({
jobs: [
job({
keys: [
keyEntry("hash-spent", { max_turns: 200, attempt_count: 200 }),
keyEntry("hash-hungry", { max_turns: 500, attempt_count: 3 }),
],
}),
],
});
render(<ShadowEvalSection />);

const spent = screen.getByText("hash-spent…").closest("tr");
const hungry = screen.getByText("hash-hungr…").closest("tr");
if (!spent || !hungry) throw new Error("expected a table row per scoped key");
expect(within(spent).getByText("completed")).toBeInTheDocument();
expect(within(spent).getByText("200 / 200")).toBeInTheDocument();
expect(within(hungry).getByText("running")).toBeInTheDocument();
expect(within(hungry).getByText("3 / 500")).toBeInTheDocument();
});

it("shows the per-key table while a multi-key job is still collecting, before any verdicts exist", () => {
mockHooks({
jobs: [
job({
judged_count: 0,
results: null,
keys: [
keyEntry("hash-spent", { max_turns: 2, attempt_count: 2 }),
keyEntry("hash-hungry", { max_turns: 500, attempt_count: 1 }),
],
}),
],
});
render(<ShadowEvalSection />);

const spent = screen.getByText("hash-spent…").closest("tr");
if (!spent) throw new Error("expected a per-key row before verdicts exist");
expect(within(spent).getByText("completed")).toBeInTheDocument();
expect(within(spent).getByText("2 / 2")).toBeInTheDocument();
expect(screen.getByText("Budget used")).toBeInTheDocument();
expect(screen.queryByText("Judged turns")).not.toBeInTheDocument();
expect(screen.getByText(/Collecting verdicts/)).toBeInTheDocument();
});

it("reads every key as completed once the job's window closes, whatever its own stop state", () => {
mockHooks({
jobs: [
job({
status: "completed",
keys: [
keyEntry("hash-spent", { max_turns: 200, stopped_at: "2026-08-08T00:00:00Z" }),
keyEntry("hash-hungry", { max_turns: 500 }),
],
}),
],
});
render(<ShadowEvalSection />);

const hungry = screen.getByText("hash-hungr…").closest("tr");
if (!hungry) throw new Error("expected a table row per scoped key");
expect(within(hungry).getByText("completed")).toBeInTheDocument();
expect(within(hungry).queryByText("running")).not.toBeInTheDocument();
});

it("keeps an older job's verdicts reachable through the previous evaluations list", async () => {
const user = userEvent.setup();
const emptyOverrides: Partial<ShadowEvalJob> = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useInfiniteKeys } from "@/app/(dashboard)/hooks/keys/useKeys";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useModelCostMap } from "@/app/(dashboard)/hooks/models/useModelCostMap";
import { useAutoRouters, usePlainModelGroups } from "@/app/(dashboard)/hooks/models/useModels";
import { PaginatedSearchSelect } from "@/components/shared/PaginatedSearchSelect";
import { PaginatedMultiSelect } from "@/components/shared/PaginatedMultiSelect";
import { SearchSelect, type SearchSelectOption } from "@/components/shared/SearchSelect";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
Expand Down Expand Up @@ -59,6 +59,13 @@ const shadowedKeysLabel = (job: ShadowEvalJob): string =>

const totalBudget = (job: ShadowEvalJob): number => job.keys.reduce((sum, key) => sum + key.max_turns, 0);

const keySpent = (key: ShadowEvalJobKey): boolean => key.attempt_count != null && key.attempt_count >= key.max_turns;

const keyStatus = (job: ShadowEvalJob, key: ShadowEvalJobKey): string => {
if (job.status === "completed" || (key.stopped_at == null && keySpent(key))) return "completed";
return key.stopped_at != null ? "stopped" : "running";
};
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

const jobHeadline = (job: ShadowEvalJob): React.ReactNode =>
job.direction === "reverse" ? (
<>
Expand Down Expand Up @@ -175,6 +182,55 @@ const VerdictBar: React.FC<{ direction: ShadowEvalDirection; results: NonNullabl
);
};

const KeyTable: React.FC<{ job: ShadowEvalJob }> = ({ job }) => {
const slices = new Map((job.results?.by_key ?? []).map((slice) => [slice.group, slice]));
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>Key</TableHead>
<TableHead>Status</TableHead>
{["Budget used", "Router wins", `${otherArmLabel(job.direction)} wins`].map((label) => (
<TableHead key={label} className="text-right">
{label}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{job.keys.map((key) => {
const slice = slices.get(key.api_key_id);
return (
<TableRow key={key.api_key_id}>
<TableCell className="font-medium text-foreground">{shadowedKeyLabel(key)}</TableCell>
<TableCell>
<StatusBadge status={keyStatus(job, key)} />
</TableCell>
<TableCell className="text-right tabular-nums">
{(key.attempt_count ?? slice?.turn_count ?? 0).toLocaleString()} / {key.max_turns.toLocaleString()}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
</TableCell>
{slice ? (
<>
<TableCell className="text-right font-medium tabular-nums text-foreground">
{pct(routerWinRate(job.direction, slice))}
</TableCell>
<TableCell className="text-right tabular-nums">
{pct(otherArmWinRate(job.direction, slice))}
</TableCell>
</>
) : (
<TableCell colSpan={2} className="text-right text-muted-foreground">
No verdicts yet
</TableCell>
)}
</TableRow>
);
})}
</TableBody>
</Table>
);
};

const emptyResultsText = (job: ShadowEvalJob, resultsError: boolean): string => {
if (resultsError) return "Results could not be loaded. Retrying.";
if (isActive(job)) return "Collecting verdicts. Results appear as sampled requests are judged.";
Expand All @@ -184,32 +240,45 @@ const emptyResultsText = (job: ShadowEvalJob, resultsError: boolean): string =>

const ResultsBody: React.FC<{ job: ShadowEvalJob; resultsError?: boolean }> = ({ job, resultsError = false }) => {
const results = job.results;
const stratifications = results ? [results.by_tier, results.by_current_model, results.by_key] : [];
if (!results || stratifications.every((slices) => slices.length === 0)) {
return <p className="px-6 py-8 text-center text-sm text-muted-foreground">{emptyResultsText(job, resultsError)}</p>;
}
const hasVerdicts = results != null && (results.by_tier.length > 0 || results.by_current_model.length > 0);
return (
<>
<div className="flex flex-col gap-1 border-b px-6 py-4">
<p className="text-[11px] uppercase tracking-wide text-muted-foreground">
Router matched or beat {job.direction === "reverse" ? "the baseline" : "your current model"}
</p>
<p className="text-3xl font-semibold text-foreground">{pct(routerMatchedOrBeatPct(job.direction, results))}</p>
<p className="text-xs text-muted-foreground">of {(job.judged_count ?? 0).toLocaleString()} judged responses</p>
</div>
<VerdictBar direction={job.direction} results={results} />
{results.by_current_model.length > 0 && (
<SliceTable
groupHeader={job.direction === "reverse" ? "Router pick" : "Compared against"}
direction={job.direction}
slices={results.by_current_model}
/>
)}
{results.by_tier.length > 0 && (
<div className={results.by_current_model.length > 0 ? "border-t" : ""}>
<SliceTable groupHeader="Prompt difficulty" direction={job.direction} slices={results.by_tier} />
{job.keys.length > 1 && (
<div className="border-b">
<KeyTable job={job} />
</div>
)}
{/* results == null re-stated for TS narrowing; hasVerdicts alone cannot narrow it */}
{!hasVerdicts || results == null ? (
<p className="px-6 py-8 text-center text-sm text-muted-foreground">{emptyResultsText(job, resultsError)}</p>
) : (
<>
<div className="flex flex-col gap-1 border-b px-6 py-4">
<p className="text-[11px] uppercase tracking-wide text-muted-foreground">
Router matched or beat {job.direction === "reverse" ? "the baseline" : "your current model"}
</p>
<p className="text-3xl font-semibold text-foreground">
{pct(routerMatchedOrBeatPct(job.direction, results))}
</p>
<p className="text-xs text-muted-foreground">
of {(job.judged_count ?? 0).toLocaleString()} judged responses
</p>
</div>
<VerdictBar direction={job.direction} results={results} />
{results.by_current_model.length > 0 && (
<SliceTable
groupHeader={job.direction === "reverse" ? "Router pick" : "Compared against"}
direction={job.direction}
slices={results.by_current_model}
/>
)}
{results.by_tier.length > 0 && (
<div className={results.by_current_model.length > 0 ? "border-t" : ""}>
<SliceTable groupHeader="Prompt difficulty" direction={job.direction} slices={results.by_tier} />
</div>
)}
</>
)}
</>
);
};
Expand Down Expand Up @@ -306,9 +375,9 @@ const DIRECTION_OPTIONS: readonly { value: ShadowEvalDirection; label: string }[

const START_FORM_DESCRIPTION: Record<ShadowEvalDirection, string> = {
forward:
"Duplicates a sampled slice of the key's traffic through the auto-router and has an LLM judge compare both answers blind. The router's answers are never served to users; judge calls bill to the shadowed key.",
"Duplicates a sampled slice of the selected keys' traffic through the auto-router and has an LLM judge compare both answers blind. Each key gets its own turn budget. The router's answers are never served to users; judge calls bill to the shadowed key.",
reverse:
"Duplicates a sampled slice of the traffic the auto-router already serves against a fixed baseline model and has an LLM judge compare both answers blind. The baseline's answers are never served to users; judge calls bill to the shadowed key.",
"Duplicates a sampled slice of the traffic the auto-router already serves against a fixed baseline model and has an LLM judge compare both answers blind. Each key gets its own turn budget. The baseline's answers are never served to users; judge calls bill to the shadowed key.",
};

const DURATION_OPTIONS = [
Expand All @@ -333,7 +402,7 @@ const Field: React.FC<{ label: string; htmlFor?: string; className?: string; chi
</div>
);

const KeySelect: React.FC<{ value: string; onChange: (token: string) => void }> = ({ value, onChange }) => {
const KeySelect: React.FC<{ value: string[]; onChange: (tokens: string[]) => void }> = ({ value, onChange }) => {
const [search, setSearch] = useState("");
const { data, isPending, isError, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteKeys(50, {
selectedKeyAlias: search || null,
Expand All @@ -350,7 +419,7 @@ const KeySelect: React.FC<{ value: string; onChange: (token: string) => void }>
[data],
);
return (
<PaginatedSearchSelect
<PaginatedMultiSelect
inputId="shadow-eval-key"
options={options}
value={value}
Expand All @@ -369,7 +438,7 @@ const KeySelect: React.FC<{ value: string; onChange: (token: string) => void }>

const StartForm: React.FC = () => {
const { accessToken } = useAuthorized();
const [apiKeyId, setApiKeyId] = useState("");
const [apiKeyIds, setApiKeyIds] = useState<string[]>([]);
const [routerName, setRouterName] = useState("");
const [direction, setDirection] = useState<ShadowEvalDirection>("forward");
const [baselineModel, setBaselineModel] = useState("");
Expand All @@ -394,12 +463,12 @@ const StartForm: React.FC = () => {
const parsedMaxTurns = Number.parseInt(maxTurns, 10);
const maxTurnsValid = parsedMaxTurns >= 1 && parsedMaxTurns <= 2000;
const baselinePicked = direction === "forward" || baselineModel !== "";
const filled = [apiKeyId, routerName, judgeModel].every((field) => field !== "") && baselinePicked;
const filled = apiKeyIds.length > 0 && [routerName, judgeModel].every((field) => field !== "") && baselinePicked;
const boundsValid = percentageValid && maxTurnsValid;
const valid = Boolean(accessToken) && filled && boundsValid;
const handleStart = () => {
const startBody = {
api_key_ids: [apiKeyId],
api_key_ids: apiKeyIds,
router_name: routerName,
direction,
...(direction === "reverse" ? { baseline_model: baselineModel } : {}),
Expand Down Expand Up @@ -436,8 +505,8 @@ const StartForm: React.FC = () => {
</SelectContent>
</Select>
</Field>
<Field label="Key to shadow" htmlFor="shadow-eval-key">
<KeySelect value={apiKeyId} onChange={setApiKeyId} />
<Field label="Keys to shadow" htmlFor="shadow-eval-key">
<KeySelect value={apiKeyIds} onChange={setApiKeyIds} />
</Field>
<Field label="Auto-router">
<SearchSelect
Expand Down
Loading
Loading