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

@ -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();
}
},
};