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