feat(research): run durable chronological validation and retain reports
This commit is contained in:
parent
67ab30cb7a
commit
abd1c5b83d
42 changed files with 5345 additions and 74 deletions
|
|
@ -1,8 +1,13 @@
|
|||
/** Prepared inputs only: this contract does not admit runs or certify out-of-sample evidence. */
|
||||
import { z } from 'zod';
|
||||
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
||||
import type { CanonicalBacktestAnalytics, HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
||||
import type { CanonicalRunRequest } from './canonical-research';
|
||||
import { experimentInputSchema, type ExperimentPreview } from './experiments';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
type ExperimentCandidate,
|
||||
type ExperimentDetail,
|
||||
type ExperimentPreview,
|
||||
} from './experiments';
|
||||
|
||||
const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
export const validationWindowSchema = z
|
||||
|
|
@ -73,3 +78,119 @@ export interface ChronologicalValidationPreview {
|
|||
policy: typeof chronologicalValidationPolicy;
|
||||
partitions: [ValidationPartitionPreview, ValidationPartitionPreview, ValidationPartitionPreview];
|
||||
}
|
||||
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
export const chronologicalValidationSubmissionSchema = chronologicalValidationInputSchema.extend({
|
||||
previewHash: hash,
|
||||
});
|
||||
export const chronologicalValidationSelectionSchema = z.object({ previewHash: hash }).strict();
|
||||
export const chronologicalValidationFinalizationSchema = z
|
||||
.object({ previewHash: hash, selectionHash: hash })
|
||||
.strict();
|
||||
export type ChronologicalValidationSubmission = z.infer<
|
||||
typeof chronologicalValidationSubmissionSchema
|
||||
>;
|
||||
export type ChronologicalValidationSelectionInput = z.infer<
|
||||
typeof chronologicalValidationSelectionSchema
|
||||
>;
|
||||
export type ChronologicalValidationFinalizationInput = z.infer<
|
||||
typeof chronologicalValidationFinalizationSchema
|
||||
>;
|
||||
|
||||
/** Copied only after validating the retained financial envelope and its canonical analytics. */
|
||||
export interface ValidationResultEvidence {
|
||||
phase: ValidationPhase;
|
||||
experimentId: string;
|
||||
runId: string;
|
||||
/** Original training-grid index; holdout experiment local index is always zero. */
|
||||
sourceCandidateIndex: number;
|
||||
trialKey: string;
|
||||
parameters: ExperimentCandidate['parameters'];
|
||||
datasetHash: string;
|
||||
requestHash: string;
|
||||
economicHash: string;
|
||||
metrics: CanonicalBacktestAnalytics['metrics'];
|
||||
unavailable: CanonicalBacktestAnalytics['unavailable'];
|
||||
completePeriodCount: number;
|
||||
periodicSampleCount: number;
|
||||
fillCount: number;
|
||||
limitations: string[];
|
||||
}
|
||||
export interface ChronologicalValidationSelection {
|
||||
version: 'chronological-validation-selection/v1';
|
||||
id: string;
|
||||
validationId: string;
|
||||
previewHash: string;
|
||||
selectionHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
/** Current original-version approval for the new holdout admissions. */
|
||||
reviewId: string;
|
||||
winner: ExperimentCandidate;
|
||||
/** All training candidates in ascending original candidate index. */
|
||||
training: ValidationResultEvidence[];
|
||||
holdoutExperimentIds: { validation: string; test: string };
|
||||
}
|
||||
export interface ChronologicalValidationReport {
|
||||
version: 'chronological-validation-report/v1';
|
||||
id: string;
|
||||
validationId: string;
|
||||
previewHash: string;
|
||||
selectionHash: string;
|
||||
reportHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
/** Independent reset accounts. This is not a continuous portfolio equity curve. */
|
||||
reset: 'initial-capital-empty-positions';
|
||||
/** All training candidates in ascending original candidate index. */
|
||||
training: ValidationResultEvidence[];
|
||||
validation: ValidationResultEvidence;
|
||||
test: ValidationResultEvidence;
|
||||
limitations: string[];
|
||||
}
|
||||
export interface ChronologicalValidationActionReceipt {
|
||||
id: string;
|
||||
validationId: string;
|
||||
operation: 'select-and-admit-holdouts' | 'finalize-report';
|
||||
previewHash: string;
|
||||
selectionHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
}
|
||||
export interface ValidationActionCapability {
|
||||
available: boolean;
|
||||
reason: string | null;
|
||||
}
|
||||
export interface ValidationPhaseState {
|
||||
phase: ValidationPhase;
|
||||
status: 'not-admitted' | 'admitted' | 'missing';
|
||||
experimentId: string | null;
|
||||
/** Existing experiment semantics apply within each single-dataset phase. */
|
||||
experiment: ExperimentDetail | null;
|
||||
}
|
||||
export interface ChronologicalValidationSummary {
|
||||
/** The validation owner is its training experiment. */
|
||||
id: string;
|
||||
name: string;
|
||||
backtestId: string;
|
||||
createdAt: string;
|
||||
cancelRequested: boolean;
|
||||
previewHash: string;
|
||||
trainingCandidateCount: number;
|
||||
stage: 'training' | 'holdouts' | 'reported';
|
||||
}
|
||||
export interface ChronologicalValidationDetail extends ChronologicalValidationSummary {
|
||||
/** The original prepared-input identity is retained unchanged at durable admission. */
|
||||
preview: ChronologicalValidationPreview;
|
||||
phases: [ValidationPhaseState, ValidationPhaseState, ValidationPhaseState];
|
||||
selection: ChronologicalValidationSelection | null;
|
||||
report: ChronologicalValidationReport | null;
|
||||
actions: {
|
||||
select: ValidationActionCapability;
|
||||
finalize: ValidationActionCapability;
|
||||
};
|
||||
}
|
||||
export interface ChronologicalValidationActionResult {
|
||||
receipt: ChronologicalValidationActionReceipt;
|
||||
validation: ChronologicalValidationDetail;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,7 +63,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '20-research-workspace.sql' ||
|
||||
f === '21-run-reproduction.sql' ||
|
||||
f === '22-experiments.sql' ||
|
||||
f === '23-experiment-retries.sql')
|
||||
f === '23-experiment-retries.sql' ||
|
||||
f === '24-chronological-validation.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { z } from 'zod';
|
|||
import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { ChronologicalValidationService } from '../services/chronological-validation.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentId,
|
||||
|
|
@ -12,12 +13,18 @@ import {
|
|||
} from '../services/experiment-input';
|
||||
import { parseExperimentRetry } from '../services/experiment-retry';
|
||||
import { ExperimentsService } from '../services/experiments.service';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
parseValidationSubmission,
|
||||
} from '../services/validation-evidence';
|
||||
import { parseChronologicalValidation } from '../services/validation-preview';
|
||||
|
||||
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
|
||||
export function createExperimentRoutes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const service = new ExperimentsService(container);
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const logger = getLogger('experiments-api');
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
@ -47,6 +54,66 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
const input = parseChronologicalValidation(await body(c.req.raw));
|
||||
return c.json({ preview: await service.previewValidation(input) });
|
||||
});
|
||||
app.post('/api/v2/experiments/validation', async c => {
|
||||
const input = parseValidationSubmission(await body(c.req.raw));
|
||||
const validation = await validations.submit(
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
);
|
||||
c.header('Location', `/api/v2/experiments/validation/${validation.id}`);
|
||||
return c.json({ validation }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments/validation', async c =>
|
||||
c.json({ validations: await validations.list(c.req.query('backtestId')) })
|
||||
);
|
||||
app.get('/api/v2/experiments/validation/:id', async c =>
|
||||
c.json({ validation: await validations.get(experimentId(c.req.param('id'))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/validation/:id/select', async c => {
|
||||
const id = experimentId(c.req.param('id')),
|
||||
input = parseValidationSelection(await body(c.req.raw));
|
||||
return c.json(
|
||||
await validations.select(
|
||||
id,
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
),
|
||||
202
|
||||
);
|
||||
});
|
||||
app.post('/api/v2/experiments/validation/:id/finalize', async c => {
|
||||
const id = experimentId(c.req.param('id')),
|
||||
input = parseValidationFinalization(await body(c.req.raw));
|
||||
return c.json(
|
||||
await validations.finalize(
|
||||
id,
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
),
|
||||
202
|
||||
);
|
||||
});
|
||||
app.post('/api/v2/experiments/validation/:id/cancel', async c => {
|
||||
const id = experimentId(c.req.param('id'));
|
||||
if (
|
||||
!z
|
||||
.object({})
|
||||
.strict()
|
||||
.safeParse(await body(c.req.raw)).success
|
||||
) {
|
||||
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
||||
}
|
||||
return c.json({ validation: await validations.cancel(id) });
|
||||
});
|
||||
app.post('/api/v2/experiments/preview', async c => {
|
||||
const input = parseExperimentInput(await body(c.req.raw));
|
||||
return c.json({ preview: await service.preview(input) });
|
||||
|
|
|
|||
|
|
@ -0,0 +1,673 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ChronologicalValidationActionReceipt,
|
||||
ChronologicalValidationActionResult,
|
||||
ChronologicalValidationDetail,
|
||||
ChronologicalValidationReport,
|
||||
ChronologicalValidationSelection,
|
||||
ChronologicalValidationSummary,
|
||||
ValidationPhase,
|
||||
ValidationPhaseState,
|
||||
ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
|
||||
import { BacktestServiceV2 } from './backtest-v2.service';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
} from './experiment-input';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
parseValidationSubmission,
|
||||
publicValidationDocument,
|
||||
retainedValidationPreview,
|
||||
selectValidationWinner,
|
||||
validationEqual,
|
||||
validationEvidence,
|
||||
validationPhasePreview,
|
||||
type PrivateValidationDocument,
|
||||
} from './validation-evidence';
|
||||
import { prepareChronologicalValidation } from './validation-preview';
|
||||
|
||||
type Actor = { principal: string; key: string };
|
||||
type Operation = 'select-and-admit-holdouts' | 'finalize-report';
|
||||
type Field = 'validation_selection' | 'validation_report';
|
||||
|
||||
const summary = (row: QueryResultRow): ChronologicalValidationSummary => ({
|
||||
id: row.id,
|
||||
name: row.validation_manifest.input.name,
|
||||
backtestId: row.backtest_id,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
cancelRequested: row.cancel_requested,
|
||||
previewHash: row.validation_manifest.previewHash,
|
||||
trainingCandidateCount: row.validation_manifest.source.candidates.length,
|
||||
stage: row.validation_report ? 'reported' : row.validation_selection ? 'holdouts' : 'training',
|
||||
});
|
||||
const receipt = (
|
||||
document: ChronologicalValidationSelection | ChronologicalValidationReport,
|
||||
operation: Operation
|
||||
): ChronologicalValidationActionReceipt => ({
|
||||
id: document.id,
|
||||
validationId: document.validationId,
|
||||
operation,
|
||||
previewHash: document.previewHash,
|
||||
selectionHash: document.selectionHash,
|
||||
createdAt: document.createdAt,
|
||||
principal: document.principal,
|
||||
});
|
||||
/** A bounded staged recipe, using ordinary immutable experiments/runs for every phase. */
|
||||
export class ChronologicalValidationService {
|
||||
private readonly database;
|
||||
private readonly experiments;
|
||||
private readonly results;
|
||||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.experiments = new ExperimentsService(container);
|
||||
this.results = new BacktestServiceV2(container);
|
||||
}
|
||||
async submit(raw: unknown, actor: Actor): Promise<ChronologicalValidationDetail> {
|
||||
const submission = parseValidationSubmission(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const { previewHash, ...input } = submission;
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: 'submit-chronological-validation',
|
||||
submission,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'SELECT id,submission_hash,validation_phase FROM research_experiments WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.submission_hash !== hash || row.validation_phase !== 'train') {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different experiment intent'
|
||||
);
|
||||
}
|
||||
return this.readDetail(client, row.id);
|
||||
};
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const sourceDataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
const prepared = prepareChronologicalValidation(input, source, sourceDataset);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Validation preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
for (const dataset of Object.values(prepared.datasets)) {
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
|
||||
[dataset.manifest.hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = (
|
||||
await client.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
dataset.manifest.hash,
|
||||
])
|
||||
).rows[0];
|
||||
if (!saved || !validationEqual(validateDatasetV2(saved.payload), dataset)) {
|
||||
throw new Error('Retained validation slice identity mismatch');
|
||||
}
|
||||
}
|
||||
const id = randomUUID(),
|
||||
train = validationPhasePreview(prepared.preview, 'train');
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'train') ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
id,
|
||||
input.backtestId,
|
||||
train.input.name,
|
||||
train,
|
||||
train.previewHash,
|
||||
identity.principal,
|
||||
identity.key,
|
||||
hash,
|
||||
prepared.preview,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent validation receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await this.insertRuns(client, id, train);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<ChronologicalValidationSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT * FROM research_experiments WHERE validation_phase='train' ${backtestId === undefined ? '' : 'AND backtest_id=$1'} ORDER BY created_at DESC,id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(row => {
|
||||
retainedValidationPreview(row.validation_manifest);
|
||||
return summary(row);
|
||||
});
|
||||
}
|
||||
async get(id: string): Promise<ChronologicalValidationDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(client => this.readDetail(client, id));
|
||||
}
|
||||
async cancel(id: string): Promise<ChronologicalValidationDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
await this.lockRoot(client, id);
|
||||
// SQL cascade also covers the existing ordinary cancel endpoint and direct SQL.
|
||||
await client.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [id]);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async select(
|
||||
id: string,
|
||||
raw: unknown,
|
||||
actor: Actor
|
||||
): Promise<ChronologicalValidationActionResult> {
|
||||
experimentId(id);
|
||||
const input = parseValidationSelection(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const operation = 'select-and-admit-holdouts' as const;
|
||||
const hash = experimentHash({ version: 1, operation, validationId: id, input });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = () =>
|
||||
this.actionReplay(client, 'validation_selection', operation, identity, hash);
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
const { root, parent } = await this.lockRoot(client, id);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (root.validation_selection) {
|
||||
throw new ExperimentError(409, 'Selection is already frozen under another receipt');
|
||||
}
|
||||
const preview = retainedValidationPreview(root.validation_manifest);
|
||||
if (preview.previewHash !== input.previewHash) {
|
||||
throw new ExperimentError(409, 'Validation input identity changed');
|
||||
}
|
||||
if (root.cancel_requested || parent.archived_at !== null) {
|
||||
throw new ExperimentError(409, 'Selection requires active uncancelled validation');
|
||||
}
|
||||
await client.query(
|
||||
'SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index FOR UPDATE',
|
||||
[id]
|
||||
);
|
||||
const training = await this.evidence(client, id, 'train');
|
||||
const winner = selectValidationWinner(preview.source.candidates, training);
|
||||
let reviewId;
|
||||
try {
|
||||
reviewId = await verifyReproductionInputs(
|
||||
client,
|
||||
this.container,
|
||||
preview.partitions[0].request
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
throw new ExperimentError(409, error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
for (const partition of preview.partitions.slice(1)) {
|
||||
let dataset;
|
||||
try {
|
||||
dataset = await readCanonicalDataset(client, partition.dataset.hash);
|
||||
} catch (error) {
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
throw new ExperimentError(409, error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!validationEqual(dataset.manifest, partition.dataset)) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Retained holdout dataset differs from the frozen validation recipe'
|
||||
);
|
||||
}
|
||||
}
|
||||
const manifest = {
|
||||
version: 'chronological-validation-selection/v1' as const,
|
||||
id: randomUUID(),
|
||||
validationId: id,
|
||||
previewHash: preview.previewHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: identity.principal,
|
||||
reviewId,
|
||||
winner,
|
||||
training,
|
||||
holdoutExperimentIds: { validation: randomUUID(), test: randomUUID() },
|
||||
};
|
||||
const selection: ChronologicalValidationSelection = {
|
||||
...manifest,
|
||||
selectionHash: experimentHash(manifest),
|
||||
};
|
||||
const stored: PrivateValidationDocument<ChronologicalValidationSelection> = {
|
||||
...selection,
|
||||
_receipt: { key: identity.key, hash },
|
||||
};
|
||||
// The operation-scoped advisory lock resolves cross-parent receipt races before a unique-index error aborts the transaction.
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
||||
`validation-select:${identity.principal}:${identity.key}`,
|
||||
]);
|
||||
const race = await replay();
|
||||
if (race) {
|
||||
return race;
|
||||
}
|
||||
await client.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [
|
||||
id,
|
||||
stored,
|
||||
]);
|
||||
for (const phase of ['validation', 'test'] as const) {
|
||||
const childId = selection.holdoutExperimentIds[phase],
|
||||
child = validationPhasePreview(preview, phase, winner, reviewId);
|
||||
await client.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_parent_id,validation_phase)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
|
||||
[
|
||||
childId,
|
||||
root.backtest_id,
|
||||
child.input.name,
|
||||
child,
|
||||
child.previewHash,
|
||||
identity.principal,
|
||||
`validation-child:${childId}`,
|
||||
experimentHash({
|
||||
version: 1,
|
||||
validationId: id,
|
||||
selectionHash: selection.selectionHash,
|
||||
phase,
|
||||
}),
|
||||
id,
|
||||
phase,
|
||||
]
|
||||
);
|
||||
await this.insertRuns(client, childId, child);
|
||||
}
|
||||
return {
|
||||
receipt: receipt(selection, operation),
|
||||
validation: await this.readDetail(client, id),
|
||||
};
|
||||
});
|
||||
}
|
||||
async finalize(
|
||||
id: string,
|
||||
raw: unknown,
|
||||
actor: Actor
|
||||
): Promise<ChronologicalValidationActionResult> {
|
||||
experimentId(id);
|
||||
const input = parseValidationFinalization(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const operation = 'finalize-report' as const,
|
||||
hash = experimentHash({ version: 1, operation, validationId: id, input });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = () =>
|
||||
this.actionReplay(client, 'validation_report', operation, identity, hash);
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
const { root } = await this.lockRoot(client, id);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (root.validation_report) {
|
||||
throw new ExperimentError(409, 'Report is already sealed under another receipt');
|
||||
}
|
||||
const preview = retainedValidationPreview(root.validation_manifest);
|
||||
if (root.cancel_requested || !root.validation_selection) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Finalization requires uncancelled validation with frozen selection'
|
||||
);
|
||||
}
|
||||
const selection = publicValidationDocument<ChronologicalValidationSelection>(
|
||||
root.validation_selection,
|
||||
'selectionHash'
|
||||
);
|
||||
if (
|
||||
input.previewHash !== preview.previewHash ||
|
||||
input.selectionHash !== selection.selectionHash
|
||||
) {
|
||||
throw new ExperimentError(409, 'Validation or selection identity changed');
|
||||
}
|
||||
for (const childId of [
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query('SELECT id FROM research_experiments WHERE id=$1 FOR UPDATE', [childId]);
|
||||
}
|
||||
for (const experimentId of [
|
||||
id,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query(
|
||||
'SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index FOR UPDATE',
|
||||
[experimentId]
|
||||
);
|
||||
}
|
||||
const training = await this.evidence(client, id, 'train');
|
||||
if (!validationEqual(training, selection.training)) {
|
||||
throw new ExperimentError(409, 'Training evidence differs from the frozen selection');
|
||||
}
|
||||
const validation = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
'validation',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
const test = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.test,
|
||||
'test',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
const manifest = {
|
||||
version: 'chronological-validation-report/v1' as const,
|
||||
id: randomUUID(),
|
||||
validationId: id,
|
||||
previewHash: preview.previewHash,
|
||||
selectionHash: selection.selectionHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: identity.principal,
|
||||
reset: 'initial-capital-empty-positions' as const,
|
||||
training,
|
||||
validation,
|
||||
test,
|
||||
limitations: [
|
||||
'Independent accounts reset initial capital and positions for every phase; no continuous portfolio curve is implied.',
|
||||
'This workflow selects using training evidence only. It does not certify that the source data was never inspected elsewhere.',
|
||||
'Completed execution is not proof of profitability or statistical adequacy.',
|
||||
],
|
||||
};
|
||||
const report: ChronologicalValidationReport = {
|
||||
...manifest,
|
||||
reportHash: experimentHash(manifest),
|
||||
};
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
||||
`validation-finalize:${identity.principal}:${identity.key}`,
|
||||
]);
|
||||
const race = await replay();
|
||||
if (race) {
|
||||
return race;
|
||||
}
|
||||
await client.query('UPDATE research_experiments SET validation_report=$2 WHERE id=$1', [
|
||||
id,
|
||||
{ ...report, _receipt: { key: identity.key, hash } },
|
||||
]);
|
||||
return { receipt: receipt(report, operation), validation: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async lockRoot(client: PoolClient, id: string) {
|
||||
const parent = (
|
||||
await client.query(
|
||||
"SELECT id,archived_at FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=$1 AND validation_phase='train') FOR UPDATE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Chronological validation not found');
|
||||
}
|
||||
const root = (
|
||||
await client.query(
|
||||
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR UPDATE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!root) {
|
||||
throw new ExperimentError(404, 'Chronological validation not found');
|
||||
}
|
||||
return { root, parent };
|
||||
}
|
||||
private async actionReplay(
|
||||
client: PoolClient,
|
||||
field: Field,
|
||||
operation: Operation,
|
||||
identity: ReturnType<typeof experimentReceipt>,
|
||||
hash: string
|
||||
): Promise<ChronologicalValidationActionResult | null> {
|
||||
const row = (
|
||||
await client.query(
|
||||
`SELECT id,${field} AS document FROM research_experiments WHERE ${field}->>'principal'=$1 AND ${field}#>>'{_receipt,key}'=$2`,
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.document._receipt.hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different validation action'
|
||||
);
|
||||
}
|
||||
const document = publicValidationDocument<
|
||||
ChronologicalValidationSelection | ChronologicalValidationReport
|
||||
>(row.document, field === 'validation_selection' ? 'selectionHash' : 'reportHash');
|
||||
return {
|
||||
receipt: receipt(document, operation),
|
||||
validation: await this.readDetail(client, row.id),
|
||||
};
|
||||
}
|
||||
private async insertRuns(client: PoolClient, id: string, preview: ExperimentPreview) {
|
||||
let number = Number(
|
||||
(
|
||||
await client.query(
|
||||
'SELECT COALESCE(MAX(run_number),0) AS n FROM runs WHERE backtest_id=$1',
|
||||
[preview.input.backtestId]
|
||||
)
|
||||
).rows[0].n
|
||||
);
|
||||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID(),
|
||||
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,
|
||||
preview.input.backtestId,
|
||||
++number,
|
||||
request,
|
||||
request.datasetHash,
|
||||
id,
|
||||
candidate.trialKey,
|
||||
candidate.index,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
}
|
||||
}
|
||||
private async evidence(
|
||||
client: PoolClient,
|
||||
id: string,
|
||||
phase: ValidationPhase,
|
||||
sourceIndex?: number
|
||||
): Promise<ValidationResultEvidence[]> {
|
||||
const detail = await this.experiments.readDetail(client, id);
|
||||
if (
|
||||
detail.cancelRequested ||
|
||||
detail.trials.some(
|
||||
t => t.cancelRequested || t.status !== 'completed' || !t.comparable || !t.runId
|
||||
)
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
`Every ${phase} trial must be complete, uncancelled and comparable`
|
||||
);
|
||||
}
|
||||
const evidence: ValidationResultEvidence[] = [];
|
||||
for (const trial of detail.trials) {
|
||||
const runId = trial.runId;
|
||||
if (!runId) {
|
||||
throw new ExperimentError(409, 'Expected phase run is missing');
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = await this.results.getRunResults(runId, client);
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof z.ZodError ||
|
||||
(error instanceof Error &&
|
||||
(error.message === 'Saved canonical result does not match its admitted request' ||
|
||||
error.message.startsWith('Native replay ')))
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
`Retained ${phase} result failed financial or analytics validation`
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
|
||||
throw new ExperimentError(409, `Retained ${phase} result is unavailable`);
|
||||
}
|
||||
if (!validationEqual(result.request, experimentTrialRequest(detail.preview, trial, runId))) {
|
||||
throw new ExperimentError(409, `Retained ${phase} result input mismatch`);
|
||||
}
|
||||
evidence.push(
|
||||
validationEvidence(
|
||||
phase,
|
||||
id,
|
||||
trial,
|
||||
sourceIndex ?? trial.index,
|
||||
result as CanonicalRunResult
|
||||
)
|
||||
);
|
||||
}
|
||||
return evidence;
|
||||
}
|
||||
private async readDetail(client: PoolClient, id: string): Promise<ChronologicalValidationDetail> {
|
||||
const row = (
|
||||
await client.query(
|
||||
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR SHARE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Chronological validation not found');
|
||||
}
|
||||
const preview = retainedValidationPreview(row.validation_manifest);
|
||||
const selection = row.validation_selection
|
||||
? publicValidationDocument<ChronologicalValidationSelection>(
|
||||
row.validation_selection,
|
||||
'selectionHash'
|
||||
)
|
||||
: null;
|
||||
const report = row.validation_report
|
||||
? publicValidationDocument<ChronologicalValidationReport>(row.validation_report, 'reportHash')
|
||||
: null;
|
||||
const phases: ValidationPhaseState[] = [];
|
||||
for (const phase of ['train', 'validation', 'test'] as const) {
|
||||
const expected = phase === 'train' ? id : selection?.holdoutExperimentIds[phase];
|
||||
if (!expected) {
|
||||
phases.push({ phase, status: 'not-admitted', experimentId: null, experiment: null });
|
||||
continue;
|
||||
}
|
||||
const exists =
|
||||
phase === 'train' ||
|
||||
(
|
||||
await client.query(
|
||||
'SELECT id FROM research_experiments WHERE id=$1 AND validation_parent_id=$2 AND validation_phase=$3',
|
||||
[expected, id, phase]
|
||||
)
|
||||
).rows.length > 0;
|
||||
phases.push({
|
||||
phase,
|
||||
status: exists ? 'admitted' : 'missing',
|
||||
experimentId: expected,
|
||||
experiment: exists ? await this.experiments.readDetail(client, expected) : null,
|
||||
});
|
||||
}
|
||||
const ready = (phase: ValidationPhaseState) =>
|
||||
phase.experiment &&
|
||||
!phase.experiment.cancelRequested &&
|
||||
phase.experiment.trials.every(
|
||||
t => t.status === 'completed' && t.comparable && !t.cancelRequested
|
||||
);
|
||||
const trainingPhase = at(phases, 0);
|
||||
const trainingExperiment = trainingPhase.experiment;
|
||||
const canSelect =
|
||||
!row.cancel_requested &&
|
||||
!selection &&
|
||||
!!ready(trainingPhase) &&
|
||||
!!trainingExperiment &&
|
||||
trainingExperiment.trials.every(
|
||||
t => typeof t.metrics?.totalReturn === 'number' && Number.isFinite(t.metrics.totalReturn)
|
||||
);
|
||||
const canFinalize = !row.cancel_requested && !!selection && !report && phases.every(ready);
|
||||
return {
|
||||
...summary(row),
|
||||
preview,
|
||||
phases: phases as ChronologicalValidationDetail['phases'],
|
||||
selection,
|
||||
report,
|
||||
actions: {
|
||||
select: {
|
||||
available: canSelect,
|
||||
reason: canSelect
|
||||
? null
|
||||
: row.cancel_requested
|
||||
? 'Validation is cancelled'
|
||||
: selection
|
||||
? 'Selection is already frozen'
|
||||
: 'Every training candidate needs complete comparable evidence and finite total return',
|
||||
},
|
||||
finalize: {
|
||||
available: canFinalize,
|
||||
reason: canFinalize
|
||||
? null
|
||||
: report
|
||||
? 'Report is already saved'
|
||||
: row.cancel_requested
|
||||
? 'Validation is cancelled'
|
||||
: 'Selection and complete uncancelled phase evidence are required',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -118,10 +118,7 @@ export class ExperimentsService {
|
|||
return prepareChronologicalValidation(input, source, dataset).preview;
|
||||
});
|
||||
}
|
||||
private async lockedPreview(
|
||||
client: PoolClient,
|
||||
input: ExperimentInput
|
||||
): Promise<ExperimentPreview> {
|
||||
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];
|
||||
|
|
@ -272,7 +269,7 @@ export class ExperimentsService {
|
|||
}
|
||||
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`,
|
||||
WHERE e.validation_phase IS NULL ${backtestId === undefined ? '' : 'AND e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(summary);
|
||||
|
|
@ -482,7 +479,7 @@ export class ExperimentsService {
|
|||
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
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`,
|
||||
|
|
|
|||
182
apps/stock/web-api/src/services/validation-evidence.ts
Normal file
182
apps/stock/web-api/src/services/validation-evidence.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { z } from 'zod';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
chronologicalValidationFinalizationSchema,
|
||||
chronologicalValidationSelectionSchema,
|
||||
chronologicalValidationSubmissionSchema,
|
||||
type ChronologicalValidationPreview,
|
||||
type ChronologicalValidationReport,
|
||||
type ChronologicalValidationSelection,
|
||||
type ValidationPhase,
|
||||
type ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
|
||||
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { canonicalReproductionHash } from './reproduction-comparison';
|
||||
import { parseChronologicalValidation } from './validation-preview';
|
||||
|
||||
export const validationEqual = (a: unknown, b: unknown) =>
|
||||
a !== undefined && b !== undefined && canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
export function parseValidationSubmission(raw: unknown) {
|
||||
return parse(chronologicalValidationSubmissionSchema, raw);
|
||||
}
|
||||
export function parseValidationSelection(raw: unknown) {
|
||||
return parse(chronologicalValidationSelectionSchema, raw);
|
||||
}
|
||||
export function parseValidationFinalization(raw: unknown) {
|
||||
return parse(chronologicalValidationFinalizationSchema, raw);
|
||||
}
|
||||
function parse<T extends z.ZodTypeAny>(schema: T, raw: unknown): z.infer<T> {
|
||||
try {
|
||||
assertStrategyJsonText(raw);
|
||||
return schema.parse(raw);
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid chronological validation operation');
|
||||
}
|
||||
}
|
||||
export function retainedValidationPreview(value: unknown): ChronologicalValidationPreview {
|
||||
const preview = value as ChronologicalValidationPreview;
|
||||
const { previewHash, ...manifest } = preview;
|
||||
if (
|
||||
preview.version !== 'chronological-validation-preview/v1' ||
|
||||
preview.execution !== 'preview-only' ||
|
||||
experimentHash(manifest) !== previewHash
|
||||
) {
|
||||
throw new Error('Retained validation preparation integrity failure');
|
||||
}
|
||||
parseChronologicalValidation(preview.input);
|
||||
retainedExperimentPreview(preview.source);
|
||||
if (preview.partitions.length !== 3) {
|
||||
throw new Error('Retained validation phase identity mismatch');
|
||||
}
|
||||
for (const [index, phase] of (['train', 'validation', 'test'] as const).entries()) {
|
||||
const partition = at(preview.partitions, index);
|
||||
if (
|
||||
partition.phase !== phase ||
|
||||
partition.request.datasetHash !== partition.dataset.hash ||
|
||||
!validationEqual(partition.dataset.bounds, preview.input.recipe[phase])
|
||||
) {
|
||||
throw new Error('Retained validation phase identity mismatch');
|
||||
}
|
||||
canonicalRunRequestSchema.parse(partition.request);
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
export function validationPhasePreview(
|
||||
preview: ChronologicalValidationPreview,
|
||||
phase: ValidationPhase,
|
||||
winner?: ExperimentCandidate,
|
||||
reviewId?: string
|
||||
) {
|
||||
const partition = preview.partitions.find(p => p.phase === phase);
|
||||
if (!partition) {
|
||||
throw new Error('Missing prepared validation phase');
|
||||
}
|
||||
const request = structuredClone(partition.request);
|
||||
if (phase !== 'train') {
|
||||
if (!winner || !reviewId) {
|
||||
throw new Error('Holdout admission requires a frozen winner and current approval');
|
||||
}
|
||||
request.strategy.selection.parameters = structuredClone(
|
||||
winner.parameters
|
||||
) as typeof request.strategy.selection.parameters;
|
||||
request.strategy.reviewId = reviewId;
|
||||
}
|
||||
return buildExperimentPreview(
|
||||
{
|
||||
backtestId: preview.input.backtestId,
|
||||
name: `${preview.input.name} · ${phase}`,
|
||||
grid: phase === 'train' ? preview.input.grid : {},
|
||||
},
|
||||
canonicalRunRequestSchema.parse(request),
|
||||
partition.dataset
|
||||
);
|
||||
}
|
||||
export function validationEvidence(
|
||||
phase: ValidationPhase,
|
||||
experimentId: string,
|
||||
candidate: ExperimentCandidate,
|
||||
sourceCandidateIndex: number,
|
||||
result: CanonicalRunResult
|
||||
): ValidationResultEvidence {
|
||||
return {
|
||||
phase,
|
||||
experimentId,
|
||||
runId: result.runId,
|
||||
sourceCandidateIndex,
|
||||
trialKey: candidate.trialKey,
|
||||
parameters: candidate.parameters,
|
||||
datasetHash: result.request.datasetHash,
|
||||
requestHash: experimentHash(result.request),
|
||||
economicHash: canonicalReproductionHash(result),
|
||||
metrics: result.analytics.metrics,
|
||||
unavailable: result.analytics.unavailable,
|
||||
completePeriodCount: result.analytics.completePeriodCount,
|
||||
periodicSampleCount: result.analytics.periodicSampleCount,
|
||||
fillCount: result.analytics.fillCount,
|
||||
limitations: [...result.financial.limitations, ...result.financial.modelLimitations],
|
||||
};
|
||||
}
|
||||
export function selectValidationWinner(
|
||||
candidates: ExperimentCandidate[],
|
||||
evidence: ValidationResultEvidence[]
|
||||
): ExperimentCandidate {
|
||||
if (
|
||||
candidates.length !== evidence.length ||
|
||||
!candidates.length ||
|
||||
candidates.some((candidate, index) => {
|
||||
const item = evidence[index];
|
||||
return (
|
||||
candidate.index !== index ||
|
||||
!item ||
|
||||
item.phase !== 'train' ||
|
||||
item.sourceCandidateIndex !== candidate.index ||
|
||||
item.trialKey !== candidate.trialKey ||
|
||||
!validationEqual(item.parameters, candidate.parameters) ||
|
||||
typeof item.metrics.totalReturn !== 'number' ||
|
||||
!Number.isFinite(item.metrics.totalReturn)
|
||||
);
|
||||
})
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Every training candidate needs complete comparable evidence and a finite total return'
|
||||
);
|
||||
}
|
||||
let winner = at(candidates, 0),
|
||||
bestScore = Number.NEGATIVE_INFINITY;
|
||||
for (const candidate of candidates) {
|
||||
const score = at(evidence, candidate.index).metrics.totalReturn;
|
||||
if (typeof score !== 'number' || !Number.isFinite(score)) {
|
||||
throw new ExperimentError(409, 'Training return is unavailable');
|
||||
}
|
||||
if (score > bestScore) {
|
||||
winner = candidate;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
export type PrivateValidationDocument<T> = T & { _receipt: { key: string; hash: string } };
|
||||
export function publicValidationDocument<
|
||||
T extends ChronologicalValidationSelection | ChronologicalValidationReport,
|
||||
>(value: PrivateValidationDocument<T>, key: 'selectionHash' | 'reportHash'): T {
|
||||
const { _receipt, ...document } = value;
|
||||
const manifest: Record<string, unknown> = { ...document };
|
||||
const hash = manifest[key];
|
||||
delete manifest[key];
|
||||
if (!_receipt || experimentHash(manifest) !== hash) {
|
||||
throw new Error('Retained validation evidence integrity failure');
|
||||
}
|
||||
return document as unknown as T;
|
||||
}
|
||||
|
|
@ -3,7 +3,11 @@ import { Layout } from '@/components/layout';
|
|||
import { BacktestDetailPageV2, BacktestListPageV2 } from '@/features/backtest';
|
||||
import { DashboardPage } from '@/features/dashboard';
|
||||
import { ExchangesPage } from '@/features/exchanges';
|
||||
import { ExperimentDetailPage, ExperimentListPage } from '@/features/experiments';
|
||||
import {
|
||||
ChronologicalValidationDetailPage,
|
||||
ExperimentDetailPage,
|
||||
ExperimentListPage,
|
||||
} from '@/features/experiments';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
import { ResearchListPage, ResearchProjectPage } from '@/features/research';
|
||||
|
|
@ -51,6 +55,10 @@ export function App() {
|
|||
</Route>
|
||||
<Route path="experiments">
|
||||
<Route index element={<ExperimentListPage />} />
|
||||
<Route
|
||||
path="validation/:validationId"
|
||||
element={<ChronologicalValidationDetailPage />}
|
||||
/>
|
||||
<Route path=":experimentId" element={<ExperimentDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
|
|
|
|||
|
|
@ -0,0 +1,506 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { ChronologicalValidationActionReceipt } from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ValidationEvidence } from './components/ValidationEvidence';
|
||||
import {
|
||||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
type ValidationDetailView,
|
||||
} from './services/chronologicalValidationDurableApi';
|
||||
|
||||
export function ChronologicalValidationDetailPage() {
|
||||
const { validationId = '' } = useParams<{ validationId: string }>();
|
||||
return <ValidationDetail key={validationId} validationId={validationId} />;
|
||||
}
|
||||
type Intent =
|
||||
| { id: string; operation: 'select'; body: { previewHash: string }; key: string }
|
||||
| {
|
||||
id: string;
|
||||
operation: 'finalize';
|
||||
body: { previewHash: string; selectionHash: string };
|
||||
key: string;
|
||||
};
|
||||
function ValidationDetail({ validationId }: { validationId: string }) {
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
reading = useRef(true),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const captured = useRef<Intent | null>(null);
|
||||
const [intent, setIntent] = useState<Intent | null>(null);
|
||||
const [validation, setValidation] = useState<ValidationDetailView | null>(null);
|
||||
const [loading, setLoading] = useState(true),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reload, setReload] = useState(0);
|
||||
const [readError, setReadError] = useState(''),
|
||||
[actionError, setActionError] = useState('');
|
||||
const [ambiguous, setAmbiguous] = useState(false),
|
||||
[receipt, setReceipt] = useState<ChronologicalValidationActionReceipt | null>(null);
|
||||
useUnsavedWarning(Boolean(intent));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (pending.current) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
const revision = ++generation.current,
|
||||
controller = new AbortController();
|
||||
read.current = controller;
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setReadError('');
|
||||
void chronologicalValidationDurableApi
|
||||
.get(validationId, controller.signal)
|
||||
.then(value => {
|
||||
if (current && revision === generation.current) {
|
||||
setValidation(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current && revision === generation.current) {
|
||||
setReadError(cause instanceof Error ? cause.message : 'Could not load validation');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current && revision === generation.current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [validationId, reload]);
|
||||
const begin = () => {
|
||||
if (pending.current || reading.current) {
|
||||
return false;
|
||||
}
|
||||
pending.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setLoading(false);
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
return true;
|
||||
};
|
||||
const finish = () => {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const advance = async (operation: 'select' | 'finalize') => {
|
||||
if (pending.current || reading.current || loading || !validation) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (
|
||||
!validation.actions[operation].available ||
|
||||
(operation === 'finalize' && !validation.selection)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current =
|
||||
operation === 'select'
|
||||
? {
|
||||
id: validationId,
|
||||
operation,
|
||||
body: { previewHash: validation.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
}
|
||||
: {
|
||||
id: validationId,
|
||||
operation,
|
||||
body: {
|
||||
previewHash: validation.previewHash,
|
||||
selectionHash: validation.selection?.selectionHash ?? '',
|
||||
},
|
||||
key: crypto.randomUUID(),
|
||||
};
|
||||
setIntent(captured.current);
|
||||
setReceipt(null);
|
||||
}
|
||||
const original = captured.current;
|
||||
if (!begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await chronologicalValidationDurableApi.advance(
|
||||
original.id,
|
||||
original.operation,
|
||||
original.body,
|
||||
original.key
|
||||
);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setAmbiguous(false);
|
||||
setReceipt(result.receipt);
|
||||
setValidation(result.validation);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(cause instanceof Error ? cause.message : 'Could not advance validation');
|
||||
setAmbiguous(!(cause instanceof ValidationApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const cancel = async () => {
|
||||
if (loading || !validation || !begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const value = await chronologicalValidationDurableApi.cancel(validationId);
|
||||
if (alive.current) {
|
||||
setValidation(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
`${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
pending.current ||
|
||||
!window.confirm(
|
||||
'Discard this action request? It may already have succeeded. Refresh the saved validation before preparing another action.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setActionError('');
|
||||
setAmbiguous(false);
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className="h-full overflow-auto p-1 space-y-4"
|
||||
onClickCapture={event => {
|
||||
if (
|
||||
(event.target as HTMLElement).closest('a') &&
|
||||
captured.current &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!window.confirm(
|
||||
'Leave this unconfirmed validation action? Its exact body and key will be discarded. You can inspect evidence in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Link to="/experiments" className="text-primary-500 text-sm">
|
||||
All experiments
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-lg font-bold">{validation?.name ?? 'Chronological validation'}</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || busy}
|
||||
onClick={() => {
|
||||
if (!pending.current && !reading.current) {
|
||||
reading.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setReload(value => value + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Refresh validation
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading validation...</p>}
|
||||
{readError && (
|
||||
<p role="alert" className="text-error">
|
||||
{readError}
|
||||
{validation && ' Showing the last loaded state.'}
|
||||
</p>
|
||||
)}
|
||||
{actionError && (
|
||||
<p role="alert" className="text-error">
|
||||
{actionError}
|
||||
</p>
|
||||
)}
|
||||
{intent && (
|
||||
<div className="space-y-2">
|
||||
<p role="status">
|
||||
{ambiguous ? 'Action acceptance is unconfirmed. ' : ''}This request still targets{' '}
|
||||
{intent.operation === 'select'
|
||||
? 'selection and holdout admission'
|
||||
: 'report finalization'}{' '}
|
||||
with its exact saved body and key.
|
||||
</p>
|
||||
<Button disabled={busy || loading} onClick={() => void advance(intent.operation)}>
|
||||
{intent.operation === 'select' ? 'Retry selection request' : 'Retry report request'}
|
||||
</Button>{' '}
|
||||
<Button variant="outline" disabled={busy} onClick={discard}>
|
||||
Discard action request
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{receipt && (
|
||||
<p role="status">
|
||||
{receipt.operation === 'select-and-admit-holdouts'
|
||||
? 'Selection and holdout admission accepted.'
|
||||
: 'Report finalization accepted.'}{' '}
|
||||
Receipt {receipt.id} · {receipt.createdAt}
|
||||
</p>
|
||||
)}
|
||||
{validation && (
|
||||
<>
|
||||
<p className="font-semibold">
|
||||
{validation.report
|
||||
? 'Execution complete · report saved'
|
||||
: validation.selection
|
||||
? 'Fixed selection saved · validation and test admitted'
|
||||
: 'Training candidates admitted · selection not yet frozen'}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{validation.trainingCandidateCount} training candidates; one validation run and one test
|
||||
run after selection. Each phase resets initial capital and positions. No combined
|
||||
portfolio equity curve is produced.
|
||||
</p>
|
||||
{validation.cancelRequested && (
|
||||
<p>
|
||||
Cancellation requested. Completed evidence remains retained; active work may still
|
||||
finish.
|
||||
</p>
|
||||
)}
|
||||
{!intent && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!validation.selection && (
|
||||
<Button
|
||||
disabled={busy || loading || !validation.actions.select.available}
|
||||
onClick={() => void advance('select')}
|
||||
>
|
||||
Freeze selection and run holdouts
|
||||
</Button>
|
||||
)}
|
||||
{validation.selection && !validation.report && (
|
||||
<Button
|
||||
disabled={busy || loading || !validation.actions.finalize.available}
|
||||
onClick={() => void advance('finalize')}
|
||||
>
|
||||
Save validation report
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!validation.selection && validation.actions.select.reason && (
|
||||
<p>{validation.actions.select.reason}</p>
|
||||
)}
|
||||
{validation.selection && !validation.report && validation.actions.finalize.reason && (
|
||||
<p>{validation.actions.finalize.reason}</p>
|
||||
)}
|
||||
{!validation.cancelRequested && !validation.report && (
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={busy || loading}
|
||||
onClick={() => void cancel()}
|
||||
>
|
||||
Cancel remaining validation work
|
||||
</Button>
|
||||
)}
|
||||
<section aria-label="Frozen chronological recipe" className="space-y-2 text-sm">
|
||||
<h2 className="font-semibold">Frozen chronological recipe</h2>
|
||||
<p>
|
||||
Train selection maximizes total return; ties use the original candidate index. Every
|
||||
candidate is required. Validation is diagnostic only; test is holdout only. Neither
|
||||
retunes the fixed selection.
|
||||
</p>
|
||||
<p>
|
||||
Initial capital (USD):{' '}
|
||||
{validation.preview.source.request.policy.matching.risk.ledger.initialCapital} · Owner
|
||||
budget: {validation.preview.source.request.strategy.selection.ownerBudget} · Seed:{' '}
|
||||
{validation.preview.source.request.strategy.selection.seed}
|
||||
</p>
|
||||
<p>
|
||||
Selection uses training results only in this workflow. These dates may have been
|
||||
examined in other research.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{validation.preview.partitions.map(part => (
|
||||
<article
|
||||
key={part.phase}
|
||||
className="border border-border rounded p-3 break-all text-xs"
|
||||
>
|
||||
<h3 className="font-semibold">{part.phase} window</h3>
|
||||
<p>Warmup: {new Date(part.dataset.bounds.warmupStart).toISOString()}</p>
|
||||
<p>
|
||||
Trading: {new Date(part.dataset.bounds.tradeStart).toISOString()} —{' '}
|
||||
{new Date(part.dataset.bounds.tradeEnd).toISOString()} (end exclusive)
|
||||
</p>
|
||||
<p>Dataset: {part.dataset.hash}</p>
|
||||
<p>
|
||||
Admitted / required warmup: {part.counts.admittedWarmup} / {part.requiredWarmup}
|
||||
</p>
|
||||
{part.warnings.map((warning, index) => (
|
||||
<p key={index}>{warning}</p>
|
||||
))}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained recipe and policies</summary>
|
||||
<pre className="max-h-80 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(
|
||||
{
|
||||
previewHash: validation.previewHash,
|
||||
input: validation.preview.input,
|
||||
policy: validation.preview.policy,
|
||||
sourceDataset: validation.preview.source.request.datasetHash,
|
||||
strategyVersion: validation.preview.source.request.strategy.versionId,
|
||||
sourceReview: validation.preview.source.request.strategy.reviewId,
|
||||
artifactHash:
|
||||
validation.preview.source.request.strategy.package.artifact.sha256,
|
||||
build: validation.preview.source.request.build,
|
||||
financialPolicy: validation.preview.source.request.policy,
|
||||
analyticsPolicy: validation.preview.source.request.analyticsPolicy,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
<section aria-label="Validation phase outcomes" className="space-y-3">
|
||||
<h2 className="font-semibold">Phase outcomes</h2>
|
||||
{validation.phases.map(phase => (
|
||||
<article
|
||||
key={phase.phase}
|
||||
aria-label={`${phase.phase} outcomes`}
|
||||
className="border border-border rounded p-3 space-y-2"
|
||||
>
|
||||
<h3 className="font-semibold">{phase.phase}</h3>
|
||||
{phase.status === 'not-admitted' && (
|
||||
<p>
|
||||
Not admitted. No {phase.phase} run exists before the fixed selection is saved.
|
||||
</p>
|
||||
)}
|
||||
{phase.status === 'missing' && (
|
||||
<p role="alert">
|
||||
Expected {phase.phase} experiment is missing. Report finalization is blocked.
|
||||
</p>
|
||||
)}
|
||||
{phase.experiment && (
|
||||
<>
|
||||
<ExperimentCounts experiment={phase.experiment} />
|
||||
<ul className="space-y-2 text-sm">
|
||||
{phase.experiment.trials.map(trial => (
|
||||
<li key={trial.trialKey}>
|
||||
Candidate{' '}
|
||||
{phase.phase === 'train'
|
||||
? trial.index + 1
|
||||
: (validation.selection?.winner.index ?? 0) + 1}{' '}
|
||||
· {trial.status} · {trial.progress}% ·{' '}
|
||||
{trial.comparable
|
||||
? 'Comparable'
|
||||
: trial.status === 'completed'
|
||||
? 'Incomparable'
|
||||
: 'Not evaluated'}
|
||||
<pre className="text-xs">{JSON.stringify(trial.parameters)}</pre>
|
||||
{trial.error && <p className="text-error">{trial.error}</p>}
|
||||
{trial.diagnostic && <p>{trial.diagnostic}</p>}
|
||||
<p>
|
||||
Total return (fraction):{' '}
|
||||
{trial.metrics?.totalReturn === null ||
|
||||
trial.metrics?.totalReturn === undefined
|
||||
? `Unavailable${trial.unavailable?.totalReturn ? `: ${trial.unavailable.totalReturn}` : ''}`
|
||||
: String(trial.metrics.totalReturn)}
|
||||
</p>
|
||||
{trial.runId && (
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/backtests/${encodeURIComponent(validation.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
|
||||
>
|
||||
Open {phase.phase} run {trial.index + 1}
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
{phase.experimentId && (
|
||||
<Link
|
||||
className="text-primary-500 text-sm"
|
||||
to={`/experiments/${encodeURIComponent(phase.experimentId)}`}
|
||||
>
|
||||
Open {phase.phase} experiment
|
||||
</Link>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
{validation.selection && (
|
||||
<section aria-label="Fixed training selection" className="space-y-2">
|
||||
<h2 className="font-semibold">Fixed training selection</h2>
|
||||
<p>Selected training candidate {validation.selection.winner.index + 1}</p>
|
||||
<pre className="text-xs">
|
||||
{JSON.stringify(validation.selection.winner.parameters, null, 2)}
|
||||
</pre>
|
||||
<p className="break-all text-xs">
|
||||
Selection {validation.selection.id} · {validation.selection.selectionHash} ·{' '}
|
||||
{validation.selection.createdAt} · {validation.selection.principal}
|
||||
</p>
|
||||
<p className="break-all text-xs">
|
||||
Holdout admission approval: {validation.selection.reviewId}
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{validation.selection && (
|
||||
<ValidationEvidence
|
||||
title="All retained training evidence"
|
||||
items={validation.report?.training ?? validation.selection.training}
|
||||
backtestId={validation.backtestId}
|
||||
/>
|
||||
)}
|
||||
{validation.report && (
|
||||
<section aria-label="Saved validation report" className="space-y-3">
|
||||
<h2 className="font-semibold">Saved validation report</h2>
|
||||
<p className="break-all text-xs">
|
||||
Report {validation.report.id} · {validation.report.reportHash} ·{' '}
|
||||
{validation.report.createdAt} · {validation.report.principal}
|
||||
</p>
|
||||
<p>
|
||||
Independent reset accounts. No return compounding, portfolio stitching or OOS
|
||||
parameter ranking is applied.
|
||||
</p>
|
||||
{validation.report.limitations.map((value, index) => (
|
||||
<p key={index}>{value}</p>
|
||||
))}
|
||||
<ValidationEvidence
|
||||
title="Retained validation and test evidence"
|
||||
items={[validation.report.validation, validation.report.test]}
|
||||
backtestId={validation.backtestId}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import type { ExperimentSummary } from '@stock-bot/stock-config/experiments';
|
|||
import { Button } from '@/components/ui/Button';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentEditor } from './components/ExperimentEditor';
|
||||
import { SavedChronologicalValidations } from './components/SavedChronologicalValidations';
|
||||
import { experimentApi } from './services/experimentApi';
|
||||
|
||||
export function ExperimentListPage() {
|
||||
|
|
@ -71,6 +72,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
</p>
|
||||
</div>
|
||||
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
|
||||
<SavedChronologicalValidations backtestId={backtestId} />
|
||||
<section aria-label="Saved experiments" className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved experiments</h2>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
|
|
@ -9,6 +11,10 @@ import {
|
|||
chronologicalValidationApi,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '../services/chronologicalValidationApi';
|
||||
import {
|
||||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
} from '../services/chronologicalValidationDurableApi';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
|
|
@ -55,6 +61,8 @@ export function ChronologicalValidationPreflight({
|
|||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
|
|
@ -62,7 +70,20 @@ export function ChronologicalValidationPreflight({
|
|||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
claimSubmission: (owner: 'ordinary' | 'chronological') => boolean;
|
||||
releaseSubmission: (owner: 'ordinary' | 'chronological') => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const trainingIntent = useRef<{
|
||||
body: ChronologicalValidationSubmission;
|
||||
key: string;
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
} | null>(null);
|
||||
const trainingPending = useRef(false);
|
||||
const [hasTrainingIntent, setHasTrainingIntent] = useState(false);
|
||||
const [submittingTraining, setSubmittingTraining] = useState(false);
|
||||
const [trainingError, setTrainingError] = useState('');
|
||||
const [trainingAmbiguous, setTrainingAmbiguous] = useState(false);
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
|
|
@ -77,8 +98,10 @@ export function ChronologicalValidationPreflight({
|
|||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
|
||||
const currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview = prepared?.identity === identity ? prepared.preview : null;
|
||||
const dirty = phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
const preview =
|
||||
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty =
|
||||
hasTrainingIntent || phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
|
|
@ -99,7 +122,7 @@ export function ChronologicalValidationPreflight({
|
|||
setError('');
|
||||
}, [identity]);
|
||||
const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
|
||||
if (disabled) {
|
||||
if (disabled || trainingIntent.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
|
|
@ -107,7 +130,7 @@ export function ChronologicalValidationPreflight({
|
|||
setWindows(previous => ({ ...previous, [phase]: { ...previous[phase], [field]: value } }));
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !eligible || pending.current) {
|
||||
if (disabled || trainingIntent.current || !eligible || pending.current) {
|
||||
return;
|
||||
}
|
||||
const captured = identity;
|
||||
|
|
@ -166,6 +189,66 @@ export function ChronologicalValidationPreflight({
|
|||
}
|
||||
}
|
||||
};
|
||||
const submitTraining = async () => {
|
||||
if (
|
||||
trainingPending.current ||
|
||||
pending.current ||
|
||||
(!trainingIntent.current && (!preview || disabled || !eligible)) ||
|
||||
!claimSubmission('chronological')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!trainingIntent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
trainingIntent.current = {
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
preview,
|
||||
};
|
||||
}
|
||||
const captured = trainingIntent.current;
|
||||
trainingPending.current = true;
|
||||
setHasTrainingIntent(true);
|
||||
setSubmittingTraining(true);
|
||||
setTrainingError('');
|
||||
try {
|
||||
const accepted = await chronologicalValidationDurableApi.submit(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
trainingIntent.current = null;
|
||||
setHasTrainingIntent(false);
|
||||
releaseSubmission('chronological');
|
||||
navigate(`/experiments/validation/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setTrainingError(message(cause));
|
||||
setTrainingAmbiguous(!(cause instanceof ValidationApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
trainingPending.current = false;
|
||||
if (alive.current) {
|
||||
setSubmittingTraining(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const discardTraining = () => {
|
||||
if (
|
||||
trainingPending.current ||
|
||||
!window.confirm(
|
||||
'Discard this training submission? It may already exist. Inspect saved chronological validations before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
trainingIntent.current = null;
|
||||
setHasTrainingIntent(false);
|
||||
setTrainingError('');
|
||||
setTrainingAmbiguous(false);
|
||||
setPrepared(null);
|
||||
releaseSubmission('chronological');
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Chronological validation preflight"
|
||||
|
|
@ -173,8 +256,8 @@ export function ChronologicalValidationPreflight({
|
|||
>
|
||||
<h3 className="font-semibold text-text-primary">Chronological validation preflight</h3>
|
||||
<p>
|
||||
Preview only. No datasets, experiments or runs are saved. Staged execution and immutable
|
||||
reports are not available yet.
|
||||
Previewing does not save datasets, experiments or runs. Submit training runs explicitly to
|
||||
start a durable validation; selection and report finalization require separate actions.
|
||||
</p>
|
||||
<p className="text-text-secondary">
|
||||
Uses the saved backtest, experiment name and parameter grid above. Enter explicit UTC
|
||||
|
|
@ -185,7 +268,7 @@ export function ChronologicalValidationPreflight({
|
|||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">{phaseLabels[phase]} window</legend>
|
||||
|
|
@ -212,7 +295,7 @@ export function ChronologicalValidationPreflight({
|
|||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || !eligible || !name.trim() || loading}
|
||||
disabled={disabled || hasTrainingIntent || !eligible || !name.trim() || loading}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview chronological validation
|
||||
|
|
@ -223,6 +306,36 @@ export function ChronologicalValidationPreflight({
|
|||
{error}
|
||||
</p>
|
||||
)}
|
||||
{trainingError && (
|
||||
<p role="alert" className="text-error">
|
||||
{trainingError}
|
||||
</p>
|
||||
)}
|
||||
{hasTrainingIntent && (
|
||||
<p role="status">
|
||||
{trainingAmbiguous ? 'Training admission is unconfirmed. ' : ''}The exact training input
|
||||
and submission key are retained. Retry this submission to recover the same validation.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasTrainingIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={submittingTraining || (!hasTrainingIntent && (disabled || loading))}
|
||||
onClick={() => void submitTraining()}
|
||||
>
|
||||
{submittingTraining
|
||||
? 'Submitting training runs...'
|
||||
: hasTrainingIntent
|
||||
? 'Retry training submission'
|
||||
: 'Submit training runs'}
|
||||
</Button>
|
||||
{hasTrainingIntent && (
|
||||
<Button variant="outline" disabled={submittingTraining} onClick={discardTraining}>
|
||||
Discard training submission
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!preview && !loading && !error && (
|
||||
<p className="text-text-secondary">
|
||||
No chronological preview prepared for the current inputs.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
|
|
@ -49,6 +49,28 @@ export function ExperimentEditor({
|
|||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | null>(null);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner === 'chronological') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
}
|
||||
}, []);
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
|
|
@ -117,7 +139,7 @@ export function ExperimentEditor({
|
|||
}, [initialBacktestId, templateReload, limit]);
|
||||
|
||||
const invalidate = (change: () => void) => {
|
||||
if (intent.current) {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
|
|
@ -128,7 +150,7 @@ export function ExperimentEditor({
|
|||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (intent.current || previewLoading) {
|
||||
if (submissionOwner.current || previewLoading) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
|
|
@ -155,7 +177,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !preview)) {
|
||||
if (pending.current || (!intent.current && !preview) || !claimSubmission('ordinary')) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
|
|
@ -177,6 +199,7 @@ export function ExperimentEditor({
|
|||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
|
|
@ -202,6 +225,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
setPreview(null);
|
||||
setError('');
|
||||
|
|
@ -240,7 +264,7 @@ export function ExperimentEditor({
|
|||
<select
|
||||
className={fieldClass}
|
||||
value={backtestId}
|
||||
disabled={hasIntent || templateLoading}
|
||||
disabled={Boolean(lockedBy) || templateLoading}
|
||||
onChange={event => invalidate(() => setBacktestId(event.target.value))}
|
||||
>
|
||||
<option value="">Select a saved canonical backtest</option>
|
||||
|
|
@ -259,7 +283,7 @@ export function ExperimentEditor({
|
|||
<input
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
disabled={hasIntent}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setName(event.target.value))}
|
||||
/>
|
||||
</label>
|
||||
|
|
@ -268,7 +292,7 @@ export function ExperimentEditor({
|
|||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={templateLoading || hasIntent}
|
||||
disabled={templateLoading || Boolean(lockedBy)}
|
||||
onClick={() => setLimit(value => value + 50)}
|
||||
>
|
||||
Load more backtests
|
||||
|
|
@ -280,7 +304,7 @@ export function ExperimentEditor({
|
|||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
disabled={hasIntent}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
|
|
@ -299,7 +323,7 @@ export function ExperimentEditor({
|
|||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
hasIntent ||
|
||||
Boolean(lockedBy) ||
|
||||
previewLoading ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
|
|
@ -324,7 +348,10 @@ export function ExperimentEditor({
|
|||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting} onClick={() => void submit()}>
|
||||
<Button
|
||||
disabled={submitting || lockedBy === 'chronological'}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
? 'Submitting experiment...'
|
||||
: hasIntent
|
||||
|
|
@ -342,9 +369,11 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={hasIntent}
|
||||
disabled={lockedBy === 'ordinary'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,84 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { ChronologicalValidationSummary } from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { chronologicalValidationDurableApi } from '../services/chronologicalValidationDurableApi';
|
||||
|
||||
export function SavedChronologicalValidations({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<ChronologicalValidationSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void chronologicalValidationDurableApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(
|
||||
cause instanceof Error ? cause.message : 'Could not load chronological validations'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<section aria-label="Saved chronological validations" className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved chronological validations</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh chronological validations
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading chronological validations...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No saved chronological validations.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-1">
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/validation/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{item.stage === 'reported'
|
||||
? 'Execution complete · report saved'
|
||||
: item.stage === 'holdouts'
|
||||
? 'Validation and test admitted'
|
||||
: 'Training candidates admitted'}{' '}
|
||||
· {item.trainingCandidateCount} training candidates
|
||||
</p>
|
||||
{item.cancelRequested && <p className="text-sm">Cancellation requested</p>}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import { Link } from 'react-router-dom';
|
||||
import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation';
|
||||
|
||||
export function ValidationEvidence({
|
||||
title,
|
||||
items,
|
||||
backtestId,
|
||||
}: {
|
||||
title: string;
|
||||
items: ValidationResultEvidence[];
|
||||
backtestId: string;
|
||||
}) {
|
||||
const metric = (
|
||||
item: ValidationResultEvidence,
|
||||
key: keyof ValidationResultEvidence['metrics']
|
||||
) =>
|
||||
item.metrics[key] === null
|
||||
? `Unavailable${item.unavailable[key] ? `: ${item.unavailable[key]}` : ''}`
|
||||
: String(item.metrics[key]);
|
||||
return (
|
||||
<section aria-label={title} className="space-y-2">
|
||||
<h3 className="font-semibold">{title}</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Phase / source candidate',
|
||||
'Parameters',
|
||||
'Total return (fraction)',
|
||||
'Max drawdown (fraction)',
|
||||
'Sharpe ratio',
|
||||
'Samples / evidence',
|
||||
].map(label => (
|
||||
<th className="p-2 border-b border-border" key={label}>
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map(item => (
|
||||
<tr key={`${item.phase}:${item.runId}`} className="align-top">
|
||||
<td className="p-2 border-b border-border">
|
||||
{item.phase} · candidate {item.sourceCandidateIndex + 1}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(item.parameters, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'totalReturn')}</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'maxDrawdown')}</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'sharpeRatio')}</td>
|
||||
<td className="p-2 border-b border-border space-y-1 min-w-64">
|
||||
<p>
|
||||
Complete periods: {item.completePeriodCount} · Periodic samples:{' '}
|
||||
{item.periodicSampleCount} · Fills: {item.fillCount}
|
||||
</p>
|
||||
{item.periodicSampleCount < 2 && (
|
||||
<p>Insufficient periodic samples for variance-based statistics.</p>
|
||||
)}
|
||||
{item.limitations.map((value, index) => (
|
||||
<p key={index}>{value}</p>
|
||||
))}
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/backtests/${encodeURIComponent(backtestId)}/run/${encodeURIComponent(item.runId)}`}
|
||||
>
|
||||
Open {item.phase} candidate {item.sourceCandidateIndex + 1} run
|
||||
</Link>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained evidence</summary>
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(item, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ const invalid = () =>
|
|||
'The chronological validation preview could not be verified. Preview the current inputs again.'
|
||||
);
|
||||
|
||||
function parsePreview(
|
||||
export function parseChronologicalValidationPreview(
|
||||
body: unknown,
|
||||
input: ChronologicalValidationInput
|
||||
): ChronologicalValidationPreviewView {
|
||||
|
|
@ -150,7 +150,7 @@ export const chronologicalValidationApi = {
|
|||
if (response.status !== 200) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsePreview(body, input);
|
||||
return parseChronologicalValidationPreview(body, input);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,388 @@
|
|||
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']),
|
||||
});
|
||||
const evidence = 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(evidence).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(evidence).min(1).max(100),
|
||||
validation: evidence,
|
||||
test: evidence,
|
||||
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
|
||||
);
|
||||
function parseDetail(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 evidence>,
|
||||
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 = parseDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
submit: (input: ChronologicalValidationSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseDetail(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 = parseDetail(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 = parseDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
};
|
||||
export type { ValidationResultEvidence };
|
||||
|
|
@ -87,7 +87,7 @@ const preview = z.object({
|
|||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const metric = z.number().finite().nullable();
|
||||
const metrics = z.object({
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
|
|
@ -118,7 +118,7 @@ const trial = candidate.extend({
|
|||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: metrics.nullable(),
|
||||
metrics: experimentMetricsSchema.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
|
@ -185,7 +185,7 @@ export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
|||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
function parseDetail(value: unknown): ExperimentDetailView {
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
parseSummary(parsed);
|
||||
const retained = parseExperimentPreview(parsed.preview);
|
||||
|
|
@ -282,7 +282,7 @@ export const experimentApi = {
|
|||
202,
|
||||
body => {
|
||||
const receipt = retryReceipt.parse(envelope(body, 'retry'));
|
||||
const experiment = parseDetail(envelope(body, 'experiment'));
|
||||
const experiment = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const current = experiment.trials.find(
|
||||
item => item.trialKey === target.trialKey && item.runId === target.runId
|
||||
);
|
||||
|
|
@ -360,7 +360,7 @@ export const experimentApi = {
|
|||
},
|
||||
202,
|
||||
body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
|
|
@ -370,7 +370,7 @@ export const experimentApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -378,7 +378,7 @@ export const experimentApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue