feat(research): add retained-input parameter sweep workbench
This commit is contained in:
parent
30accfcf43
commit
6f64ef62ba
41 changed files with 4469 additions and 34 deletions
180
apps/stock/web-api/src/services/experiment-input.ts
Normal file
180
apps/stock/web-api/src/services/experiment-input.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
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 {
|
||||
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: z.enum(['operator', 'service']),
|
||||
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 = 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;
|
||||
}
|
||||
420
apps/stock/web-api/src/services/experiments.service.ts
Normal file
420
apps/stock/web-api/src/services/experiments.service.ts
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type {
|
||||
ExperimentCounts,
|
||||
ExperimentDetail,
|
||||
ExperimentInput,
|
||||
ExperimentPreview,
|
||||
ExperimentSummary,
|
||||
ExperimentTrial,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
import { admitCanonicalRequest, readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
parseExperimentInput,
|
||||
parseExperimentSubmission,
|
||||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { StrategyCatalogError } from './strategy-catalog.service';
|
||||
|
||||
interface Query {
|
||||
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
||||
}
|
||||
const equal = (left: unknown, right: unknown) =>
|
||||
left !== undefined &&
|
||||
right !== undefined &&
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const metricsSchema = z
|
||||
.object({
|
||||
totalReturn: z.number().finite().nullable(),
|
||||
cagr: z.number().finite().nullable(),
|
||||
maxDrawdown: z.number().finite().nullable(),
|
||||
exposureTime: z.number().finite().nullable(),
|
||||
volatility: z.number().finite().nullable(),
|
||||
downsideDeviation: z.number().finite().nullable(),
|
||||
sharpeRatio: z.number().finite().nullable(),
|
||||
sortinoRatio: z.number().finite().nullable(),
|
||||
var95: z.number().finite().nullable(),
|
||||
cvar95: z.number().finite().nullable(),
|
||||
var99: z.number().finite().nullable(),
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
})
|
||||
.strict();
|
||||
const reasons = z.enum([
|
||||
'nonpositive-baseline',
|
||||
'negative-terminal-equity',
|
||||
'zero-duration',
|
||||
'nonfinite-result',
|
||||
'undefined-period-return',
|
||||
'insufficient-periods',
|
||||
'missing-risk-free',
|
||||
'missing-benchmark',
|
||||
'zero-variance',
|
||||
'zero-downside-deviation',
|
||||
'unsupported-round-trips',
|
||||
]);
|
||||
const unavailableSchema = z.record(metricsSchema.keyof(), reasons);
|
||||
const summaryColumns = `e.id,e.name,e.backtest_id,e.created_at,e.cancel_requested,e.preview_hash,
|
||||
jsonb_array_length(e.preview->'candidates') AS trial_count,
|
||||
e.preview#>>'{request,datasetHash}' AS dataset_hash,
|
||||
e.preview#>>'{request,strategy,versionId}' AS strategy_version_id,
|
||||
(SELECT jsonb_object_agg(status, n) FROM (SELECT status,count(*) AS n FROM runs WHERE experiment_id=e.id GROUP BY status) counts) AS counts`;
|
||||
const summary = (row: QueryResultRow): ExperimentSummary => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
backtestId: row.backtest_id,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
cancelRequested: row.cancel_requested,
|
||||
trialCount: Number(row.trial_count),
|
||||
datasetHash: row.dataset_hash,
|
||||
strategyVersionId: row.strategy_version_id,
|
||||
previewHash: row.preview_hash,
|
||||
counts: Object.fromEntries(
|
||||
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
||||
status,
|
||||
Number(row.counts?.[status] ?? 0),
|
||||
])
|
||||
) as ExperimentCounts,
|
||||
});
|
||||
|
||||
/** The manifest receipt and all durable children commit together; the existing worker owns execution. */
|
||||
export class ExperimentsService {
|
||||
private readonly database;
|
||||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
}
|
||||
async preview(raw: unknown): Promise<ExperimentPreview> {
|
||||
const input = parseExperimentInput(raw);
|
||||
return this.database.transaction(client => this.lockedPreview(client, input));
|
||||
}
|
||||
private async lockedPreview(
|
||||
client: PoolClient,
|
||||
input: ExperimentInput
|
||||
): Promise<ExperimentPreview> {
|
||||
const parent = (
|
||||
await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId])
|
||||
).rows[0];
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Backtest not found');
|
||||
}
|
||||
if (parent.archived_at !== null) {
|
||||
throw new ExperimentError(409, 'Restore the archived backtest before creating an experiment');
|
||||
}
|
||||
if (!parent.strategy_version_id) {
|
||||
throw new ExperimentError(409, 'Experiments require a retained canonical built-in template');
|
||||
}
|
||||
let request;
|
||||
try {
|
||||
request = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
{
|
||||
name: parent.name,
|
||||
strategyVersionId: parent.strategy_version_id,
|
||||
strategyParameters: parent.strategy_parameters,
|
||||
symbols: parent.symbols,
|
||||
startDate: parent.start_date,
|
||||
endDate: parent.end_date,
|
||||
initialCapital: Number(parent.initial_capital),
|
||||
config: parent.config,
|
||||
},
|
||||
input.backtestId,
|
||||
PREVIEW_RUN_ID
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause instanceof HistoricalDataRequestError ||
|
||||
cause instanceof StrategyCatalogError ||
|
||||
cause instanceof z.ZodError
|
||||
) {
|
||||
throw new ExperimentError(409, `Canonical experiment unavailable: ${cause.message}`);
|
||||
}
|
||||
if (
|
||||
cause &&
|
||||
typeof cause === 'object' &&
|
||||
'code' in cause &&
|
||||
['ENOENT', 'ENOTDIR', 'EACCES'].includes(String(cause.code))
|
||||
) {
|
||||
throw new ExperimentError(409, 'The canonical build is not installed');
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
return buildExperimentPreview(
|
||||
input,
|
||||
request,
|
||||
(await readCanonicalDataset(client, request.datasetHash)).manifest
|
||||
);
|
||||
}
|
||||
async submit(raw: unknown, actor: { principal: string; key: string }): Promise<ExperimentDetail> {
|
||||
const submission = parseExperimentSubmission(raw);
|
||||
const receipt = experimentReceipt(actor);
|
||||
const { previewHash, ...input } = submission;
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'SELECT id,submission_hash FROM research_experiments WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[receipt.principal, receipt.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (row && row.submission_hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different experiment intent'
|
||||
);
|
||||
}
|
||||
return row ? this.readDetail(client, row.id) : null;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
// Serialize same-parent admissions, then recheck accepted receipts before current eligibility.
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const preview = await this.lockedPreview(client, input);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Experiment preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
const experimentId = randomUUID();
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_experiments (id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
experimentId,
|
||||
input.backtestId,
|
||||
input.name,
|
||||
preview,
|
||||
previewHash,
|
||||
receipt.principal,
|
||||
receipt.key,
|
||||
hash,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent experiment receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
let runNumber = Number(
|
||||
(
|
||||
await client.query(
|
||||
'SELECT COALESCE(MAX(run_number),0) AS n FROM runs WHERE backtest_id=$1',
|
||||
[input.backtestId]
|
||||
)
|
||||
).rows[0].n
|
||||
);
|
||||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID();
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
await client.query(
|
||||
`INSERT INTO runs (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
runId,
|
||||
input.backtestId,
|
||||
++runNumber,
|
||||
request,
|
||||
request.datasetHash,
|
||||
experimentId,
|
||||
candidate.trialKey,
|
||||
candidate.index,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
}
|
||||
return this.readDetail(client, experimentId);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<ExperimentSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT ${summaryColumns} FROM research_experiments e
|
||||
${backtestId === undefined ? '' : 'WHERE e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
async get(id: string): Promise<ExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.readDetail(this.database, id);
|
||||
}
|
||||
async cancel(id: string): Promise<ExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1 RETURNING id',
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE runs SET cancel_requested=TRUE,
|
||||
status=CASE WHEN status='pending' THEN 'cancelled'::run_status ELSE status END,
|
||||
completed_at=CASE WHEN status='pending' THEN NOW() ELSE completed_at END,updated_at=NOW()
|
||||
WHERE experiment_id=$1 AND status IN ('pending','running','paused')`,
|
||||
[id]
|
||||
);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
private async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
const row = (
|
||||
await database.query(
|
||||
`SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`,
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
const preview = retainedExperimentPreview(row.preview);
|
||||
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
|
||||
const runs = (
|
||||
await database.query(
|
||||
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
|
||||
br.canonical_result->>'kind' AS result_kind,br.canonical_result->>'status' AS result_status,
|
||||
br.canonical_result->>'runId' AS result_run_id,br.canonical_result->>'backtestId' AS result_backtest_id,
|
||||
br.canonical_result->>'financialEngine' AS financial_engine,br.canonical_result->>'strategyExecution' AS strategy_execution,
|
||||
br.canonical_result->'request' AS result_request,br.canonical_result#>'{analytics,policy}' AS analytics_policy,
|
||||
br.canonical_result#>'{analytics,version}' AS analytics_version,
|
||||
br.canonical_result#>'{financial,identity}' AS financial_identity,br.canonical_result#>'{financial,policy}' AS financial_policy,
|
||||
br.canonical_result#>'{analytics,metrics}' AS metrics,br.canonical_result#>'{analytics,unavailable}' AS unavailable,
|
||||
br.canonical_result#>'{financial,limitations}' AS limitations,br.canonical_result#>'{financial,modelLimitations}' AS model_limitations
|
||||
FROM runs r LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.experiment_id=$1 ORDER BY r.trial_index`,
|
||||
[id]
|
||||
)
|
||||
).rows;
|
||||
const trials = preview.candidates.map(candidate => {
|
||||
const run = runs.find(item => item.trial_index === candidate.index);
|
||||
const trial: ExperimentTrial = {
|
||||
...candidate,
|
||||
runId: run?.id ?? null,
|
||||
status: run?.status ?? 'missing',
|
||||
progress: Number(run?.progress ?? 0),
|
||||
cancelRequested: run?.cancel_requested ?? false,
|
||||
error: run?.error ?? null,
|
||||
comparable: false,
|
||||
diagnostic: null,
|
||||
metrics: null,
|
||||
unavailable: null,
|
||||
limitations: [],
|
||||
};
|
||||
if (!run) {
|
||||
trial.diagnostic = 'Expected trial run is missing';
|
||||
return trial;
|
||||
}
|
||||
const expected = experimentTrialRequest(preview, candidate, run.id);
|
||||
if (
|
||||
run.trial_key !== candidate.trialKey ||
|
||||
run.backtest_id !== preview.input.backtestId ||
|
||||
run.dataset_hash !== expected.datasetHash ||
|
||||
!equal(run.request_snapshot, expected)
|
||||
) {
|
||||
trial.diagnostic = 'Retained run inputs do not match the frozen experiment';
|
||||
return trial;
|
||||
}
|
||||
if (run.status !== 'completed') {
|
||||
trial.diagnostic = run.error ?? `Trial is ${run.status}`;
|
||||
return trial;
|
||||
}
|
||||
const expectedPolicy: CanonicalBacktestAnalytics['policy'] = {
|
||||
...expected.analyticsPolicy,
|
||||
calendarId: expected.policy.matching.risk.ledger.riskSession.calendarId,
|
||||
calendarRevision: expected.policy.matching.risk.ledger.riskSession.calendarRevision,
|
||||
sampling: 'account-boundary-after-observations-v1',
|
||||
marks: 'last-available-no-per-session-freshness-certification',
|
||||
returnUnit: 'fraction',
|
||||
variance: 'sample-n-minus-one',
|
||||
riskFreeConversion: 'annual-rate-divided-by-periods-per-year',
|
||||
downside: 'full-series-rms-relative-to-risk-free',
|
||||
partialPeriods: 'visible-excluded-from-periodic-statistics',
|
||||
drawdown: 'session-end-and-terminal-sampled',
|
||||
exposureBasis: 'elapsed-calendar-time',
|
||||
cagrBasis: 'elapsed-calendar-days-365',
|
||||
zeroTerminalCagr: 'negative-one-for-positive-elapsed-time',
|
||||
};
|
||||
const metrics = metricsSchema.safeParse(run.metrics);
|
||||
const unavailable = unavailableSchema.safeParse(run.unavailable);
|
||||
if (
|
||||
run.result_kind !== 'canonical-result/v1' ||
|
||||
run.result_status !== 'completed' ||
|
||||
run.result_run_id !== run.id ||
|
||||
run.result_backtest_id !== expected.backtestId ||
|
||||
run.financial_engine !== 'rust' ||
|
||||
run.strategy_execution !== 'typescript-retained-builtin/v1' ||
|
||||
!equal(run.result_request, expected) ||
|
||||
run.analytics_version !== 1 ||
|
||||
!equal(run.analytics_policy, expectedPolicy) ||
|
||||
!equal(run.financial_identity, {
|
||||
version: 1,
|
||||
sessionId: run.id,
|
||||
datasetHash: expected.datasetHash,
|
||||
}) ||
|
||||
!equal(run.financial_policy, expected.policy) ||
|
||||
!metrics.success ||
|
||||
!unavailable.success ||
|
||||
!Array.isArray(run.model_limitations) ||
|
||||
run.model_limitations.some((item: unknown) => typeof item !== 'string') ||
|
||||
!Array.isArray(run.limitations) ||
|
||||
run.limitations.some((item: unknown) => typeof item !== 'string')
|
||||
) {
|
||||
trial.diagnostic = 'Completed result provenance or metrics are unavailable or inconsistent';
|
||||
return trial;
|
||||
}
|
||||
if (
|
||||
Object.entries(metrics.data).some(([key, value]) =>
|
||||
value === null
|
||||
? !Object.hasOwn(unavailable.data, key)
|
||||
: Object.hasOwn(unavailable.data, key)
|
||||
)
|
||||
) {
|
||||
trial.diagnostic = 'Completed result metric availability is inconsistent';
|
||||
return trial;
|
||||
}
|
||||
trial.comparable = true;
|
||||
trial.metrics = metrics.data;
|
||||
trial.unavailable = unavailable.data;
|
||||
trial.limitations = [...run.limitations, ...run.model_limitations];
|
||||
return trial;
|
||||
});
|
||||
const counts = summary({ ...row, counts: {} }).counts;
|
||||
for (const run of runs) {
|
||||
if (Object.hasOwn(counts, run.status)) {
|
||||
counts[run.status as keyof ExperimentCounts]++;
|
||||
}
|
||||
}
|
||||
return { ...summary(row), counts, preview, trials };
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue