388 lines
13 KiB
TypeScript
388 lines
13 KiB
TypeScript
import { z } from 'zod';
|
|
import {
|
|
chronologicalValidationInputSchema,
|
|
type ChronologicalValidationActionReceipt,
|
|
type ChronologicalValidationDetail,
|
|
type ChronologicalValidationFinalizationInput,
|
|
type ChronologicalValidationSelectionInput,
|
|
type ChronologicalValidationSubmission,
|
|
type ChronologicalValidationSummary,
|
|
type ValidationResultEvidence,
|
|
} from '@stock-bot/stock-config/chronological-validation';
|
|
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
|
import {
|
|
parseChronologicalValidationPreview,
|
|
type ChronologicalValidationPreviewView,
|
|
} from './chronologicalValidationApi';
|
|
import {
|
|
experimentMetricsSchema,
|
|
parseExperimentDetail,
|
|
type ExperimentDetailView,
|
|
} from './experimentApi';
|
|
|
|
export type ValidationDetailView = Omit<ChronologicalValidationDetail, 'preview' | 'phases'> & {
|
|
preview: ChronologicalValidationPreviewView;
|
|
phases: Array<{
|
|
phase: 'train' | 'validation' | 'test';
|
|
status: 'not-admitted' | 'admitted' | 'missing';
|
|
experimentId: string | null;
|
|
experiment: ExperimentDetailView | null;
|
|
}>;
|
|
};
|
|
export class ValidationApiError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly status: number | null
|
|
) {
|
|
super(message);
|
|
}
|
|
get ambiguous() {
|
|
return this.status === null || this.status >= 500;
|
|
}
|
|
}
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
|
uuid = z.string().uuid(),
|
|
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
const candidate = z.object({
|
|
index: count,
|
|
trialKey: hash,
|
|
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
|
});
|
|
const actor = z.enum(['operator', 'service']);
|
|
const summary = z.object({
|
|
id: uuid,
|
|
name: z.string().min(1),
|
|
backtestId: uuid,
|
|
createdAt: z.string().min(1),
|
|
cancelRequested: z.boolean(),
|
|
previewHash: hash,
|
|
trainingCandidateCount: count.min(1).max(100),
|
|
stage: z.enum(['training', 'holdouts', 'reported']),
|
|
});
|
|
export const validationEvidenceSchema = z.object({
|
|
phase: z.enum(['train', 'validation', 'test']),
|
|
experimentId: uuid,
|
|
runId: uuid,
|
|
sourceCandidateIndex: count,
|
|
trialKey: hash,
|
|
parameters: candidate.shape.parameters,
|
|
datasetHash: hash,
|
|
requestHash: hash,
|
|
economicHash: hash,
|
|
metrics: experimentMetricsSchema,
|
|
unavailable: z.record(z.string()),
|
|
completePeriodCount: count,
|
|
periodicSampleCount: count,
|
|
fillCount: count,
|
|
limitations: z.array(z.string()),
|
|
});
|
|
const selection = z.object({
|
|
version: z.literal('chronological-validation-selection/v1'),
|
|
id: uuid,
|
|
validationId: uuid,
|
|
previewHash: hash,
|
|
selectionHash: hash,
|
|
createdAt: z.string().min(1),
|
|
principal: actor,
|
|
reviewId: uuid,
|
|
winner: candidate,
|
|
training: z.array(validationEvidenceSchema).min(1).max(100),
|
|
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
|
});
|
|
const report = z.object({
|
|
version: z.literal('chronological-validation-report/v1'),
|
|
id: uuid,
|
|
validationId: uuid,
|
|
previewHash: hash,
|
|
selectionHash: hash,
|
|
reportHash: hash,
|
|
createdAt: z.string().min(1),
|
|
principal: actor,
|
|
reset: z.literal('initial-capital-empty-positions'),
|
|
training: z.array(validationEvidenceSchema).min(1).max(100),
|
|
validation: validationEvidenceSchema,
|
|
test: validationEvidenceSchema,
|
|
limitations: z.array(z.string()),
|
|
});
|
|
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
|
const phase = z.object({
|
|
phase: z.enum(['train', 'validation', 'test']),
|
|
status: z.enum(['not-admitted', 'admitted', 'missing']),
|
|
experimentId: uuid.nullable(),
|
|
experiment: z.unknown(),
|
|
});
|
|
const detail = summary.extend({
|
|
preview: z.unknown(),
|
|
phases: z.tuple([phase, phase, phase]),
|
|
selection: selection.nullable(),
|
|
report: report.nullable(),
|
|
actions: z.object({ select: capability, finalize: capability }),
|
|
});
|
|
const receipt = z.object({
|
|
id: uuid,
|
|
validationId: uuid,
|
|
operation: z.enum(['select-and-admit-holdouts', 'finalize-report']),
|
|
previewHash: hash,
|
|
selectionHash: hash,
|
|
createdAt: z.string().min(1),
|
|
principal: actor,
|
|
});
|
|
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
|
const invalid = () =>
|
|
new ValidationApiError(
|
|
'The saved validation response could not be verified. Refresh or retry the same request.',
|
|
null
|
|
);
|
|
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
|
const value = detail.parse(raw);
|
|
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
|
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
|
if (
|
|
value.backtestId !== preview.input.backtestId ||
|
|
value.name !== preview.input.name ||
|
|
value.previewHash !== preview.previewHash ||
|
|
value.trainingCandidateCount !== preview.source.candidates.length ||
|
|
(value.stage === 'training') !== (value.selection === null) ||
|
|
(value.stage === 'reported') !== (value.report !== null)
|
|
) {
|
|
throw invalid();
|
|
}
|
|
const phases = value.phases.map((item, index) => {
|
|
const name = (['train', 'validation', 'test'] as const)[index];
|
|
if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) {
|
|
throw invalid();
|
|
}
|
|
const expectedId =
|
|
name === 'train'
|
|
? value.id
|
|
: (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null);
|
|
if (
|
|
item.experimentId !== expectedId ||
|
|
(item.status === 'not-admitted') !== (expectedId === null)
|
|
) {
|
|
throw invalid();
|
|
}
|
|
const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment);
|
|
if (experiment) {
|
|
const prototype = preview.partitions[index];
|
|
const parameters =
|
|
name === 'train'
|
|
? prototype?.request.strategy.selection.parameters
|
|
: value.selection?.winner.parameters;
|
|
if (!prototype || !parameters) {
|
|
throw invalid();
|
|
}
|
|
const expectedRequest = {
|
|
...prototype.request,
|
|
strategy: {
|
|
...prototype.request.strategy,
|
|
reviewId:
|
|
name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId,
|
|
selection: { ...prototype.request.strategy.selection, parameters },
|
|
},
|
|
};
|
|
const expectedCandidates =
|
|
name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }];
|
|
if (
|
|
experiment.id !== expectedId ||
|
|
experiment.backtestId !== value.backtestId ||
|
|
!same(experiment.preview.request, expectedRequest) ||
|
|
!same(experiment.preview.dataset, prototype.dataset) ||
|
|
!same(experiment.preview.candidates, expectedCandidates) ||
|
|
!same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {})
|
|
) {
|
|
throw invalid();
|
|
}
|
|
}
|
|
return { ...item, experiment };
|
|
});
|
|
const validateEvidence = (
|
|
item: z.infer<typeof validationEvidenceSchema>,
|
|
expectedPhase: 'train' | 'validation' | 'test'
|
|
) => {
|
|
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
|
const candidateValue = preview.source.candidates[item.sourceCandidateIndex];
|
|
const phaseValue = phases[index];
|
|
const trial = phaseValue?.experiment?.trials.find(
|
|
trial => trial.runId === item.runId && trial.trialKey === item.trialKey
|
|
);
|
|
if (
|
|
!candidateValue ||
|
|
!phaseValue ||
|
|
item.phase !== expectedPhase ||
|
|
item.experimentId !== phaseValue.experimentId ||
|
|
item.trialKey !== candidateValue.trialKey ||
|
|
!same(item.parameters, candidateValue.parameters) ||
|
|
item.datasetHash !== preview.partitions[index]?.dataset.hash ||
|
|
(expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) ||
|
|
(phaseValue.experiment &&
|
|
(!trial ||
|
|
trial.status !== 'completed' ||
|
|
!trial.comparable ||
|
|
!same(trial.metrics, item.metrics) ||
|
|
!same(trial.unavailable, item.unavailable) ||
|
|
!same(trial.limitations, item.limitations)))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
};
|
|
if (value.selection) {
|
|
const chosen = value.selection;
|
|
if (
|
|
chosen.validationId !== value.id ||
|
|
chosen.previewHash !== value.previewHash ||
|
|
!same(chosen.winner, preview.source.candidates[chosen.winner.index]) ||
|
|
chosen.training.length !== value.trainingCandidateCount ||
|
|
chosen.training.some((item, index) => item.sourceCandidateIndex !== index) ||
|
|
new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test])
|
|
.size !== 3
|
|
) {
|
|
throw invalid();
|
|
}
|
|
for (const item of chosen.training) {
|
|
validateEvidence(item, 'train');
|
|
if (item.metrics.totalReturn === null) {
|
|
throw invalid();
|
|
}
|
|
}
|
|
}
|
|
if (value.report) {
|
|
const saved = value.report;
|
|
if (
|
|
!value.selection ||
|
|
saved.validationId !== value.id ||
|
|
saved.previewHash !== value.previewHash ||
|
|
saved.selectionHash !== value.selection.selectionHash ||
|
|
!same(saved.training, value.selection.training)
|
|
) {
|
|
throw invalid();
|
|
}
|
|
validateEvidence(saved.validation, 'validation');
|
|
validateEvidence(saved.test, 'test');
|
|
}
|
|
if (
|
|
(value.actions.select.available && (value.selection || value.cancelRequested)) ||
|
|
(value.actions.finalize.available &&
|
|
(!value.selection || value.report || value.cancelRequested))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
return { ...value, preview, phases } as ValidationDetailView;
|
|
}
|
|
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
|
async function request<T>(
|
|
path: string,
|
|
init: RequestInit,
|
|
status: number,
|
|
parse: (body: unknown) => T
|
|
): Promise<T> {
|
|
let response: Response;
|
|
try {
|
|
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init);
|
|
} catch (cause) {
|
|
if (init.signal?.aborted) {
|
|
throw cause;
|
|
}
|
|
throw new ValidationApiError(
|
|
'The validation response was lost. Retry the same request to recover its receipt.',
|
|
null
|
|
);
|
|
}
|
|
const body: unknown = await response.json().catch(() => null);
|
|
if (!response.ok) {
|
|
const error = z.object({ error: z.string() }).safeParse(body);
|
|
throw new ValidationApiError(
|
|
error.success ? error.data.error : `Validation request failed (${response.status})`,
|
|
response.status
|
|
);
|
|
}
|
|
try {
|
|
if (response.status !== status) {
|
|
throw invalid();
|
|
}
|
|
return parse(body);
|
|
} catch {
|
|
throw invalid();
|
|
}
|
|
}
|
|
const post = (body: unknown, key?: string): RequestInit => ({
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
|
});
|
|
export const chronologicalValidationDurableApi = {
|
|
list: (backtestId?: string, signal?: AbortSignal) =>
|
|
request(
|
|
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
|
|
{ signal },
|
|
200,
|
|
body => {
|
|
const rows = z.array(summary).parse(envelope(body, 'validations'));
|
|
if (
|
|
new Set(rows.map(row => row.id)).size !== rows.length ||
|
|
(backtestId && rows.some(row => row.backtestId !== backtestId))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
return rows as ChronologicalValidationSummary[];
|
|
}
|
|
),
|
|
get: (id: string, signal?: AbortSignal) =>
|
|
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
|
const value = parseValidationDetail(envelope(body, 'validation'));
|
|
if (value.id !== id) {
|
|
throw invalid();
|
|
}
|
|
return value;
|
|
}),
|
|
submit: (input: ChronologicalValidationSubmission, key: string) =>
|
|
request('', post(input, key), 202, body => {
|
|
const value = parseValidationDetail(envelope(body, 'validation'));
|
|
const { previewHash, ...original } = input;
|
|
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
|
throw invalid();
|
|
}
|
|
return value;
|
|
}),
|
|
advance: (
|
|
id: string,
|
|
operation: 'select' | 'finalize',
|
|
input: ChronologicalValidationSelectionInput | ChronologicalValidationFinalizationInput,
|
|
key: string
|
|
) =>
|
|
request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => {
|
|
const accepted = receipt.parse(envelope(body, 'receipt'));
|
|
const value = parseValidationDetail(envelope(body, 'validation'));
|
|
const record = operation === 'select' ? value.selection : value.report;
|
|
if (
|
|
accepted.validationId !== id ||
|
|
value.id !== id ||
|
|
accepted.previewHash !== input.previewHash ||
|
|
value.previewHash !== input.previewHash ||
|
|
accepted.operation !==
|
|
(operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report') ||
|
|
accepted.selectionHash !== value.selection?.selectionHash ||
|
|
!record ||
|
|
accepted.id !== record.id ||
|
|
accepted.createdAt !== record.createdAt ||
|
|
accepted.principal !== record.principal ||
|
|
(operation === 'finalize' &&
|
|
(!('selectionHash' in input) ||
|
|
accepted.selectionHash !== input.selectionHash ||
|
|
!value.report))
|
|
) {
|
|
throw invalid();
|
|
}
|
|
return { receipt: accepted as ChronologicalValidationActionReceipt, validation: value };
|
|
}),
|
|
cancel: (id: string) =>
|
|
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
|
const value = parseValidationDetail(envelope(body, 'validation'));
|
|
if (value.id !== id || !value.cancelRequested) {
|
|
throw invalid();
|
|
}
|
|
return value;
|
|
}),
|
|
};
|
|
export type { ValidationResultEvidence };
|