feat(research): compare saved experiments against explicit trials

This commit is contained in:
Boki 2026-10-24 14:06:21 -04:00
parent 397cd0e160
commit 46a4f13acd
22 changed files with 3045 additions and 35 deletions

View file

@ -37,6 +37,10 @@
"types": "./dist/contracts/chronological-validation.d.ts",
"default": "./dist/contracts/chronological-validation.js"
},
"./experiment-comparison": {
"types": "./dist/contracts/experiment-comparison.d.ts",
"default": "./dist/contracts/experiment-comparison.js"
},
"./cost-sensitivity": {
"types": "./dist/contracts/cost-sensitivity.d.ts",
"default": "./dist/contracts/cost-sensitivity.js"

View file

@ -0,0 +1,66 @@
/** Read-only comparison of retained inputs and existing scalar result summaries. */
import { z } from 'zod';
import type { WorkbenchExperimentDetail } from './cost-sensitivity';
const experimentId = z
.string()
.uuid()
.transform(id => id.toLowerCase());
export const experimentComparisonInputSchema = z
.object({
leftId: experimentId,
rightId: experimentId,
referenceTrialKey: z
.string()
.regex(/^[a-f0-9]{64}$/)
.optional(),
})
.strict()
.refine(input => input.leftId !== input.rightId, {
message: 'Select two different experiments',
});
export type ExperimentComparisonInput = z.infer<typeof experimentComparisonInputSchema>;
/** Stable order for mismatch explanations; these are conditions, not performance scores. */
export const experimentComparisonDimensions = [
'dataset',
'window',
'capital',
'costs',
'execution',
'risk',
'clock',
'analytics',
'seed',
'build',
'models',
] as const;
export type ExperimentComparisonDimension = (typeof experimentComparisonDimensions)[number];
export interface ExperimentComparisonRow {
experimentId: string;
trialKey: string;
inputCompatibility: 'match' | 'mismatch';
differences: ExperimentComparisonDimension[];
/** Existing compact provenance/shape checks, not full financial reconciliation. */
summaryAvailable: boolean;
/** Both saved summaries exist and their input conditions match. */
ready: boolean;
}
export interface ExperimentComparison {
version: 'experiment-comparison/v1';
policy: 'retained-input-compatibility/v1';
selection: Required<ExperimentComparisonInput>;
reference: {
experimentId: string;
trialKey: string;
index: number;
runId: string | null;
summaryAvailable: boolean;
diagnostic: string | null;
};
/** Existing compact result readers; never include full financial/trade/return arrays. */
experiments: [WorkbenchExperimentDetail, WorkbenchExperimentDetail];
/** Left then right, in each experiment's immutable candidate order. */
rows: ExperimentComparisonRow[];
limitations: string[];
}

View file

@ -211,6 +211,17 @@ export function createExperimentRoutes(container: IServiceContainer) {
}
return c.json({ experiments: await service.list(filter) });
});
app.get('/api/v2/experiments/compare', async c => {
const params = new URL(c.req.url).searchParams;
const seen = new Set<string>();
for (const key of params.keys()) {
if (seen.has(key) || !['leftId', 'rightId', 'referenceTrialKey'].includes(key)) {
throw new ExperimentError(400, 'Unknown or duplicate comparison query parameter');
}
seen.add(key);
}
return c.json({ comparison: await service.compare(Object.fromEntries(params)) });
});
app.get('/api/v2/experiments/:id', async c =>
c.json({ experiment: await service.get(experimentId(c.req.param('id'))) })
);

View file

@ -0,0 +1,124 @@
import { at } from '@stock-bot/invariants';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import type { WorkbenchExperimentDetail } from '@stock-bot/stock-config/cost-sensitivity';
import {
experimentComparisonDimensions,
experimentComparisonInputSchema,
type ExperimentComparison,
type ExperimentComparisonDimension,
type ExperimentComparisonInput,
} from '@stock-bot/stock-config/experiment-comparison';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
import { workbenchTrialRequest } from './cost-sensitivity-input';
import { ExperimentError, PREVIEW_RUN_ID } from './experiment-input';
export function parseExperimentComparison(raw: unknown): ExperimentComparisonInput {
const parsed = experimentComparisonInputSchema.safeParse(raw);
if (!parsed.success) {
throw new ExperimentError(
400,
'Comparison requires two distinct experiment IDs and an optional reference trial key'
);
}
return parsed.data;
}
/** Partition the complete parsed replay policy. Only validated admission/owner identities normalize. */
export function comparisonConditions(
input: CanonicalRunRequest,
manifest: HistoricalDatasetManifestV2
): Record<ExperimentComparisonDimension, unknown> {
const request = canonicalRunRequestSchema.parse(input),
policy = structuredClone(request.policy);
policy.matching.risk.ledger.sessionId = 'comparison-run';
policy.matching.risk.ledger.accountId = 'comparison-account';
policy.matching.risk.ledger.ownerIds[0] = 'comparison-owner';
at(policy.matching.owners, 0).ownerId = 'comparison-owner';
at(policy.cadence, 0).owner_id = 'comparison-owner';
const { matching, risk_boundaries, ...policyRemainder } = policy;
const { risk, halfSpreadRate, slippageRate, ...matchingRemainder } = matching;
const { ledger, feeRate, ...riskRemainder } = risk;
const { initialCapital, riskSession, ...ledgerRemainder } = ledger;
return {
dataset: { manifest, datasetHash: request.datasetHash },
window: manifest.bounds,
capital: { initialCapital, ownerBudget: request.strategy.selection.ownerBudget },
costs: { feeRate, halfSpreadRate, slippageRate },
execution: {
...policyRemainder,
matching: matchingRemainder,
instrumentId: request.strategy.selection.instrumentId,
seriesId: request.strategy.selection.seriesId,
},
risk: { ...riskRemainder, ledger: ledgerRemainder },
clock: { riskSession, risk_boundaries },
analytics: request.analyticsPolicy,
seed: request.strategy.selection.seed,
build: request.build,
models: request.modelArtifacts,
};
}
export function compareExperiments(
raw: ExperimentComparisonInput,
experiments: [WorkbenchExperimentDetail, WorkbenchExperimentDetail]
): ExperimentComparison {
const input = parseExperimentComparison(raw),
[left, right] = experiments;
if (left.id !== input.leftId || right.id !== input.rightId) {
throw new Error('Comparison experiment identities do not match the requested pair');
}
const reference =
input.referenceTrialKey === undefined
? at(left.trials, 0)
: left.trials.find(trial => trial.trialKey === input.referenceTrialKey);
if (!reference) {
throw new ExperimentError(409, 'Reference trial does not belong to the left experiment');
}
const conditions = comparisonConditions(
workbenchTrialRequest(left.preview, reference, reference.runId ?? PREVIEW_RUN_ID),
left.preview.dataset
);
const rows = experiments.flatMap(experiment =>
experiment.trials.map(trial => {
const current = comparisonConditions(
workbenchTrialRequest(experiment.preview, trial, trial.runId ?? PREVIEW_RUN_ID),
experiment.preview.dataset
);
const differences = experimentComparisonDimensions.filter(
dimension =>
canonicalStrategyJson(current[dimension]) !== canonicalStrategyJson(conditions[dimension])
);
return {
experimentId: experiment.id,
trialKey: trial.trialKey,
inputCompatibility: differences.length ? ('mismatch' as const) : ('match' as const),
differences,
summaryAvailable: trial.comparable,
ready: differences.length === 0 && trial.comparable && reference.comparable,
};
})
);
return {
version: 'experiment-comparison/v1',
policy: 'retained-input-compatibility/v1',
selection: { ...input, referenceTrialKey: reference.trialKey },
reference: {
experimentId: left.id,
trialKey: reference.trialKey,
index: reference.index,
runId: reference.runId,
summaryAvailable: reference.comparable,
diagnostic: reference.diagnostic,
},
experiments,
rows,
limitations: [
'Matching settings and saved scalar summaries do not establish economic equivalence, full financial reconciliation, independence, statistical significance or out-of-sample validity.',
'Summary availability uses existing compact provenance and shape checks. Open the exact run for deeper retained-result validation.',
'Strategy implementations and parameters may differ. Rows preserve original candidate order; no ranking or preferred candidate is implied.',
],
};
}

View file

@ -27,6 +27,7 @@ import {
retainedWorkbenchPreview,
workbenchTrialRequest,
} from './cost-sensitivity-input';
import { compareExperiments, parseExperimentComparison } from './experiment-comparison';
import {
buildExperimentPreview,
ExperimentError,
@ -319,6 +320,30 @@ export class ExperimentsService {
);
return rows.rows.map(summary);
}
async compare(raw: unknown) {
const input = parseExperimentComparison(raw);
return this.database.transaction(async client => {
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
const rows = (
await client.query(
'SELECT id,validation_phase FROM research_experiments WHERE id=ANY($1::uuid[])',
[[input.leftId, input.rightId]]
)
).rows;
if (rows.length !== 2) {
throw new ExperimentError(404, 'Comparison experiment not found');
}
if (rows.some(row => row.validation_phase !== null)) {
throw new ExperimentError(
409,
'Compare standalone experiments; chronological phases have their own workflow'
);
}
const left = await this.readDetail(client, input.leftId),
right = await this.readDetail(client, input.rightId);
return compareExperiments(input, [left, right]);
});
}
async get(id: string): Promise<WorkbenchExperimentDetail> {
experimentId(id);
return this.readDetail(this.database, id);

View file

@ -5,6 +5,7 @@ import { DashboardPage } from '@/features/dashboard';
import { ExchangesPage } from '@/features/exchanges';
import {
ChronologicalValidationDetailPage,
ExperimentComparisonPage,
ExperimentDetailPage,
ExperimentListPage,
WalkForwardDetailPage,
@ -56,6 +57,7 @@ export function App() {
</Route>
<Route path="experiments">
<Route index element={<ExperimentListPage />} />
<Route path="compare" element={<ExperimentComparisonPage />} />
<Route
path="validation/:validationId"
element={<ChronologicalValidationDetailPage />}

View file

@ -0,0 +1,322 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import type {
ExperimentComparisonDimension,
ExperimentComparisonInput,
} from '@stock-bot/stock-config/experiment-comparison';
import { Button } from '@/components/ui/Button';
import { ExperimentCounts } from './components/ExperimentCounts';
import { ExperimentInputs } from './components/ExperimentInputs';
import { metricText } from './components/trialMetricText';
import {
experimentComparisonApi,
parseComparisonQuery,
type ExperimentComparisonView,
} from './services/experimentComparisonApi';
const dimensionLabels: Record<ExperimentComparisonDimension, string> = {
dataset: 'Dataset and retained provenance',
window: 'Warmup and evaluation window',
capital: 'Initial capital and strategy budget',
costs: 'Fees, spread or slippage',
execution: 'Execution and liquidity settings',
risk: 'Portfolio risk limits and ledger settings',
clock: 'Account risk-session clock',
analytics: 'Metric definitions and analytics settings',
seed: 'Random seed',
build: 'Engine, worker or runtime build',
models: 'Model artifacts',
};
export function ExperimentComparisonPage() {
const [params, setParams] = useSearchParams();
let input: ExperimentComparisonInput;
try {
input = parseComparisonQuery(params);
} catch (cause) {
return (
<div className="space-y-3 p-1">
<h1 className="text-lg font-bold">Compare experiments</h1>
<p role="alert">{cause instanceof Error ? cause.message : 'Invalid comparison URL'}</p>
<Link className="text-primary-500" to="/experiments">
Select experiments
</Link>
</div>
);
}
return (
<Comparison
key={params.toString()}
input={input}
onReference={key => setParams({ ...input, referenceTrialKey: key })}
/>
);
}
function Comparison({
input,
onReference,
}: {
input: ExperimentComparisonInput;
onReference: (key: string) => void;
}) {
const [value, setValue] = useState<ExperimentComparisonView | null>(null),
[loading, setLoading] = useState(true),
[error, setError] = useState(''),
[reload, setReload] = useState(0);
const reading = useRef(true);
useEffect(() => {
let current = true;
const controller = new AbortController();
reading.current = true;
setLoading(true);
setError('');
void experimentComparisonApi
.get(input, controller.signal)
.then(result => {
if (current) {
setValue(result);
}
})
.catch(cause => {
if (current) {
setError(cause instanceof Error ? cause.message : 'Could not load comparison');
}
})
.finally(() => {
if (current) {
reading.current = false;
setLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [input.leftId, input.rightId, input.referenceTrialKey, reload]);
return (
<div className="h-full overflow-auto p-1 space-y-4">
<Link className="text-primary-500 text-sm" to="/experiments">
All experiments
</Link>
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-lg font-bold">Compare experiments</h1>
<Button
variant="outline"
disabled={loading}
onClick={() => {
if (!reading.current) {
reading.current = true;
setReload(current => current + 1);
}
}}
>
Refresh comparison
</Button>
</div>
<p className="text-sm">
Read-only comparison of recorded settings and saved summaries. Matching settings do not
establish economic equivalence, full financial reconciliation, independence, statistical
significance or out-of-sample validity. No ranking, deltas or aggregate performance are
calculated.
</p>
{loading && <p role="status">Loading comparison...</p>}
{error && (
<p role="alert" className="text-error">
{error}
{value && ' Showing the last loaded comparison for this same selection.'}
</p>
)}
{value && (
<>
<label className="block text-sm">
Reference trial
<select
aria-label="Reference trial"
className="mt-1 w-full rounded border border-border bg-background p-2"
value={value.selection.referenceTrialKey}
onChange={event => onReference(event.target.value)}
>
{value.experiments[0].trials.map(trial => (
<option key={trial.trialKey} value={trial.trialKey}>
{'costs' in trial
? trial.index === 0
? 'Baseline'
: `Scenario ${trial.index}`
: `Trial ${trial.index + 1}`}{' '}
· {JSON.stringify(trial.parameters)} · {trial.status}
</option>
))}
</select>
</label>
<p className="text-sm">
Reference comes from {value.experiments[0].name}. Without an explicit URL reference, its
frozen first candidate is used; completion status and performance never choose the
reference.
</p>
{!value.reference.summaryAvailable && (
<p role="status">
Reference saved summary unavailable:{' '}
{value.reference.diagnostic ?? 'No comparable saved summary exists for this trial.'}{' '}
Settings comparisons and every outcome remain visible.
</p>
)}
<section aria-label="Comparison limitations" className="text-sm space-y-1">
{value.limitations.map((text, index) => (
<p key={index}>{text}</p>
))}
</section>
{value.experiments.map((experiment, side) => (
<section
key={experiment.id}
aria-label={`${side === 0 ? 'Left' : 'Right'} experiment outcomes`}
className="space-y-3"
>
<h2 className="font-semibold">
{side === 0 ? 'Left' : 'Right'}: {experiment.name}
</h2>
<Link
className="text-primary-500 text-sm"
to={`/experiments/${encodeURIComponent(experiment.id)}`}
>
Open {side === 0 ? 'left' : 'right'} experiment
</Link>
<ExperimentCounts experiment={experiment} />
<p className="text-sm break-all">
Strategy {experiment.preview.request.strategy.selection.strategyId} · Version{' '}
{experiment.strategyVersionId} · Dataset {experiment.datasetHash}
</p>
<details>
<summary className="cursor-pointer">
{side === 0 ? 'Left' : 'Right'} frozen inputs
</summary>
<ExperimentInputs preview={experiment.preview} />
</details>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead>
<tr>
{[
'Trial / parameters',
'Status',
'Effective costs (fractions)',
'Input settings',
'Saved summary',
'Total return (fraction)',
'Max drawdown (fraction)',
'Sharpe ratio',
'Diagnostics / evidence',
].map(label => (
<th className="p-2 border-b border-border whitespace-nowrap" key={label}>
{label}
</th>
))}
</tr>
</thead>
<tbody>
{experiment.trials.map(trial => {
const row = value.rows.find(
item =>
item.experimentId === experiment.id && item.trialKey === trial.trialKey
);
if (!row) {
throw new Error('Verified comparison row is missing');
}
const matching = experiment.preview.request.policy.matching,
costs =
'costs' in trial
? trial.costs
: {
feeRate: matching.risk.feeRate,
slippageRate: matching.slippageRate,
};
const reference =
experiment.id === value.reference.experimentId &&
trial.trialKey === value.reference.trialKey;
return (
<tr key={trial.trialKey} className="align-top">
<td className="p-2 border-b border-border">
<p>
{'costs' in trial
? trial.index === 0
? 'Baseline'
: `Scenario ${trial.index}`
: `Trial ${trial.index + 1}`}
{reference ? ' · Reference' : ''}
</p>
<pre className="whitespace-pre-wrap text-xs">
{JSON.stringify(trial.parameters, null, 2)}
</pre>
</td>
<td className="p-2 border-b border-border">
<p>{trial.status}</p>
<p>
{trial.status === 'missing'
? 'Expected run missing'
: `${trial.progress}% complete`}
</p>
{trial.cancelRequested && <p>Cancellation requested</p>}
</td>
<td className="p-2 border-b border-border">
<p>Fee: {costs.feeRate}</p>
<p>Half-spread: {matching.halfSpreadRate}</p>
<p>Slippage: {costs.slippageRate}</p>
</td>
<td className="p-2 border-b border-border">
<p>
{row.inputCompatibility === 'match'
? 'Matching settings'
: 'Settings differ'}
</p>
{row.differences.map(difference => (
<p key={difference}>{dimensionLabels[difference]}</p>
))}
</td>
<td className="p-2 border-b border-border">
<p>
{row.summaryAvailable
? 'Saved summary available'
: (trial.diagnostic ?? 'Saved summary unavailable')}
</p>
<p>
{row.ready
? 'Matching settings and both saved summaries available'
: 'Comparison evidence not ready'}
</p>
</td>
<td className="p-2 border-b border-border">
{metricText(trial, 'totalReturn')}
</td>
<td className="p-2 border-b border-border">
{metricText(trial, 'maxDrawdown')}
</td>
<td className="p-2 border-b border-border">
{metricText(trial, 'sharpeRatio')}
</td>
<td className="p-2 border-b border-border min-w-64 space-y-1">
{trial.error && <p>{trial.error}</p>}
{trial.diagnostic && <p>{trial.diagnostic}</p>}
{trial.limitations.map((text, index) => (
<p key={index}>{text}</p>
))}
{trial.runId && (
<Link
className="text-primary-500"
to={`/backtests/${encodeURIComponent(experiment.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
>
Open {side === 0 ? 'left' : 'right'} trial {trial.index + 1} run
</Link>
)}
<p className="break-all text-xs">Trial key {trial.trialKey}</p>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</section>
))}
</>
)}
</div>
);
}

View file

@ -6,6 +6,7 @@ import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWa
import { ExperimentCounts } from './components/ExperimentCounts';
import { ExperimentInputs } from './components/ExperimentInputs';
import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery';
import { metricText } from './components/trialMetricText';
import {
experimentApi,
type WorkbenchExperimentDetailView as Detail,
@ -15,12 +16,6 @@ export function ExperimentDetailPage() {
const { experimentId = '' } = useParams<{ experimentId: string }>();
return <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
}
function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTrial['metrics']>) {
const value = trial.metrics?.[key];
return value === null || value === undefined
? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}`
: String(value);
}
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
const alive = useRef(false);
const pending = useRef(false);

View file

@ -19,6 +19,10 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
const [error, setError] = useState('');
const [reload, setReload] = useState(0);
const [dirty, setDirty] = useState(false);
const [selected, setSelected] = useState<string[]>([]);
const [leftId, rightId] = selected;
const compareUrl =
leftId && rightId ? `/experiments/compare?${new URLSearchParams({ leftId, rightId })}` : null;
useEffect(() => {
let current = true;
const controller = new AbortController();
@ -30,6 +34,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
.then(value => {
if (current) {
setRows(value);
setSelected(previous => previous.filter(id => value.some(item => item.id === id)));
}
})
.catch(cause => {
@ -87,6 +92,18 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
Refresh experiments
</Button>
</div>
<div className="text-sm space-y-2">
<p>Select two experiments in order. The first supplies the reference trial.</p>
{compareUrl && !loading && !error ? (
<Link className="text-primary-500" to={compareUrl}>
Compare selected experiments
</Link>
) : (
<Button variant="outline" size="sm" disabled>
Compare selected experiments
</Button>
)}
</div>
{backtestId && (
<p className="text-sm">
Showing experiments for the selected backtest.{' '}
@ -104,6 +121,26 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
{!loading && !error && rows.length === 0 && <p>No experiments yet.</p>}
{rows.map(item => (
<article key={item.id} className="rounded-lg border border-border p-3 space-y-2">
<label className="flex gap-2 items-center text-sm">
<input
type="checkbox"
aria-label={`Select ${item.name} for comparison`}
checked={selected.includes(item.id)}
disabled={loading || (!selected.includes(item.id) && selected.length === 2)}
onChange={() =>
setSelected(previous =>
previous.includes(item.id)
? previous.filter(id => id !== item.id)
: previous.length < 2
? [...previous, item.id]
: previous
)
}
/>
{selected.includes(item.id)
? `Selected ${selected.indexOf(item.id) + 1}`
: 'Select for comparison'}
</label>
<Link
className="font-medium text-primary-500"
to={`/experiments/${encodeURIComponent(item.id)}`}

View file

@ -0,0 +1,11 @@
import type { ExperimentTrial } from '@stock-bot/stock-config/experiments';
export function metricText(
trial: ExperimentTrial,
key: keyof NonNullable<ExperimentTrial['metrics']>
) {
const value = trial.metrics?.[key];
return value === null || value === undefined
? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}`
: String(value);
}

View file

@ -1,4 +1,5 @@
export { ExperimentListPage } from './ExperimentListPage';
export { ExperimentDetailPage } from './ExperimentDetailPage';
export { ExperimentComparisonPage } from './ExperimentComparisonPage';
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
export { WalkForwardDetailPage } from './WalkForwardDetailPage';

View file

@ -0,0 +1,146 @@
import { z } from 'zod';
import {
experimentComparisonDimensions,
experimentComparisonInputSchema,
type ExperimentComparison,
type ExperimentComparisonInput,
} from '@stock-bot/stock-config/experiment-comparison';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import {
parseWorkbenchExperimentDetail,
type WorkbenchExperimentDetailView,
} from './experimentApi';
export type ExperimentComparisonView = Omit<ExperimentComparison, 'experiments'> & {
experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView];
};
const hash = z.string().regex(/^[a-f0-9]{64}$/),
uuid = z.string().uuid();
const schema = z.object({
version: z.literal('experiment-comparison/v1'),
policy: z.literal('retained-input-compatibility/v1'),
selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(),
reference: z.object({
experimentId: uuid,
trialKey: hash,
index: z.number().int().nonnegative(),
runId: uuid.nullable(),
summaryAvailable: z.boolean(),
diagnostic: z.string().nullable(),
}),
experiments: z.tuple([z.unknown(), z.unknown()]),
rows: z
.array(
z.object({
experimentId: uuid,
trialKey: hash,
inputCompatibility: z.enum(['match', 'mismatch']),
differences: z.array(z.enum(experimentComparisonDimensions)),
summaryAvailable: z.boolean(),
ready: z.boolean(),
})
)
.min(2)
.max(200),
limitations: z.array(z.string().min(1)).min(1),
});
const invalid = () =>
new Error('The experiment comparison could not be verified. Refresh the same selection.');
export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput {
const allowed = ['leftId', 'rightId', 'referenceTrialKey'];
for (const key of params.keys()) {
if (!allowed.includes(key) || params.getAll(key).length !== 1) {
throw new Error(
'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.'
);
}
}
const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params));
if (!result.success) {
throw new Error(
'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.'
);
}
return result.data;
}
export function parseExperimentComparison(
raw: unknown,
input: ExperimentComparisonInput
): ExperimentComparisonView {
const value = schema.parse(raw),
experiments = value.experiments.map(
parseWorkbenchExperimentDetail
) as ExperimentComparisonView['experiments'];
const [left, right] = experiments;
const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey;
const reference = left.trials.find(trial => trial.trialKey === expectedKey);
if (
!reference ||
left.id !== input.leftId ||
right.id !== input.rightId ||
value.selection.leftId !== input.leftId ||
value.selection.rightId !== input.rightId ||
value.selection.referenceTrialKey !== expectedKey ||
value.reference.experimentId !== left.id ||
value.reference.trialKey !== reference.trialKey ||
value.reference.index !== reference.index ||
value.reference.runId !== reference.runId ||
value.reference.summaryAvailable !== reference.comparable ||
value.reference.diagnostic !== reference.diagnostic
) {
throw invalid();
}
const expectedRows = experiments.flatMap(experiment =>
experiment.trials.map(trial => ({ experimentId: experiment.id, trial }))
);
if (value.rows.length !== expectedRows.length) {
throw invalid();
}
value.rows.forEach((row, index) => {
const expected = expectedRows[index],
order = row.differences.map(key => experimentComparisonDimensions.indexOf(key));
if (
!expected ||
row.experimentId !== expected.experimentId ||
row.trialKey !== expected.trial.trialKey ||
order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) ||
(row.inputCompatibility === 'match') !== (row.differences.length === 0) ||
row.summaryAvailable !== expected.trial.comparable ||
row.ready !==
(row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable)
) {
throw invalid();
}
});
return { ...value, experiments };
}
export const experimentComparisonApi = {
async get(
input: ExperimentComparisonInput,
signal?: AbortSignal
): Promise<ExperimentComparisonView> {
const normalized = experimentComparisonInputSchema.parse(input);
const query = new URLSearchParams(normalized);
const response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/compare?${query}`, {
signal,
});
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
const message = z.object({ error: z.string() }).safeParse(body);
throw new Error(
message.success ? message.data.error : `Comparison unavailable (${response.status})`
);
}
try {
if (response.status !== 200) {
throw invalid();
}
return parseExperimentComparison(
z.object({ comparison: z.unknown() }).parse(body).comparison,
normalized
);
} catch {
throw invalid();
}
},
};