stock-bot/apps/stock/web-api/src/services/experiment-input.ts

186 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createHash } from 'node:crypto';
import { z } from 'zod';
import { retainedProgramSelectionSchema } from '@stock-bot/stock-config/candidate-execution';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import {
experimentInputSchema,
experimentSubmissionSchema,
MAX_EXPERIMENT_TRIALS,
type ExperimentCandidate,
type ExperimentInput,
type ExperimentPreview,
type ExperimentSubmission,
} from '@stock-bot/stock-config/experiments';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import {
assertStrategyJsonText,
builtinStrategySelectionSchema,
canonicalStrategyJson,
validateStrategyParameters,
} from '@stock-bot/stock-config/strategy';
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
export class ExperimentError extends Error {
constructor(
public readonly status: 400 | 404 | 409,
message: string
) {
super(message);
}
}
export const PREVIEW_RUN_ID = '00000000-0000-4000-8000-000000000001';
export const experimentHash = (value: unknown) =>
createHash('sha256').update(canonicalStrategyJson(value)).digest('hex');
export function parseExperimentInput(input: unknown): ExperimentInput {
try {
assertStrategyJsonText(input);
return experimentInputSchema.parse(input);
} catch {
throw new ExperimentError(400, 'Invalid experiment input');
}
}
export function parseExperimentSubmission(input: unknown): ExperimentSubmission {
try {
assertStrategyJsonText(input);
return experimentSubmissionSchema.parse(input);
} catch {
throw new ExperimentError(400, 'Invalid experiment submission');
}
}
export function experimentId(input: unknown): string {
const parsed = z.string().uuid().safeParse(input);
if (!parsed.success) {
throw new ExperimentError(400, 'Invalid experiment or backtest ID');
}
return parsed.data;
}
export function experimentReceipt(input: { principal: string; key: string }) {
const parsed = z
.object({
principal: researchActorSchema,
key: z.string().regex(/^[\x21-\x7e]{1,200}$/),
})
.strict()
.safeParse(input);
if (!parsed.success) {
throw new ExperimentError(
400,
'A verified principal and visible ASCII Idempotency-Key of 1–200 characters are required'
);
}
return parsed.data;
}
/** Parameter grids never change data, accounting, execution or analysis policy. */
export function experimentCandidates(
input: ExperimentInput,
request: CanonicalRunRequest
): ExperimentCandidate[] {
const axes = Object.keys(input.grid).sort();
let count = 1;
for (const name of axes) {
if (
!Object.hasOwn(request.strategy.package.parameterSchema.properties, name) ||
['__proto__', 'constructor', 'prototype'].includes(name)
) {
throw new ExperimentError(400, `Unknown or reserved parameter: ${name}`);
}
const values = input.grid[name] ?? [];
if (new Set(values.map(canonicalStrategyJson)).size !== values.length) {
throw new ExperimentError(400, `Duplicate values for parameter: ${name}`);
}
count *= values.length;
if (count > MAX_EXPERIMENT_TRIALS) {
throw new ExperimentError(
400,
`An experiment may contain at most ${MAX_EXPERIMENT_TRIALS} trials`
);
}
}
let combinations = [{ ...request.strategy.selection.parameters }];
for (const name of axes) {
combinations = combinations.flatMap(parameters =>
(input.grid[name] ?? []).map(value => ({ ...parameters, [name]: value }))
);
}
const keys = new Set<string>();
return combinations.map((parameters, index) => {
try {
const validated = validateStrategyParameters(request.strategy.package, parameters);
const selection = (
request.strategy.origin === 'candidate'
? retainedProgramSelectionSchema
: builtinStrategySelectionSchema
).parse({
...request.strategy.selection,
parameters: validated,
});
const trialKey = experimentHash({ version: 1, parameters: selection.parameters });
if (keys.has(trialKey)) {
throw new Error('Duplicate normalized parameter combination');
}
keys.add(trialKey);
return { index, parameters: selection.parameters, trialKey };
} catch (cause) {
throw new ExperimentError(
400,
`Invalid parameter combination ${index + 1}: ${cause instanceof Error ? cause.message : 'validation failed'}`
);
}
});
}
export function buildExperimentPreview(
input: ExperimentInput,
request: CanonicalRunRequest,
dataset: HistoricalDatasetManifestV2
): ExperimentPreview {
const manifest = {
version: 'research-experiment-preview/v1' as const,
input,
request,
dataset,
candidates: experimentCandidates(input, request),
};
return { ...manifest, previewHash: experimentHash(manifest) };
}
export function experimentTrialRequest(
preview: ExperimentPreview,
candidate: ExperimentCandidate,
runId: string
): CanonicalRunRequest {
const request = structuredClone(preview.request);
request.runId = runId;
request.policy.matching.risk.ledger.sessionId = runId;
request.policy.matching.risk.ledger.accountId = `research:${runId}`;
return canonicalRunRequestSchema.parse({
...request,
strategy: {
...request.strategy,
selection: { ...request.strategy.selection, parameters: candidate.parameters },
},
});
}
/** Fail closed for corrupt saved manifests; do not relabel storage failures as user errors. */
export function retainedExperimentPreview(value: unknown): ExperimentPreview {
const preview = value as ExperimentPreview;
const input = experimentInputSchema.parse(preview.input);
const request = canonicalRunRequestSchema.parse(preview.request);
if (request.runId !== PREVIEW_RUN_ID || request.backtestId !== input.backtestId) {
throw new Error('Retained experiment request identity mismatch');
}
if (!preview.dataset || preview.dataset.hash !== request.datasetHash) {
throw new Error('Retained experiment dataset identity mismatch');
}
let expected;
try {
expected = buildExperimentPreview(input, request, preview.dataset);
} catch {
throw new Error('Retained experiment candidates failed integrity validation');
}
if (canonicalStrategyJson(preview) !== canonicalStrategyJson(expected)) {
throw new Error('Retained experiment preview integrity failure');
}
return expected;
}