Skip to content

🎥 Make videos programmatically with React

`@remotion/skills-evals`: Add batched eval runs (#7396)

Igor Samokhovetsa07d5a7dcd11
diff --git a/packages/skills-evals/README.md b/packages/skills-evals/README.md
index 4510034e8b..5a8521f7dd 100644
--- a/packages/skills-evals/README.md
+++ b/packages/skills-evals/README.md
@@ -2,4 +2,19 @@
## Usage
-This is an internal package and has no documentation.
+This is an internal package.
+
+Run a scenario once:
+
+```bash
+bun run eval run <scenario-id>
+```
+
+Run a scenario or comparison multiple times in parallel:
+
+```bash
+bun run eval run <scenario-id> --runs 4
+bun run eval compare <scenario-id> --runs 4
+```
+
+`--runs` accepts values from 1 to 4.
diff --git a/packages/skills-evals/src/app/comparison-data.ts b/packages/skills-evals/src/app/comparison-data.ts
index 5dcb008006..67d1366e60 100644
--- a/packages/skills-evals/src/app/comparison-data.ts
+++ b/packages/skills-evals/src/app/comparison-data.ts
@@ -9,6 +9,11 @@ export type ComparisonWithManifests = {
afterManifest: SkillEvalManifest;
beforeManifest: SkillEvalManifest;
comparison: SkillEvalComparison;
+ runs: {
+ afterManifest: SkillEvalManifest;
+ beforeManifest: SkillEvalManifest;
+ index: number;
+ }[];
skillDiff: string;
};
@@ -53,13 +58,43 @@ export const loadComparison = async (
}
const comparison = await readJson<SkillEvalComparison>(comparisonPath);
- const [beforeManifest, afterManifest, skillDiff] = await Promise.all([
- readJson<SkillEvalManifest>(comparison.before.manifestPath),
- readJson<SkillEvalManifest>(comparison.after.manifestPath),
+ const comparisonRuns = comparison.runs ?? [
+ {
+ after: comparison.after,
+ before: comparison.before,
+ index: 1,
+ },
+ ];
+ const [runManifests, skillDiff] = await Promise.all([
+ Promise.all(
+ comparisonRuns.map(async (run) => {
+ const [beforeManifest, afterManifest] = await Promise.all([
+ readJson<SkillEvalManifest>(run.before.manifestPath),
+ readJson<SkillEvalManifest>(run.after.manifestPath),
+ ]);
+
+ return {
+ afterManifest,
+ beforeManifest,
+ index: run.index,
+ };
+ }),
+ ),
readFile(comparison.skillDiffPath, 'utf-8'),
]);
+ const firstRun = runManifests[0];
+
+ if (!firstRun) {
+ return null;
+ }
- return {afterManifest, beforeManifest, comparison, skillDiff};
+ return {
+ afterManifest: firstRun.afterManifest,
+ beforeManifest: firstRun.beforeManifest,
+ comparison,
+ runs: runManifests,
+ skillDiff,
+ };
};
export const getPreferredArtifact = (manifest: SkillEvalManifest) =>
diff --git a/packages/skills-evals/src/app/comparison.tsx b/packages/skills-evals/src/app/comparison.tsx
index 782c58874e..f07f59c327 100644
--- a/packages/skills-evals/src/app/comparison.tsx
+++ b/packages/skills-evals/src/app/comparison.tsx
@@ -151,7 +151,9 @@ const ComparisonDiffScript = () => (
);
export const renderComparison = (comparisonData: ComparisonWithManifests) => {
- const {afterManifest, beforeManifest, comparison, skillDiff} = comparisonData;
+ const {afterManifest, beforeManifest, comparison, runs, skillDiff} =
+ comparisonData;
+ const hasBatch = runs.length > 1;
return page({
children: (
@@ -173,18 +175,40 @@ export const renderComparison = (comparisonData: ComparisonWithManifests) => {
title={comparison.scenarioId}
/>
<main className="grid min-w-0 gap-4">
- <div className="grid grid-cols-2 gap-3 max-lg:grid-cols-1">
- <RunPanel
- label={`Before (${comparison.before.gitRef ?? comparison.before.source})`}
- manifest={beforeManifest}
- manifestPath={comparison.before.manifestPath}
- />
- <RunPanel
- label="After"
- manifest={afterManifest}
- manifestPath={comparison.after.manifestPath}
- />
- </div>
+ {runs.map((run) => {
+ const runMetadata = comparison.runs?.find(
+ (candidate) => candidate.index === run.index,
+ );
+ const beforeMetadata = runMetadata?.before ?? comparison.before;
+
+ return (
+ <section className="grid min-w-0 gap-3" key={run.index}>
+ {hasBatch ? (
+ <h2 className="text-[0.9375rem] font-semibold">
+ Run #{run.index}
+ </h2>
+ ) : null}
+ <div className="grid grid-cols-2 gap-3 max-lg:grid-cols-1">
+ <RunPanel
+ label={`Before (${beforeMetadata.gitRef ?? beforeMetadata.source})`}
+ manifest={run.beforeManifest}
+ manifestPath={
+ runMetadata?.before.manifestPath ??
+ comparison.before.manifestPath
+ }
+ />
+ <RunPanel
+ label="After"
+ manifest={run.afterManifest}
+ manifestPath={
+ runMetadata?.after.manifestPath ??
+ comparison.after.manifestPath
+ }
+ />
+ </div>
+ </section>
+ );
+ })}
<details
className="min-w-0 rounded-2xl border border-zinc-200 bg-white p-4"
open
diff --git a/packages/skills-evals/src/app/jobs.ts b/packages/skills-evals/src/app/jobs.ts
index dc8f2c72d4..a8749c0998 100644
--- a/packages/skills-evals/src/app/jobs.ts
+++ b/packages/skills-evals/src/app/jobs.ts
@@ -5,13 +5,18 @@ import {
type SkillEvalComparisonEvent,
type SkillEvalComparisonRunLabel,
} from '../compare';
+import {
+ maxParallelSkillEvalRuns,
+ validateSkillEvalRunCount,
+} from '../run-count';
import {runSkillEval, type SkillEvalPhase} from '../run-skill-eval';
+import {runWithConcurrency} from '../run-with-concurrency';
import {toComparisonUrl} from './shared';
export type Job = {
id: string;
logs: string[];
- runs: Record<SkillEvalComparisonRunLabel, JobRun>;
+ runs: JobRunGroup[];
scenarioId: string;
startedAt: string;
status: 'running' | 'completed' | 'failed' | 'skipped';
@@ -19,6 +24,13 @@ export type Job = {
error?: string;
message?: string;
resultUrl?: string;
+ runCount: number;
+};
+
+export type JobRunGroup = {
+ after: JobRun;
+ before: JobRun;
+ index: number;
};
export type JobRun = {
@@ -42,13 +54,12 @@ const createJobRun = (): JobRun => ({
status: 'waiting',
});
-export const createJobRuns = (): Record<
- SkillEvalComparisonRunLabel,
- JobRun
-> => ({
- after: createJobRun(),
- before: createJobRun(),
-});
+export const createJobRuns = (runCount = 1): JobRunGroup[] =>
+ Array.from({length: runCount}, (_, index) => ({
+ after: createJobRun(),
+ before: createJobRun(),
+ index: index + 1,
+ }));
export const formatRunLabel = (label: SkillEvalComparisonRunLabel) =>
label === 'before' ? 'Before' : 'After';
@@ -71,8 +82,9 @@ export const getActiveJob = (scenarioId: string) =>
export const startComparison = (
scenario: SkillEvalScenario,
- options: {beforeGitRef?: string} = {},
+ options: {beforeGitRef?: string; runCount?: number} = {},
) => {
+ const runCount = validateSkillEvalRunCount(options.runCount);
const existingJob = getActiveJob(scenario.id);
if (existingJob) {
@@ -83,7 +95,8 @@ export const startComparison = (
id: `${Date.now()}-${scenario.id}`,
logs: [],
message: 'Preparing comparison...',
- runs: createJobRuns(),
+ runCount,
+ runs: createJobRuns(runCount),
scenarioId: scenario.id,
startedAt: new Date().toISOString(),
status: 'running',
@@ -97,9 +110,11 @@ export const startComparison = (
};
const updateJobMessage = () => {
- const running = Object.entries(job.runs)
- .filter(([, run]) => run.status === 'running')
- .map(([label]) => formatRunLabel(label as SkillEvalComparisonRunLabel));
+ const running = job.runs.flatMap((runGroup) =>
+ (['before', 'after'] as const)
+ .filter((label) => runGroup[label].status === 'running')
+ .map((label) => `${formatRunLabel(label)} #${runGroup.index}`),
+ );
if (running.length > 0) {
job.message = `${running.join(' and ')} ${
@@ -108,14 +123,16 @@ export const startComparison = (
return;
}
- const failed = Object.entries(job.runs).find(
- ([, run]) => run.status === 'failed',
- );
+ const failed = job.runs.flatMap((runGroup) =>
+ (['before', 'after'] as const)
+ .filter((label) => runGroup[label].status === 'failed')
+ .map((label) => ({label, runGroup})),
+ )[0];
if (failed) {
- job.message = `${formatRunLabel(
- failed[0] as SkillEvalComparisonRunLabel,
- )} failed.`;
+ job.message = `${formatRunLabel(failed.label)} #${
+ failed.runGroup.index
+ } failed.`;
}
};
@@ -126,7 +143,12 @@ export const startComparison = (
return;
}
- const run = job.runs[event.label];
+ const runGroup = job.runs[event.runIndex - 1];
+ const run = runGroup?.[event.label];
+
+ if (!run) {
+ return;
+ }
if (event.type === 'run-start') {
run.status = 'running';
@@ -168,6 +190,7 @@ export const startComparison = (
const comparisonPromise = runSkillEvalComparison(scenario, {
beforeGitRef: options.beforeGitRef,
onEvent: handleEvent,
+ runCount,
})
.then((result) => {
if (result.skipped) {
@@ -190,7 +213,11 @@ export const startComparison = (
return job;
};
-export const startRun = (scenario: SkillEvalScenario) => {
+export const startRun = (
+ scenario: SkillEvalScenario,
+ runCountInput?: number,
+) => {
+ const runCount = validateSkillEvalRunCount(runCountInput);
const existingJob = getActiveJob(scenario.id);
if (existingJob) {
@@ -201,53 +228,100 @@ export const startRun = (scenario: SkillEvalScenario) => {
id: `${Date.now()}-${scenario.id}`,
logs: [],
message: 'Preparing run...',
- runs: createJobRuns(),
+ runCount,
+ runs: createJobRuns(runCount),
scenarioId: scenario.id,
startedAt: new Date().toISOString(),
status: 'running',
};
- const run = job.runs.after;
- job.runs.before.message = 'Not needed for a plain run';
- job.runs.before.status = 'completed';
+ for (const runGroup of job.runs) {
+ runGroup.before.message = 'Not needed for a plain run';
+ runGroup.before.status = 'completed';
+ }
+
jobs.set(job.id, job);
- const runPromise = runSkillEval({
- ...scenario,
- onPhase: (event) => {
- run.status = 'running';
- run.message = `${phaseLabels[event.phase]}${
- event.status === 'completed' ? ' complete' : ''
- }`;
- job.message = 'Running scenario...';
- },
- onOutput: (output) => {
- run.status = 'running';
- run.message = `${phaseLabels[output.phase]} (${output.stream})`;
- run.logs.push(output.chunk);
- trimLog(run.logs, 1000);
- job.message = 'Running scenario...';
- },
- skillSnapshot: {
- isWorkingTree: true,
- label: 'after',
+ const runPromise = runWithConcurrency({
+ inputs: Array.from({length: runCount}, (_, index) => index + 1),
+ limit: maxParallelSkillEvalRuns,
+ worker: async (runIndex) => {
+ const run = job.runs[runIndex - 1]?.after;
+
+ if (!run) {
+ throw new Error(`Missing run state for run #${runIndex}.`);
+ }
+
+ try {
+ const result = await runSkillEval({
+ ...scenario,
+ onPhase: (event) => {
+ run.status = 'running';
+ run.message = `${phaseLabels[event.phase]}${
+ event.status === 'completed' ? ' complete' : ''
+ }`;
+ job.message = `Running scenario${
+ runCount > 1 ? ` (${runCount} runs)` : ''
+ }...`;
+ },
+ onOutput: (output) => {
+ run.status = 'running';
+ run.message = `${phaseLabels[output.phase]} (${output.stream})`;
+ run.logs.push(output.chunk);
+ trimLog(run.logs, 1000);
+ job.message = `Running scenario${
+ runCount > 1 ? ` (${runCount} runs)` : ''
+ }...`;
+ },
+ runLabel:
+ runCount === 1
+ ? undefined
+ : `run-${String(runIndex).padStart(2, '0')}`,
+ skillSnapshot: {
+ isWorkingTree: true,
+ label: 'after',
+ },
+ });
+
+ run.status = 'completed';
+ run.message = 'Run complete.';
+ return result;
+ } catch (error) {
+ run.status = 'failed';
+ run.message = error instanceof Error ? error.message : String(error);
+ throw error;
+ }
},
})
- .then((result) => {
- run.status = 'completed';
- run.message = 'Run complete.';
- job.message = 'Run complete.';
- job.resultUrl = `/runs/${encodeURIComponent(
- result.manifest.id,
- )}/${encodeURIComponent(basename(result.manifest.runDir))}`;
+ .then((results) => {
+ const result = results[0];
+
+ if (!result) {
+ throw new Error('No run result was produced.');
+ }
+
+ job.message =
+ runCount === 1 ? 'Run complete.' : `${runCount} runs complete.`;
+ if (runCount === 1) {
+ job.resultUrl = `/runs/${encodeURIComponent(
+ result.manifest.id,
+ )}/${encodeURIComponent(basename(result.manifest.runDir))}`;
+ }
+
job.status = 'completed';
})
.catch((error: unknown) => {
job.error = error instanceof Error ? error.message : String(error);
job.message = job.error;
job.status = 'failed';
- run.status = 'failed';
- run.message = job.error;
+ for (const runGroup of job.runs) {
+ const run = runGroup.after;
+
+ if (run.status === 'running' || run.status === 'waiting') {
+ run.status = 'failed';
+ run.message = job.error;
+ }
+ }
});
runPromise.catch(() => undefined);
diff --git a/packages/skills-evals/src/app/routes.ts b/packages/skills-evals/src/app/routes.ts
index 6013821443..0ace26569f 100644
--- a/packages/skills-evals/src/app/routes.ts
+++ b/packages/skills-evals/src/app/routes.ts
@@ -8,6 +8,12 @@ import {loadRun, renderRun} from './run';
import {renderScenario} from './scenario';
import {htmlResponse, json, notFound} from './shared';
+const getRunCount = (request: Request) => {
+ const value = new URL(request.url).searchParams.get('runs');
+
+ return value === null ? undefined : Number(value);
+};
+
export const routes = {
'/': async () => htmlResponse(await renderHome()),
@@ -28,7 +34,19 @@ export const routes = {
? body.beforeGitRef
: undefined;
- return json(startComparison(scenario, {beforeGitRef}));
+ try {
+ return json(
+ startComparison(scenario, {
+ beforeGitRef,
+ runCount: getRunCount(request),
+ }),
+ );
+ } catch (error) {
+ return json(
+ {error: error instanceof Error ? error.message : String(error)},
+ {status: 400},
+ );
+ }
},
},
@@ -50,7 +68,14 @@ export const routes = {
return json({error: 'Unknown scenario'}, {status: 404});
}
- return json(startRun(scenario));
+ try {
+ return json(startRun(scenario, getRunCount(request)));
+ } catch (error) {
+ return json(
+ {error: error instanceof Error ? error.message : String(error)},
+ {status: 400},
+ );
+ }
},
},
diff --git a/packages/skills-evals/src/app/scenario.tsx b/packages/skills-evals/src/app/scenario.tsx
index dad528fe3b..0a3bc6425d 100644
--- a/packages/skills-evals/src/app/scenario.tsx
+++ b/packages/skills-evals/src/app/scenario.tsx
@@ -11,6 +11,7 @@ import {
getActiveJob,
type Job,
type JobRun,
+ type JobRunGroup,
} from './jobs';
import {
Card,
@@ -93,7 +94,10 @@ const toRunListItems = ({
...comparisons.map((comparison) => ({
completedAt: comparison.completedAt,
href: toComparisonUrl(comparison),
- metadata: `${comparison.before.hash} -> ${comparison.after.hash}`,
+ metadata:
+ comparison.runs && comparison.runs.length > 1
+ ? `${comparison.runs.length} comparison runs`
+ : `${comparison.before.hash} -> ${comparison.after.hash}`,
})),
...runs.map((run) => ({
completedAt: run.completedAt,
@@ -145,21 +149,131 @@ const ScenarioPageScript = ({
dangerouslySetInnerHTML={{
__html: `
const button = document.getElementById('run-comparison');
+const runCountSelect = document.getElementById('run-count');
const baseRefInput = document.getElementById('comparison-base-ref');
const panel = document.getElementById('active-job');
const log = document.getElementById('job-log');
const status = document.getElementById('job-status');
-const runStatus = {
- before: document.getElementById('before-run-status'),
- after: document.getElementById('after-run-status'),
-};
-const runLog = {
- before: document.getElementById('before-run-log'),
- after: document.getElementById('after-run-log'),
-};
+const runGroups = document.getElementById('run-groups');
const activeJobId = ${JSON.stringify(activeJob?.id ?? null)};
const defaultBaseRef = ${JSON.stringify(baseRef)};
+const shouldStickToBottom = (element) =>
+ element.scrollHeight - element.scrollTop - element.clientHeight < 8;
+
+const formatLabel = (label) => label === 'before' ? 'Before' : 'After';
+const createRunPanel = (runGroup, label) => {
+ const run = runGroup[label];
+ const section = document.createElement('section');
+ section.className = 'min-w-0 rounded-xl border border-zinc-200 bg-white p-3';
+ section.dataset.runLabel = label;
+
+ const header = document.createElement('div');
+ header.className = 'flex items-center justify-between gap-3';
+
+ const title = document.createElement('h4');
+ title.className = 'text-sm font-semibold';
+ title.textContent = formatLabel(label);
+
+ const pill = document.createElement('span');
+ pill.className = 'rounded-full bg-zinc-50 px-2 py-1 text-xs text-zinc-500 data-[status=completed]:text-emerald-700 data-[status=failed]:text-red-700 data-[status=running]:text-yellow-700';
+ pill.dataset.runStatus = label;
+ pill.dataset.status = run.status;
+ pill.textContent = run.message || run.status;
+
+ header.append(title, pill);
+ section.append(header);
+
+ const pre = document.createElement('pre');
+ pre.className = 'mt-3 max-h-70 overflow-auto whitespace-pre-wrap rounded-lg border border-zinc-200 bg-zinc-50 p-3 text-xs text-zinc-700';
+ pre.dataset.runLog = label;
+ pre.hidden = !run.logs?.length;
+ pre.textContent = run.logs?.join('') || '';
+ section.append(pre);
+ pre.scrollTop = pre.scrollHeight;
+
+ return section;
+};
+
+const createRunGroup = (runGroup, totalRuns) => {
+ const section = document.createElement('section');
+ section.className = 'min-w-0 rounded-2xl border border-zinc-200 bg-zinc-50 p-4';
+ section.dataset.runIndex = String(runGroup.index);
+
+ const title = document.createElement('h3');
+ title.className = 'text-[0.9375rem] font-semibold';
+ title.textContent = totalRuns > 1 ? 'Run #' + runGroup.index : 'Run';
+ section.append(title);
+
+ const grid = document.createElement('div');
+ grid.className = 'mt-3 grid grid-cols-2 gap-3 max-lg:grid-cols-1';
+ grid.append(createRunPanel(runGroup, 'before'), createRunPanel(runGroup, 'after'));
+ section.append(grid);
+
+ return section;
+};
+
+const updateRunPanel = (section, runGroup, label) => {
+ const run = runGroup[label];
+ const pill = section.querySelector('[data-run-status="' + label + '"]');
+ const pre = section.querySelector('[data-run-log="' + label + '"]');
+ const logText = run.logs?.join('') || '';
+
+ pill.dataset.status = run.status;
+ pill.textContent = run.message || run.status;
+
+ if (pre.textContent !== logText) {
+ const stickToBottom = shouldStickToBottom(pre);
+ pre.textContent = logText;
+ pre.hidden = !logText;
+
+ if (stickToBottom) {
+ pre.scrollTop = pre.scrollHeight;
+ }
+ }
+};
+
+const updateRunGroup = (section, runGroup, totalRuns) => {
+ const title = section.querySelector('h3');
+ title.textContent = totalRuns > 1 ? 'Run #' + runGroup.index : 'Run';
+ updateRunPanel(section.querySelector('[data-run-label="before"]'), runGroup, 'before');
+ updateRunPanel(section.querySelector('[data-run-label="after"]'), runGroup, 'after');
+};
+
+const createWaitingRunGroups = (runCount) => Array.from({length: runCount}, (_, index) => ({
+ index: index + 1,
+ before: {logs: [], message: 'Waiting to start', status: 'waiting'},
+ after: {logs: [], message: 'Waiting to start', status: 'waiting'},
+}));
+
+const renderRunGroups = (runs) => {
+ const runList = runs || [];
+ const seen = new Set();
+
+ for (const runGroup of runList) {
+ const key = String(runGroup.index);
+ let section = runGroups.querySelector('[data-run-index="' + key + '"]');
+
+ if (!section) {
+ section = createRunGroup(runGroup, runList.length);
+ runGroups.append(section);
+ for (const pre of section.querySelectorAll('[data-run-log]')) {
+ pre.scrollTop = pre.scrollHeight;
+ }
+ } else {
+ updateRunGroup(section, runGroup, runList.length);
+ }
+
+ seen.add(key);
+ }
+
+ for (const section of [...runGroups.querySelectorAll('[data-run-index]')]) {
+ if (!seen.has(section.dataset.runIndex)) {
+ section.remove();
+ }
+ }
+};
+
const renderJob = (job) => {
panel.hidden = false;
status.textContent = job.message || job.status;
@@ -170,22 +284,7 @@ const renderJob = (job) => {
log.scrollTop = log.scrollHeight;
}
- for (const label of ['before', 'after']) {
- const run = job.runs?.[label];
-
- if (!run) {
- continue;
- }
-
- runStatus[label].textContent = run.message || run.status;
- runStatus[label].dataset.status = run.status;
-
- if (run.logs?.length) {
- runLog[label].hidden = false;
- runLog[label].textContent = run.logs.join('');
- runLog[label].scrollTop = runLog[label].scrollHeight;
- }
- }
+ renderRunGroups(job.runs);
};
const poll = async (jobId) => {
@@ -203,6 +302,11 @@ const poll = async (jobId) => {
return;
}
+ if (job.status === 'completed') {
+ button.disabled = false;
+ return;
+ }
+
if (job.status === 'failed' || job.status === 'skipped') {
button.disabled = false;
return;
@@ -221,15 +325,12 @@ button?.addEventListener('click', async () => {
button.disabled = true;
panel.hidden = false;
status.textContent = 'Starting comparison...';
- for (const label of ['before', 'after']) {
- runStatus[label].textContent = 'Waiting to start';
- runStatus[label].dataset.status = 'waiting';
- runLog[label].hidden = true;
- runLog[label].textContent = '';
- }
+ renderRunGroups(createWaitingRunGroups(Number(runCountSelect.value)));
const beforeGitRef = baseRefInput?.value?.trim() || defaultBaseRef;
const shouldCompare = button.dataset.hasSkillChanges === 'true' || beforeGitRef !== defaultBaseRef;
- const response = await fetch(shouldCompare ? button.dataset.compareUrl : button.dataset.runUrl, {
+ const targetUrl = new URL(shouldCompare ? button.dataset.compareUrl : button.dataset.runUrl, location.origin);
+ targetUrl.searchParams.set('runs', runCountSelect.value);
+ const response = await fetch(targetUrl.pathname + targetUrl.search, {
body: shouldCompare ? JSON.stringify({beforeGitRef}) : undefined,
headers: shouldCompare ? {'content-type': 'application/json'} : undefined,
method: 'POST',
@@ -249,27 +350,51 @@ const RunProgressCard = ({
jobRun: JobRun;
label: 'after' | 'before';
}) => (
- <section className="min-w-0 rounded-xl border border-zinc-200 bg-zinc-50 p-3">
+ <section
+ className="min-w-0 rounded-xl border border-zinc-200 bg-white p-3"
+ data-run-label={label}
+ >
<div className="flex items-center justify-between gap-3">
- <h3 className="text-sm font-semibold">{formatRunLabel(label)}</h3>
+ <h4 className="text-sm font-semibold">{formatRunLabel(label)}</h4>
<span
- className="rounded-full bg-white px-2 py-1 text-xs text-zinc-500 data-[status=completed]:text-emerald-700 data-[status=failed]:text-red-700 data-[status=running]:text-yellow-700"
+ className="rounded-full bg-zinc-50 px-2 py-1 text-xs text-zinc-500 data-[status=completed]:text-emerald-700 data-[status=failed]:text-red-700 data-[status=running]:text-yellow-700"
+ data-run-status={label}
data-status={jobRun.status}
- id={`${label}-run-status`}
>
{jobRun.message}
</span>
</div>
<pre
- className="mt-3 max-h-70 overflow-auto whitespace-pre-wrap rounded-lg border border-zinc-200 bg-white p-3 text-xs text-zinc-700"
+ className="mt-3 max-h-70 overflow-auto whitespace-pre-wrap rounded-lg border border-zinc-200 bg-zinc-50 p-3 text-xs text-zinc-700"
+ data-run-log={label}
hidden={jobRun.logs.length === 0}
- id={`${label}-run-log`}
>
{jobRun.logs.join('')}
</pre>
</section>
);
+const RunProgressGroup = ({
+ runCount,
+ runGroup,
+}: {
+ runCount: number;
+ runGroup: JobRunGroup;
+}) => (
+ <section
+ className="min-w-0 rounded-2xl border border-zinc-200 bg-zinc-50 p-4"
+ data-run-index={runGroup.index}
+ >
+ <h3 className="text-[0.9375rem] font-semibold">
+ {runCount > 1 ? `Run #${runGroup.index}` : 'Run'}
+ </h3>
+ <div className="mt-3 grid grid-cols-2 gap-3 max-lg:grid-cols-1">
+ <RunProgressCard jobRun={runGroup.before} label="before" />
+ <RunProgressCard jobRun={runGroup.after} label="after" />
+ </div>
+ </section>
+);
+
const ActiveJobPanel = ({
hasSkillChanges,
job,
@@ -278,6 +403,7 @@ const ActiveJobPanel = ({
job: Job | undefined;
}) => {
const runs = job?.runs ?? createJobRuns();
+ const runCount = job?.runCount ?? runs.length;
return (
<section
@@ -289,8 +415,12 @@ const ActiveJobPanel = ({
<h2 className="text-[0.9375rem] font-semibold">Active run</h2>
<p className="text-sm text-zinc-500">
{hasSkillChanges
- ? 'Before and after run in parallel once the skill diff is ready.'
- : 'Scenario run without a before/after comparison.'}
+ ? `Before and after run in parallel once the skill diff is ready${
+ job && job.runCount > 1 ? ` (${job.runCount} runs).` : '.'
+ }`
+ : `Scenario run without a before/after comparison${
+ job && job.runCount > 1 ? ` (${job.runCount} runs).` : '.'
+ }`}
</p>
</div>
<p className="mt-3 text-[0.8125rem] text-yellow-700" id="job-status">
@@ -303,9 +433,14 @@ const ActiveJobPanel = ({
>
{job?.logs.join('') ?? ''}
</pre>
- <div className="mt-3 grid grid-cols-2 gap-3 max-lg:grid-cols-1">
- <RunProgressCard jobRun={runs.before} label="before" />
- <RunProgressCard jobRun={runs.after} label="after" />
+ <div className="mt-3 grid gap-3" id="run-groups">
+ {runs.map((runGroup) => (
+ <RunProgressGroup
+ key={runGroup.index}
+ runCount={runCount}
+ runGroup={runGroup}
+ />
+ ))}
</div>
</section>
);
@@ -325,16 +460,35 @@ export const renderScenario = async (scenario: SkillEvalScenario) => {
<>
<Header
action={
- <button
- className="rounded-full bg-zinc-900 px-3 py-2 text-[0.8125rem] font-semibold text-white hover:bg-zinc-800 disabled:bg-zinc-300 disabled:text-zinc-500"
- data-compare-url={`/api/compare/${encodeURIComponent(scenario.id)}`}
- data-has-skill-changes={String(skillDiffState.hasChanges)}
- data-run-url={`/api/run/${encodeURIComponent(scenario.id)}`}
- data-scenario={scenario.id}
- id="run-comparison"
- >
- {skillDiffState.hasChanges ? 'Run comparison' : 'Run'}
- </button>
+ <div className="flex flex-wrap items-center gap-2">
+ <label
+ className="text-[0.8125rem] font-medium text-zinc-500"
+ htmlFor="run-count"
+ >
+ Runs
+ </label>
+ <select
+ className="rounded-full border border-zinc-200 bg-white px-3 py-2 text-[0.8125rem] font-semibold text-zinc-700"
+ defaultValue="1"
+ id="run-count"
+ >
+ {[1, 2, 3, 4].map((runCount) => (
+ <option key={runCount} value={runCount}>
+ {runCount}
+ </option>
+ ))}
+ </select>
+ <button
+ className="rounded-full bg-zinc-900 px-3 py-2 text-[0.8125rem] font-semibold text-white hover:bg-zinc-800 disabled:bg-zinc-300 disabled:text-zinc-500"
+ data-compare-url={`/api/compare/${encodeURIComponent(scenario.id)}`}
+ data-has-skill-changes={String(skillDiffState.hasChanges)}
+ data-run-url={`/api/run/${encodeURIComponent(scenario.id)}`}
+ data-scenario={scenario.id}
+ id="run-comparison"
+ >
+ {skillDiffState.hasChanges ? 'Run comparison' : 'Run'}
+ </button>
+ </div>
}
subtitle={scenario.model}
title={scenario.id}
diff --git a/packages/skills-evals/src/cli.ts b/packages/skills-evals/src/cli.ts
index 604df74059..c9c851f473 100644
--- a/packages/skills-evals/src/cli.ts
+++ b/packages/skills-evals/src/cli.ts
@@ -1,6 +1,8 @@
import {scenarios} from '../scenarios';
import {runSkillEvalComparison} from './compare';
+import {maxParallelSkillEvalRuns, validateSkillEvalRunCount} from './run-count';
import {runSkillEval} from './run-skill-eval';
+import {runWithConcurrency} from './run-with-concurrency';
const serverUrl = 'http://localhost:4321';
@@ -22,6 +24,62 @@ const getScenario = (id: string | undefined) => {
return scenario;
};
+const parseRunCount = (args: string[]) => {
+ let runCount = 1;
+
+ for (let index = 0; index < args.length; index++) {
+ const arg = args[index];
+
+ if (arg === '--runs') {
+ const value = args[index + 1];
+
+ if (!value) {
+ throw new Error('Pass a value after --runs.');
+ }
+
+ runCount = Number(value);
+ index++;
+ } else if (arg.startsWith('--runs=')) {
+ runCount = Number(arg.slice('--runs='.length));
+ } else {
+ throw new Error(`Unknown option "${arg}".`);
+ }
+ }
+
+ return validateSkillEvalRunCount(runCount, '--runs');
+};
+
+const parseCompareOptions = (args: string[]) => {
+ let beforeGitRef: string | undefined;
+ const runCountArgs: string[] = [];
+
+ for (let index = 0; index < args.length; index++) {
+ const arg = args[index];
+
+ if (arg === '--runs') {
+ const value = args[index + 1];
+
+ if (!value) {
+ throw new Error('Pass a value after --runs.');
+ }
+
+ runCountArgs.push(arg, value);
+ index++;
+ } else if (arg.startsWith('--runs=')) {
+ runCountArgs.push(arg);
+ } else if (!beforeGitRef) {
+ beforeGitRef = arg;
+ } else {
+ throw new Error(`Unknown option "${arg}".`);
+ }
+ }
+
+ return {
+ beforeGitRef,
+ runCount: parseRunCount(runCountArgs),
+ };
+};
+
const main = async () => {
const command = process.argv[2];
@@ -29,15 +87,16 @@ const main = async () => {
await import('./server');
} else if (command === 'compare') {
const scenario = getScenario(process.argv[3]);
- const beforeGitRef = process.argv[4];
+ const {beforeGitRef, runCount} = parseCompareOptions(process.argv.slice(4));
process.stdout.write(
`Comparing ${scenario.id} with ${scenario.model}${
beforeGitRef ? ` against ${beforeGitRef}` : ''
- }\n`,
+ } (${runCount} ${runCount === 1 ? 'run' : 'runs'})\n`,
);
const result = await runSkillEvalComparison(scenario, {
beforeGitRef,
onLog: (chunk) => process.stdout.write(chunk),
+ runCount,
});
if (result.skipped) {
@@ -46,7 +105,13 @@ const main = async () => {
}
process.stdout.write(
- `${scenario.id}: ${result.comparison.before.hash} -> ${result.comparison.after.hash}\n`,
+ result.comparison.runs
+ ?.map(
+ (run) =>
+ `${scenario.id} #${run.index}: ${run.before.hash} -> ${run.after.hash}\n`,
+ )
+ .join('') ??
+ `${scenario.id}: ${result.comparison.before.hash} -> ${result.comparison.after.hash}\n`,
);
process.stdout.write(`Preview: ${serverUrl}\n`);
} else if (command === 'list') {
@@ -61,15 +126,47 @@ const main = async () => {
const scenariosToRun =
scenarioId === '--all' ? scenarios : [getScenario(scenarioId)];
+ const runCount = parseRunCount(process.argv.slice(4));
for (const scenario of scenariosToRun) {
- process.stdout.write(`Running ${scenario.id} with ${scenario.model}\n`);
- const result = await runSkillEval(scenario);
- process.stdout.write(`Wrote ${result.manifestPath}\n`);
+ process.stdout.write(
+ `Running ${scenario.id} with ${scenario.model} (${runCount} ${
+ runCount === 1 ? 'run' : 'runs'
+ })\n`,
+ );
+ const runIndexes = Array.from(
+ {length: runCount},
+ (_, index) => index + 1,
+ );
+ const results = await runWithConcurrency({
+ inputs: runIndexes,
+ limit: maxParallelSkillEvalRuns,
+ worker: async (runIndex) => {
+ const result = await runSkillEval({
+ ...scenario,
+ runLabel:
+ runCount === 1
+ ? undefined
+ : `run-${String(runIndex).padStart(2, '0')}`,
+ skillSnapshot: {
+ isWorkingTree: true,
+ label: 'after',
+ },
+ });
+ process.stdout.write(
+ `Wrote run #${runIndex}: ${result.manifestPath}\n`,
+ );
+ return result;
+ },
+ });
+
+ process.stdout.write(
+ `Completed ${results.length} ${results.length === 1 ? 'run' : 'runs'} for ${scenario.id}\n`,
+ );
}
} else {
process.stdout.write(
- 'Usage: bun run eval <list|run|compare|dev> [scenario-id|--all] [base-ref]\n',
+ 'Usage: bun run eval <list|run|compare|dev> [scenario-id|--all] [base-ref] [--runs 1-4]\n',
);
process.exit(command ? 1 : 0);
}
diff --git a/packages/skills-evals/src/compare.ts b/packages/skills-evals/src/compare.ts
index 0683d30d2e..432fc60406 100644
--- a/packages/skills-evals/src/compare.ts
+++ b/packages/skills-evals/src/compare.ts
@@ -10,11 +10,13 @@ import {
writeJson,
} from './files';
import type {SkillEvalComparison} from './manifest';
+import {maxParallelSkillEvalRuns, validateSkillEvalRunCount} from './run-count';
import {
runSkillEval,
type SkillEvalOutput,
type SkillEvalPhaseEvent,
} from './run-skill-eval';
+import {runWithConcurrency} from './run-with-concurrency';
export type SkillEvalComparisonRunLabel = 'after' | 'before';
@@ -25,25 +27,30 @@ export type SkillEvalComparisonEvent =
}
| {
label: SkillEvalComparisonRunLabel;
+ runIndex: number;
type: 'run-start';
}
| {
event: SkillEvalPhaseEvent;
label: SkillEvalComparisonRunLabel;
+ runIndex: number;
type: 'run-phase';
}
| {
label: SkillEvalComparisonRunLabel;
output: SkillEvalOutput;
+ runIndex: number;
type: 'run-output';
}
| {
label: SkillEvalComparisonRunLabel;
+ runIndex: number;
type: 'run-complete';
}
| {
error: string;
label: SkillEvalComparisonRunLabel;
+ runIndex: number;
type: 'run-error';
};
@@ -61,6 +68,7 @@ type SkillEvalComparisonOptions = {
beforeGitRef?: string;
onEvent?: (event: SkillEvalComparisonEvent) => void;
onLog?: (chunk: string) => void;
+ runCount?: number;
};
type BeforeSkillsSource = {
@@ -119,6 +127,7 @@ export const runSkillEvalComparison = async (
scenario: SkillEvalScenario,
options: SkillEvalComparisonOptions = {},
): Promise<SkillEvalComparisonResult> => {
+ const runCount = validateSkillEvalRunCount(options.runCount);
const comparisonId = `${createTimestamp()}--${sanitizePathPart(scenario.id)}`;
const comparisonDir = join(
comparisonsRoot,
@@ -173,38 +182,57 @@ export const runSkillEvalComparison = async (
await writeFile(skillDiffPath, `${diff.stdout}${diff.stderr}`);
+ const formatRun = (label: SkillEvalComparisonRunLabel, runIndex: number) =>
+ runCount === 1 ? label : `${label}#${runIndex}`;
+
const forwardOutput =
- (label: SkillEvalComparisonRunLabel) => (output: SkillEvalOutput) => {
- options.onEvent?.({label, output, type: 'run-output'});
+ (label: SkillEvalComparisonRunLabel, runIndex: number) =>
+ (output: SkillEvalOutput) => {
+ options.onEvent?.({label, output, runIndex, type: 'run-output'});
options.onLog?.(
- `[${label} ${output.phase} ${output.stream}] ${output.chunk}`,
+ `[${formatRun(label, runIndex)} ${output.phase} ${
+ output.stream
+ }] ${output.chunk}`,
);
};
const forwardPhase =
- (label: SkillEvalComparisonRunLabel) => (event: SkillEvalPhaseEvent) => {
- options.onEvent?.({event, label, type: 'run-phase'});
- options.onLog?.(`[${label} ${event.phase}] ${event.status}\n`);
+ (label: SkillEvalComparisonRunLabel, runIndex: number) =>
+ (event: SkillEvalPhaseEvent) => {
+ options.onEvent?.({event, label, runIndex, type: 'run-phase'});
+ options.onLog?.(
+ `[${formatRun(label, runIndex)} ${event.phase}] ${event.status}\n`,
+ );
};
- const abortControllers: Record<SkillEvalComparisonRunLabel, AbortController> =
- {
- after: new AbortController(),
- before: new AbortController(),
- };
- let firstSnapshotError: unknown = null;
- const runSnapshot = async (label: SkillEvalComparisonRunLabel) => {
- emitMessage(`[compare] Running ${label} snapshot\n`);
- options.onEvent?.({label, type: 'run-start'});
+ type SnapshotTask = {
+ label: SkillEvalComparisonRunLabel;
+ runIndex: number;
+ };
+ const abortControllers = new Set<AbortController>();
+ const abortAll = () => {
+ for (const controller of abortControllers) {
+ controller.abort();
+ }
+ };
+
+ const runSnapshot = async ({label, runIndex}: SnapshotTask) => {
+ const controller = new AbortController();
+ abortControllers.add(controller);
+ emitMessage(`[compare] Running ${formatRun(label, runIndex)} snapshot\n`);
+ options.onEvent?.({label, runIndex, type: 'run-start'});
try {
const result = await runSkillEval({
...scenario,
- onOutput: forwardOutput(label),
- onPhase: forwardPhase(label),
- runLabel: label,
+ onOutput: forwardOutput(label, runIndex),
+ onPhase: forwardPhase(label, runIndex),
+ runLabel:
+ runCount === 1
+ ? label
+ : `${label}-${String(runIndex).padStart(2, '0')}`,
runRoot: join(comparisonDir, 'runs'),
- signal: abortControllers[label].signal,
+ signal: controller.signal,
skillSnapshot:
label === 'before'
? {
@@ -219,74 +247,77 @@ export const runSkillEvalComparison = async (
label === 'before' ? beforeSkillsPath : afterSkillsPath,
});
- options.onEvent?.({label, type: 'run-complete'});
- return result;
+ options.onEvent?.({label, runIndex, type: 'run-complete'});
+ return {label, result, runIndex};
} catch (error) {
options.onEvent?.({
error: getErrorMessage(error),
label,
+ runIndex,
type: 'run-error',
});
+ abortAll();
throw error;
+ } finally {
+ abortControllers.delete(controller);
}
};
- const runSnapshotWithSiblingCancellation = async (
- label: SkillEvalComparisonRunLabel,
- sibling: SkillEvalComparisonRunLabel,
- ) => {
- try {
- return await runSnapshot(label);
- } catch (error) {
- if (!firstSnapshotError) {
- firstSnapshotError = error;
- abortControllers[sibling].abort();
- }
+ const snapshotTasks = Array.from({length: runCount}, (_, index) => index + 1)
+ .map((runIndex) => [
+ {label: 'before' as const, runIndex},
+ {label: 'after' as const, runIndex},
+ ])
+ .flat();
+ const snapshotResults = await runWithConcurrency({
+ inputs: snapshotTasks,
+ limit: maxParallelSkillEvalRuns,
+ worker: runSnapshot,
+ });
+ const resultsByKey = new Map(
+ snapshotResults.map((snapshot) => [
+ `${snapshot.label}:${snapshot.runIndex}`,
+ snapshot.result,
+ ]),
+ );
+ const runPairs = Array.from({length: runCount}, (_, index) => {
+ const runIndex = index + 1;
+ const before = resultsByKey.get(`before:${runIndex}`);
+ const after = resultsByKey.get(`after:${runIndex}`);
- throw error;
+ if (!before || !after) {
+ throw new Error(`Missing results for comparison run ${runIndex}.`);
}
- };
-
- const [beforeResult, afterResult] = await Promise.allSettled([
- runSnapshotWithSiblingCancellation('before', 'after'),
- runSnapshotWithSiblingCancellation('after', 'before'),
- ]);
-
- if (firstSnapshotError) {
- throw firstSnapshotError;
- }
-
- if (beforeResult.status === 'rejected') {
- throw beforeResult.reason;
- }
-
- if (afterResult.status === 'rejected') {
- throw afterResult.reason;
- }
- const before = beforeResult.value;
- const after = afterResult.value;
+ return {
+ after: {
+ hash: after.manifest.skillSnapshot.hash,
+ isWorkingTree: true,
+ label: 'after' as const,
+ manifestPath: after.manifestPath,
+ skillsPath: afterSkillsPath,
+ },
+ before: {
+ gitRef: beforeSource.gitRef,
+ hash: before.manifest.skillSnapshot.hash,
+ label: 'before' as const,
+ manifestPath: before.manifestPath,
+ source: beforeSource.source,
+ skillsPath: beforeSkillsPath,
+ },
+ index: runIndex,
+ };
+ });
const completedAt = new Date().toISOString();
const comparison: SkillEvalComparison = {
- after: {
- hash: after.manifest.skillSnapshot.hash,
- isWorkingTree: true,
- label: 'after',
- manifestPath: after.manifestPath,
- skillsPath: afterSkillsPath,
- },
- before: {
- gitRef: beforeSource.gitRef,
- hash: before.manifest.skillSnapshot.hash,
- label: 'before',
- manifestPath: before.manifestPath,
- source: beforeSource.source,
- skillsPath: beforeSkillsPath,
- },
+ after: runPairs[0].after,
+ before: runPairs[0].before,
completedAt,
comparisonDir,
createdAt,
id: comparisonId,
+ runCount,
+ runs: runPairs,
scenarioId: scenario.id,
skillDiffPath,
};
diff --git a/packages/skills-evals/src/manifest.ts b/packages/skills-evals/src/manifest.ts
index e47ee48b10..765112a7dd 100644
--- a/packages/skills-evals/src/manifest.ts
+++ b/packages/skills-evals/src/manifest.ts
@@ -54,6 +54,30 @@ export type SkillEvalResult = {
scenario: SkillEvalScenario;
};
+export type SkillEvalComparisonBeforeRun = {
+ label: 'before';
+ source: 'git-ref' | 'head';
+ skillsPath: string;
+ hash: string;
+ gitRef?: string;
+ comparisonId?: string;
+ manifestPath: string;
+};
+
+export type SkillEvalComparisonAfterRun = {
+ label: 'after';
+ skillsPath: string;
+ hash: string;
+ isWorkingTree: boolean;
+ manifestPath: string;
+};
+
+export type SkillEvalComparisonRunPair = {
+ after: SkillEvalComparisonAfterRun;
+ before: SkillEvalComparisonBeforeRun;
+ index: number;
+};
+
export type SkillEvalComparison = {
id: string;
scenarioId: string;
@@ -61,20 +85,8 @@ export type SkillEvalComparison = {
completedAt: string;
comparisonDir: string;
skillDiffPath: string;
- before: {
- label: 'before';
- source: 'git-ref' | 'head';
- skillsPath: string;
- hash: string;
- gitRef?: string;
- comparisonId?: string;
- manifestPath: string;
- };
- after: {
- label: 'after';
- skillsPath: string;
- hash: string;
- isWorkingTree: boolean;
- manifestPath: string;
- };
+ before: SkillEvalComparisonBeforeRun;
+ after: SkillEvalComparisonAfterRun;
+ runCount?: number;
+ runs?: SkillEvalComparisonRunPair[];
};
diff --git a/packages/skills-evals/src/run-count.ts b/packages/skills-evals/src/run-count.ts
new file mode 100644
index 0000000000..35532a62ef
--- /dev/null
+++ b/packages/skills-evals/src/run-count.ts
@@ -0,0 +1,22 @@
+export const maxParallelSkillEvalRuns = 4;
+
+export const validateSkillEvalRunCount = (
+ runCount: number | undefined,
+ name = 'Run count',
+) => {
+ if (runCount === undefined) {
+ return 1;
+ }
+
+ if (
+ !Number.isInteger(runCount) ||
+ runCount < 1 ||
+ runCount > maxParallelSkillEvalRuns
+ ) {
+ throw new Error(
+ `${name} must be an integer between 1 and ${maxParallelSkillEvalRuns}.`,
+ );
+ }
+
+ return runCount;
+};
diff --git a/packages/skills-evals/src/run-skill-eval.ts b/packages/skills-evals/src/run-skill-eval.ts
index 0d77e5f159..eda630345b 100644
--- a/packages/skills-evals/src/run-skill-eval.ts
+++ b/packages/skills-evals/src/run-skill-eval.ts
@@ -37,7 +37,7 @@ type SkillEvalScenarioInput = SkillEvalScenario & {
onOutput?: (output: SkillEvalOutput) => void;
onPhase?: (event: SkillEvalPhaseEvent) => void;
runRoot?: string;
- runLabel?: 'before' | 'after';
+ runLabel?: string;
signal?: AbortSignal;
skillsSourcePath?: string;
skillSnapshot?: Partial<
diff --git a/packages/skills-evals/src/run-with-concurrency.ts b/packages/skills-evals/src/run-with-concurrency.ts
new file mode 100644
index 0000000000..1e2c8f12e2
--- /dev/null
+++ b/packages/skills-evals/src/run-with-concurrency.ts
@@ -0,0 +1,36 @@
+export const runWithConcurrency = async <TInput, TOutput>({
+ inputs,
+ limit,
+ worker,
+}: {
+ inputs: TInput[];
+ limit: number;
+ worker: (input: TInput) => Promise<TOutput>;
+}) => {
+ const results: TOutput[] = [];
+ let nextIndex = 0;
+ let firstError: unknown = null;
+ const workerCount = Math.min(limit, inputs.length);
+
+ await Promise.allSettled(
+ Array.from({length: workerCount}, async () => {
+ while (nextIndex < inputs.length && !firstError) {
+ const currentIndex = nextIndex;
+ nextIndex++;
+
+ try {
+ results[currentIndex] = await worker(inputs[currentIndex]);
+ } catch (error) {
+ firstError ??= error;
+ throw error;
+ }
+ }
+ }),
+ );
+
+ if (firstError) {
+ throw firstError;
+ }
+
+ return results;
+};