diff --git a/apps/stock/config/src/contracts/chronological-validation.ts b/apps/stock/config/src/contracts/chronological-validation.ts index 3cd4f239..cd245772 100644 --- a/apps/stock/config/src/contracts/chronological-validation.ts +++ b/apps/stock/config/src/contracts/chronological-validation.ts @@ -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; +} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 20199ae8..ef2fe600 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -63,7 +63,8 @@ export async function runMigrations(container: IServiceContainer): Promise 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(); diff --git a/apps/stock/web-api/src/routes/experiments.routes.ts b/apps/stock/web-api/src/routes/experiments.routes.ts index 6972ed5e..a52a01c8 100644 --- a/apps/stock/web-api/src/routes/experiments.routes.ts +++ b/apps/stock/web-api/src/routes/experiments.routes.ts @@ -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) }); diff --git a/apps/stock/web-api/src/services/chronological-validation.service.ts b/apps/stock/web-api/src/services/chronological-validation.service.ts new file mode 100644 index 00000000..4d3b9c2e --- /dev/null +++ b/apps/stock/web-api/src/services/chronological-validation.service.ts @@ -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 { + 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 { + 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 { + experimentId(id); + return this.database.transaction(client => this.readDetail(client, id)); + } + async cancel(id: string): Promise { + 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 { + 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 = { + ...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 { + 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( + 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, + hash: string + ): Promise { + 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 { + 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 { + 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( + row.validation_selection, + 'selectionHash' + ) + : null; + const report = row.validation_report + ? publicValidationDocument(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', + }, + }, + }; + } +} diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts index d299da10..46642987 100644 --- a/apps/stock/web-api/src/services/experiments.service.ts +++ b/apps/stock/web-api/src/services/experiments.service.ts @@ -118,10 +118,7 @@ export class ExperimentsService { return prepareChronologicalValidation(input, source, dataset).preview; }); } - private async lockedPreview( - client: PoolClient, - input: ExperimentInput - ): Promise { + async lockedPreview(client: PoolClient, input: ExperimentInput): Promise { 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 { + async readDetail(database: Query, id: string): Promise { const row = ( await database.query( `SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`, diff --git a/apps/stock/web-api/src/services/validation-evidence.ts b/apps/stock/web-api/src/services/validation-evidence.ts new file mode 100644 index 00000000..339ba990 --- /dev/null +++ b/apps/stock/web-api/src/services/validation-evidence.ts @@ -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(schema: T, raw: unknown): z.infer { + 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 & { _receipt: { key: string; hash: string } }; +export function publicValidationDocument< + T extends ChronologicalValidationSelection | ChronologicalValidationReport, +>(value: PrivateValidationDocument, key: 'selectionHash' | 'reportHash'): T { + const { _receipt, ...document } = value; + const manifest: Record = { ...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; +} diff --git a/apps/stock/web-app/src/app/App.tsx b/apps/stock/web-app/src/app/App.tsx index 6531e49b..21a8ce21 100644 --- a/apps/stock/web-app/src/app/App.tsx +++ b/apps/stock/web-app/src/app/App.tsx @@ -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() { } /> + } + /> } /> (); + return ; +} +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(null); + const captured = useRef(null); + const [intent, setIntent] = useState(null); + const [validation, setValidation] = useState(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(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 ( +
{ + 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(); + } + }} + > + + All experiments + +
+

{validation?.name ?? 'Chronological validation'}

+ +
+ {loading &&

Loading validation...

} + {readError && ( +

+ {readError} + {validation && ' Showing the last loaded state.'} +

+ )} + {actionError && ( +

+ {actionError} +

+ )} + {intent && ( +
+

+ {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. +

+ {' '} + +
+ )} + {receipt && ( +

+ {receipt.operation === 'select-and-admit-holdouts' + ? 'Selection and holdout admission accepted.' + : 'Report finalization accepted.'}{' '} + Receipt {receipt.id} · {receipt.createdAt} +

+ )} + {validation && ( + <> +

+ {validation.report + ? 'Execution complete · report saved' + : validation.selection + ? 'Fixed selection saved · validation and test admitted' + : 'Training candidates admitted · selection not yet frozen'} +

+

+ {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. +

+ {validation.cancelRequested && ( +

+ Cancellation requested. Completed evidence remains retained; active work may still + finish. +

+ )} + {!intent && ( +
+ {!validation.selection && ( + + )} + {validation.selection && !validation.report && ( + + )} +
+ )} + {!validation.selection && validation.actions.select.reason && ( +

{validation.actions.select.reason}

+ )} + {validation.selection && !validation.report && validation.actions.finalize.reason && ( +

{validation.actions.finalize.reason}

+ )} + {!validation.cancelRequested && !validation.report && ( + + )} +
+

Frozen chronological recipe

+

+ 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. +

+

+ 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} +

+

+ Selection uses training results only in this workflow. These dates may have been + examined in other research. +

+
+ {validation.preview.partitions.map(part => ( +
+

{part.phase} window

+

Warmup: {new Date(part.dataset.bounds.warmupStart).toISOString()}

+

+ Trading: {new Date(part.dataset.bounds.tradeStart).toISOString()} —{' '} + {new Date(part.dataset.bounds.tradeEnd).toISOString()} (end exclusive) +

+

Dataset: {part.dataset.hash}

+

+ Admitted / required warmup: {part.counts.admittedWarmup} / {part.requiredWarmup} +

+ {part.warnings.map((warning, index) => ( +

{warning}

+ ))} +
+ ))} +
+
+ Exact retained recipe and policies +
+                {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
+                )}
+              
+
+
+
+

Phase outcomes

+ {validation.phases.map(phase => ( +
+

{phase.phase}

+ {phase.status === 'not-admitted' && ( +

+ Not admitted. No {phase.phase} run exists before the fixed selection is saved. +

+ )} + {phase.status === 'missing' && ( +

+ Expected {phase.phase} experiment is missing. Report finalization is blocked. +

+ )} + {phase.experiment && ( + <> + +
    + {phase.experiment.trials.map(trial => ( +
  • + 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'} +
    {JSON.stringify(trial.parameters)}
    + {trial.error &&

    {trial.error}

    } + {trial.diagnostic &&

    {trial.diagnostic}

    } +

    + Total return (fraction):{' '} + {trial.metrics?.totalReturn === null || + trial.metrics?.totalReturn === undefined + ? `Unavailable${trial.unavailable?.totalReturn ? `: ${trial.unavailable.totalReturn}` : ''}` + : String(trial.metrics.totalReturn)} +

    + {trial.runId && ( + + Open {phase.phase} run {trial.index + 1} + + )} +
  • + ))} +
+ + )} + {phase.experimentId && ( + + Open {phase.phase} experiment + + )} +
+ ))} +
+ {validation.selection && ( +
+

Fixed training selection

+

Selected training candidate {validation.selection.winner.index + 1}

+
+                {JSON.stringify(validation.selection.winner.parameters, null, 2)}
+              
+

+ Selection {validation.selection.id} · {validation.selection.selectionHash} ·{' '} + {validation.selection.createdAt} · {validation.selection.principal} +

+

+ Holdout admission approval: {validation.selection.reviewId} +

+
+ )} + {validation.selection && ( + + )} + {validation.report && ( +
+

Saved validation report

+

+ Report {validation.report.id} · {validation.report.reportHash} ·{' '} + {validation.report.createdAt} · {validation.report.principal} +

+

+ Independent reset accounts. No return compounding, portfolio stitching or OOS + parameter ranking is applied. +

+ {validation.report.limitations.map((value, index) => ( +

{value}

+ ))} + +
+ )} + + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx index 1c5c2469..09fc469d 100644 --- a/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx @@ -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 }) {

+

Saved experiments

diff --git a/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx b/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx index d6364583..ed6441d5 100644 --- a/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx +++ b/apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx @@ -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(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 (

Chronological validation preflight

- 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.

Uses the saved backtest, experiment name and parameter grid above. Enter explicit UTC @@ -185,7 +268,7 @@ export function ChronologicalValidationPreflight({ {phases.map(phase => (

{phaseLabels[phase]} window @@ -212,7 +295,7 @@ export function ChronologicalValidationPreflight({ )} + {hasTrainingIntent && ( + + )} +
+ )} {!preview && !loading && !error && (

No chronological preview prepared for the current inputs. diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx index eea5809f..8e0a51e9 100644 --- a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx +++ b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx @@ -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(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({ invalidate(() => setName(event.target.value))} /> @@ -268,7 +292,7 @@ export function ExperimentEditor({

); diff --git a/apps/stock/web-app/src/features/experiments/components/SavedChronologicalValidations.tsx b/apps/stock/web-app/src/features/experiments/components/SavedChronologicalValidations.tsx new file mode 100644 index 00000000..4884a790 --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/components/SavedChronologicalValidations.tsx @@ -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([]); + 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 ( +
+
+

Saved chronological validations

+ +
+ {loading &&

Loading chronological validations...

} + {error && ( +

+ {error} +

+ )} + {!loading && !error && rows.length === 0 &&

No saved chronological validations.

} + {rows.map(item => ( +
+ + {item.name} + +

+ {item.stage === 'reported' + ? 'Execution complete · report saved' + : item.stage === 'holdouts' + ? 'Validation and test admitted' + : 'Training candidates admitted'}{' '} + · {item.trainingCandidateCount} training candidates +

+ {item.cancelRequested &&

Cancellation requested

} +

Created {item.createdAt}

+
+ ))} +
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/components/ValidationEvidence.tsx b/apps/stock/web-app/src/features/experiments/components/ValidationEvidence.tsx new file mode 100644 index 00000000..6eb125c9 --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/components/ValidationEvidence.tsx @@ -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 ( +
+

{title}

+
+ + + + {[ + 'Phase / source candidate', + 'Parameters', + 'Total return (fraction)', + 'Max drawdown (fraction)', + 'Sharpe ratio', + 'Samples / evidence', + ].map(label => ( + + ))} + + + + {items.map(item => ( + + + + + + + + + ))} + +
+ {label} +
+ {item.phase} · candidate {item.sourceCandidateIndex + 1} + +
+                    {JSON.stringify(item.parameters, null, 2)}
+                  
+
{metric(item, 'totalReturn')}{metric(item, 'maxDrawdown')}{metric(item, 'sharpeRatio')} +

+ Complete periods: {item.completePeriodCount} · Periodic samples:{' '} + {item.periodicSampleCount} · Fills: {item.fillCount} +

+ {item.periodicSampleCount < 2 && ( +

Insufficient periodic samples for variance-based statistics.

+ )} + {item.limitations.map((value, index) => ( +

{value}

+ ))} + + Open {item.phase} candidate {item.sourceCandidateIndex + 1} run + +
+ Exact retained evidence +
+                      {JSON.stringify(item, null, 2)}
+                    
+
+
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/index.ts b/apps/stock/web-app/src/features/experiments/index.ts index 4cca53ef..72d7ebb9 100644 --- a/apps/stock/web-app/src/features/experiments/index.ts +++ b/apps/stock/web-app/src/features/experiments/index.ts @@ -1,2 +1,3 @@ export { ExperimentListPage } from './ExperimentListPage'; export { ExperimentDetailPage } from './ExperimentDetailPage'; +export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage'; diff --git a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts index 6f6381f5..00333e5e 100644 --- a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts @@ -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(); } diff --git a/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts new file mode 100644 index 00000000..95627326 --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts @@ -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 & { + 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, + 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( + path: string, + init: RequestInit, + status: number, + parse: (body: unknown) => T +): Promise { + 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 }; diff --git a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts index 84490735..42d1abde 100644 --- a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts @@ -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(); } diff --git a/database/postgres/init/24-chronological-validation.sql b/database/postgres/init/24-chronological-validation.sql new file mode 100644 index 00000000..d234aa46 --- /dev/null +++ b/database/postgres/init/24-chronological-validation.sql @@ -0,0 +1,442 @@ +-- Each chronological phase remains an ordinary one-dataset experiment and run lifecycle. +ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_manifest JSONB; +ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_parent_id UUID REFERENCES research_experiments(id) ON DELETE RESTRICT; +ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_phase TEXT; +ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_selection JSONB; +ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_report JSONB; +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='validation_experiment_shape' AND conrelid='research_experiments'::regclass) THEN + ALTER TABLE research_experiments ADD CONSTRAINT validation_experiment_shape CHECK (( + (validation_phase IS NULL AND validation_parent_id IS NULL AND validation_manifest IS NULL AND validation_selection IS NULL AND validation_report IS NULL) + OR (validation_phase='train' AND validation_parent_id IS NULL AND validation_manifest IS NOT NULL) + OR (validation_phase IN ('validation','test') AND validation_parent_id IS NOT NULL AND validation_parent_id<>id AND validation_manifest IS NULL AND validation_selection IS NULL AND validation_report IS NULL) + ) IS TRUE); + END IF; +END $$; +CREATE UNIQUE INDEX IF NOT EXISTS validation_child_phase ON research_experiments(validation_parent_id,validation_phase) WHERE validation_parent_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS validation_selection_receipt ON research_experiments((validation_selection->>'principal'),(validation_selection#>>'{_receipt,key}')) WHERE validation_selection IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS validation_report_receipt ON research_experiments((validation_report->>'principal'),(validation_report#>>'{_receipt,key}')) WHERE validation_report IS NOT NULL; + +-- Reuse the original source-template proof without invoking a trigger function as a normal function. +CREATE OR REPLACE FUNCTION validate_experiment_manifest(candidate_row research_experiments) RETURNS void LANGUAGE plpgsql AS $$ +DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; request JSONB; candidate JSONB; candidate_index INTEGER := 0; +BEGIN + SELECT * INTO parent FROM backtests WHERE id=candidate_row.backtest_id FOR UPDATE; + request := candidate_row.preview->'request'; + IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND NOT candidate_row.cancel_requested + AND jsonb_typeof(candidate_row.preview)='object' AND candidate_row.preview->>'version'='research-experiment-preview/v1' + AND candidate_row.preview->>'previewHash'=candidate_row.preview_hash AND candidate_row.preview#>>'{input,name}'=candidate_row.name + AND candidate_row.preview#>>'{input,backtestId}'=candidate_row.backtest_id::text + AND jsonb_typeof(candidate_row.preview#>'{input,grid}')='object' + AND jsonb_typeof(candidate_row.preview->'candidates')='array' + AND jsonb_array_length(candidate_row.preview->'candidates') BETWEEN 1 AND 100 + AND request->>'kind'='canonical-research/v1' AND request->>'backtestId'=candidate_row.backtest_id::text + AND request->>'runId'='00000000-0000-4000-8000-000000000001' + AND request->>'name'=parent.name + AND request#>>'{strategy,versionId}'=parent.strategy_version_id::text + AND request#>'{strategy,selection,parameters}'=parent.strategy_parameters + AND request->>'datasetHash'=parent.config->>'datasetHash' + AND request#>>'{policy,matching,risk,ledger,sessionId}'=request->>'runId' + AND request#>>'{policy,matching,risk,ledger,accountId}'='research:'||(request->>'runId') + AND request#>>'{policy,matching,risk,ledger,baseCurrency}'='USD' + AND request#>>'{policy,matching,risk,ledger,reserveOwnerId}'='reserve' + AND (request#>>'{policy,matching,risk,ledger,initialCapital}')::numeric=parent.initial_capital + AND request#>>'{strategy,selection,ownerBudget}'=parent.config#>>'{canonical,ownerBudget}' + AND request#>'{strategy,selection,seed}'=parent.config#>'{canonical,seed}' + AND request#>>'{policy,allow_exploratory}'='false' + AND jsonb_typeof(request->'build')='object' + AND request#>>'{build,version}'='1' AND request#>>'{build,runtime}'='bun' + AND request#>>'{build,workerSha256}' ~ '^[a-f0-9]{64}$' + AND request#>>'{build,engineWrapperSha256}' ~ '^[a-f0-9]{64}$' + AND request#>>'{build,engineBinarySha256}' ~ '^[a-f0-9]{64}$' + AND request#>>'{build,dependencyLockSha256}' ~ '^[a-f0-9]{64}$' + AND length(request#>>'{build,runtimeVersion}')>0 AND length(request#>>'{build,platform}')>0 AND length(request#>>'{build,arch}')>0 + AND request->'modelArtifacts'='[]'::jsonb) IS NOT TRUE THEN + RAISE EXCEPTION 'Experiment manifest requires an active canonical template and complete frozen identity' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM jsonb_each(parent.config->'canonical') settings + WHERE CASE settings.key + WHEN 'version' THEN request#>'{analyticsPolicy,version}' + WHEN 'ownerBudget' THEN request#>'{strategy,selection,ownerBudget}' + WHEN 'seed' THEN request#>'{strategy,selection,seed}' + WHEN 'halfSpreadRate' THEN request#>'{policy,matching,halfSpreadRate}' + WHEN 'slippageRate' THEN request#>'{policy,matching,slippageRate}' + WHEN 'latencyMs' THEN request#>'{policy,matching,latencyMs}' + WHEN 'participationRate' THEN request#>'{policy,participation_rate}' + WHEN 'periodsPerYear' THEN request#>'{analyticsPolicy,periodsPerYear}' + WHEN 'annualRiskFreeRate' THEN request#>'{analyticsPolicy,annualRiskFreeRate}' + ELSE request#>ARRAY['policy','matching','risk',settings.key] END IS DISTINCT FROM settings.value) THEN + RAISE EXCEPTION 'Experiment financial and analysis settings must match its saved template' USING ERRCODE='23514'; + END IF; + SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id + WHERE v.id=parent.strategy_version_id FOR UPDATE OF s; + SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; + IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' + AND request#>>'{strategy,origin}'='builtin' AND request#>>'{strategy,familyId}'=selected.strategy_id::text + AND request#>>'{strategy,reviewId}'=approval.id::text AND request#>'{strategy,package}'=selected.envelope + AND request#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text + AND request#>'{policy,matching,risk,ledger,ownerIds}'=jsonb_build_array('strategy:'||selected.id::text) + AND request#>'{policy,matching,owners}'=jsonb_build_array(jsonb_build_object('ownerId','strategy:'||selected.id::text,'mode','Target')) + AND request#>>'{strategy,selection,strategyId}'=selected.envelope#>>'{program,strategyId}' + AND request#>>'{strategy,selection,strategyVersion}'=selected.envelope#>>'{program,strategyVersion}') IS NOT TRUE THEN + RAISE EXCEPTION 'Experiment requires the exact current approved built-in version' USING ERRCODE='23514'; + END IF; + SELECT payload INTO retained FROM backtest_datasets WHERE hash=request->>'datasetHash'; + IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible' + AND retained->'manifest'=candidate_row.preview->'dataset' AND retained#>>'{manifest,hash}'=request->>'datasetHash' + AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 AND jsonb_array_length(retained#>'{manifest,series}')=1 + AND jsonb_array_length(retained#>'{manifest,universe,instrumentIds}')=1 + AND request#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}' + AND request#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}' + AND request#>'{policy,matching,series}'=jsonb_build_array(jsonb_build_object('instrumentId',request#>>'{strategy,selection,instrumentId}','seriesId',request#>>'{strategy,selection,seriesId}','mode','Open')) + AND request#>'{policy,cadence}'=jsonb_build_array(jsonb_build_object('owner_id','strategy:'||selected.id::text,'series_ids',jsonb_build_array(request#>>'{strategy,selection,seriesId}')))) IS NOT TRUE THEN + RAISE EXCEPTION 'Experiment requires the exact eligible retained single-asset dataset' USING ERRCODE='23514'; + END IF; + FOR candidate IN SELECT value FROM jsonb_array_elements(candidate_row.preview->'candidates') LOOP + IF (jsonb_typeof(candidate)='object' AND candidate->>'index'=candidate_index::text + AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(candidate->'parameters')='object' + AND candidate->'parameters' <> '{}'::jsonb + AND NOT EXISTS (SELECT 1 FROM jsonb_object_keys(candidate->'parameters') p(key) + WHERE p.key IN ('__proto__','constructor','prototype') OR NOT selected.envelope#>'{parameterSchema,properties}' ? p.key) + AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(selected.envelope#>'{parameterSchema,required}') required(key) + WHERE NOT candidate->'parameters' ? required.key) + AND NOT EXISTS (SELECT 1 FROM jsonb_each(candidate->'parameters') p WHERE jsonb_typeof(p.value) NOT IN ('string','number','boolean'))) IS NOT TRUE THEN + RAISE EXCEPTION 'Experiment candidates require contiguous indexes, keys and complete scalar parameters' USING ERRCODE='23514'; + END IF; + candidate_index := candidate_index+1; + END LOOP; + IF (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(candidate_row.preview->'candidates'))<>candidate_index + OR (SELECT count(DISTINCT value->'parameters') FROM jsonb_array_elements(candidate_row.preview->'candidates'))<>candidate_index THEN + RAISE EXCEPTION 'Experiment candidates must be unique' USING ERRCODE='23514'; + END IF; + RETURN; +END $$; +CREATE OR REPLACE FUNCTION require_experiment_manifest() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + PERFORM validate_experiment_manifest(NEW); RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS experiment_manifest_admission ON research_experiments; +CREATE TRIGGER experiment_manifest_admission BEFORE INSERT ON research_experiments FOR EACH ROW WHEN (NEW.validation_phase IS NULL) EXECUTE FUNCTION require_experiment_manifest(); + +CREATE OR REPLACE FUNCTION assert_validation_phase_preview(value JSONB, manifest JSONB, phase TEXT, winner JSONB DEFAULT NULL, review_id TEXT DEFAULT NULL) +RETURNS void LANGUAGE plpgsql AS $$ +DECLARE partition JSONB; request JSONB; candidates JSONB; expected JSONB; +BEGIN + partition := manifest->'partitions'->CASE phase WHEN 'train' THEN 0 WHEN 'validation' THEN 1 WHEN 'test' THEN 2 ELSE -1 END; + request := partition->'request'; + IF phase='train' THEN candidates := manifest#>'{source,candidates}'; + ELSE + IF winner IS NULL OR review_id IS NULL THEN RAISE EXCEPTION 'Holdout requires frozen winner and approval' USING ERRCODE='23514'; END IF; + request := jsonb_set(request,'{strategy,selection,parameters}',winner->'parameters'); + request := jsonb_set(request,'{strategy,reviewId}',to_jsonb(review_id)); + candidates := jsonb_build_array(jsonb_set(winner,'{index}','0'::jsonb)); + END IF; + expected := jsonb_build_object('version','research-experiment-preview/v1','input',jsonb_build_object( + 'backtestId',manifest#>'{input,backtestId}','name',(manifest#>>'{input,name}')||' · '||phase, + 'grid',CASE WHEN phase='train' THEN manifest#>'{input,grid}' ELSE '{}'::jsonb END), + 'request',request,'dataset',partition->'dataset','candidates',candidates); + IF ((value-'previewHash')=expected AND value->>'previewHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Validation phase must preserve its exact frozen request, data and candidate' USING ERRCODE='23514'; + END IF; +END $$; + +CREATE OR REPLACE FUNCTION assert_validation_preparation(manifest JSONB) RETURNS void LANGUAGE plpgsql AS $$ +DECLARE source JSONB; retained JSONB; slice JSONB; partition JSONB; bounds JSONB; bar JSONB; calendar JSONB; + phase TEXT; idx INTEGER := 0; candidate JSONB; required_history INTEGER := 0; n INTEGER; + warmup BIGINT; start_at BIGINT; end_at BIGINT; prior_end BIGINT := NULL; + total INTEGER; available_warmup INTEGER; admitted INTEGER; evaluation INTEGER; terminal INTEGER; delayed INTEGER; + previous_event BIGINT; previous_sequence BIGINT; event_at BIGINT; sequence BIGINT; arrival BIGINT; + expected_bars JSONB; expected_manifest JSONB; expected_request JSONB; initial_session JSONB; boundaries JSONB; counts JSONB; +BEGIN + source := manifest->'source'; + IF (manifest->>'version'='chronological-validation-preview/v1' AND manifest->>'execution'='preview-only' + AND manifest->>'previewHash' ~ '^[a-f0-9]{64}$' + AND ((manifest->'input')-'recipe')=source->'input' + AND manifest#>'{input,recipe,version}'='1'::jsonb AND manifest#>'{input,recipe,labelHorizonMs}'='0'::jsonb + AND jsonb_typeof(manifest->'partitions')='array' AND jsonb_array_length(manifest->'partitions')=3 + AND manifest->'policy'='{"selection":{"phase":"train","metric":"totalReturn","direction":"maximize","tieBreak":"candidate-index","requireAllCandidates":true},"validationRole":"diagnostic-only","testRole":"holdout-only","reset":"initial-capital-empty-positions","model":"deterministic-unfitted","readiness":"input-checks-only"}'::jsonb) IS NOT TRUE THEN + RAISE EXCEPTION 'Validation requires the fixed complete chronological preparation policy' USING ERRCODE='23514'; + END IF; + SELECT payload INTO retained FROM backtest_datasets WHERE hash=source#>>'{request,datasetHash}'; + IF (retained->'manifest'=source->'dataset' AND retained#>>'{manifest,eligibility}'='eligible') IS NOT TRUE THEN + RAISE EXCEPTION 'Validation source must equal its retained eligible manifest' USING ERRCODE='23514'; + END IF; + FOR candidate IN SELECT value FROM jsonb_array_elements(source->'candidates') LOOP + IF source#>>'{request,strategy,selection,strategyId}'='sma_crossover' THEN + n := (candidate#>>'{parameters,slowPeriod}')::integer+1; + ELSIF source#>>'{request,strategy,selection,strategyId}'='mean_reversion' THEN + n := GREATEST((candidate#>>'{parameters,lookbackPeriod}')::integer,(candidate#>>'{parameters,trendPeriod}')::integer, + (candidate#>>'{parameters,momentumPeriod}')::integer+1,(candidate#>>'{parameters,volatilityPeriod}')::integer+1); + ELSE RAISE EXCEPTION 'Unsupported validation strategy' USING ERRCODE='23514'; END IF; + required_history := GREATEST(required_history,n); + END LOOP; + SELECT value INTO calendar FROM jsonb_array_elements(retained#>'{manifest,calendars}') WHERE value->>'id'=retained#>>'{manifest,series,0,calendarId}'; + FOREACH phase IN ARRAY ARRAY['train','validation','test'] LOOP + partition := manifest->'partitions'->idx; bounds := manifest#>ARRAY['input','recipe',phase]; + warmup := (bounds->>'warmupStart')::bigint; start_at := (bounds->>'tradeStart')::bigint; end_at := (bounds->>'tradeEnd')::bigint; + IF (partition->>'phase'=phase AND warmup=(retained#>>'{manifest,bounds,warmupStart}')::bigint + AND start_at>=(retained#>>'{manifest,bounds,tradeStart}')::bigint + AND end_at<=(retained#>>'{manifest,bounds,tradeEnd}')::bigint + AND (prior_end IS NULL OR prior_end<=start_at) + AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(retained->'bars') b, unnest(ARRAY[warmup,start_at,end_at]) boundary + WHERE (b->>'intervalStart')::bigint>'intervalEnd')::bigint)) IS NOT TRUE THEN + RAISE EXCEPTION 'Validation windows must be exact chronological in-source boundaries' USING ERRCODE='23514'; + END IF; + SELECT COALESCE(jsonb_agg(value ORDER BY ordinality),'[]'::jsonb) INTO expected_bars FROM jsonb_array_elements(retained->'bars') WITH ORDINALITY + WHERE (value->>'intervalStart')::bigint>=warmup AND (value->>'intervalEnd')::bigint<=end_at; + total := jsonb_array_length(expected_bars); + expected_manifest := ((retained->'manifest')-'hash'-'bounds'-'barCount') || jsonb_build_object('hash',partition#>'{dataset,hash}','bounds',bounds,'barCount',total); + SELECT payload INTO slice FROM backtest_datasets WHERE hash=partition#>>'{dataset,hash}'; + IF (total>0 AND slice->'bars'=expected_bars AND slice->'manifest'=expected_manifest AND partition->'dataset'=expected_manifest + AND partition#>>'{dataset,hash}' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Validation slice must preserve exact source bars, availability and metadata' USING ERRCODE='23514'; + END IF; + available_warmup:=0; admitted:=0; evaluation:=0; terminal:=0; delayed:=0; previous_event:=NULL; previous_sequence:=NULL; + FOR bar IN SELECT value FROM jsonb_array_elements(expected_bars) LOOP + arrival:=(bar->>'availableAt')::bigint; event_at:=(bar->>'eventTime')::bigint; sequence:=(bar->>'sourceSequence')::bigint; + IF arrivalprevious_event OR (event_at=previous_event AND sequence>previous_sequence) THEN + admitted:=admitted+1; previous_event:=event_at; previous_sequence:=sequence; + END IF; + ELSIF arrival'counts'=counts AND (partition->>'requiredWarmup')::integer=required_history AND admitted>=required_history AND evaluation>0 + AND jsonb_typeof(partition->'warnings')='array') IS NOT TRUE THEN + RAISE EXCEPTION 'Validation history readiness and availability counts must be exact' USING ERRCODE='23514'; + END IF; + SELECT value INTO initial_session FROM jsonb_array_elements(calendar->'sessions') WHERE (value->>'open')::bigint<=warmup ORDER BY (value->>'open')::bigint DESC LIMIT 1; + SELECT COALESCE(jsonb_agg(jsonb_build_object('calendarId',calendar->'id','calendarRevision',calendar->'revision','sessionId',value->'date','startsAt',value->'open') ORDER BY ordinality),'[]'::jsonb) + INTO boundaries FROM jsonb_array_elements(calendar->'sessions') WITH ORDINALITY WHERE (value->>'open')::bigint>warmup AND (value->>'open')::bigint<=end_at; + expected_request:=jsonb_set(source->'request','{datasetHash}',partition#>'{dataset,hash}'); + expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,riskSession}',jsonb_build_object('calendarId',calendar->'id','calendarRevision',calendar->'revision','sessionId',initial_session->'date','startsAt',initial_session->'open')); + expected_request:=jsonb_set(expected_request,'{policy,risk_boundaries}',boundaries); + IF (initial_session IS NOT NULL AND partition->'request'=expected_request) IS NOT TRUE THEN + RAISE EXCEPTION 'Validation phases may change only their dataset and exact retained account clock' USING ERRCODE='23514'; + END IF; + idx:=idx+1; prior_end:=end_at; + END LOOP; +END $$; + +CREATE OR REPLACE FUNCTION require_validation_experiment() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE source_row research_experiments; root research_experiments; selected RECORD; approval RECORD; phase_id TEXT; +BEGIN + IF NEW.validation_selection IS NOT NULL OR NEW.validation_report IS NOT NULL OR NEW.cancel_requested THEN + RAISE EXCEPTION 'New validation phases cannot invent selection, report or cancellation' USING ERRCODE='23514'; + END IF; + IF NEW.validation_phase='train' THEN + source_row:=NEW; source_row.preview:=NEW.validation_manifest->'source'; source_row.preview_hash:=source_row.preview->>'previewHash'; source_row.name:=source_row.preview#>>'{input,name}'; + PERFORM validate_experiment_manifest(source_row); + PERFORM assert_validation_preparation(NEW.validation_manifest); + PERFORM assert_validation_phase_preview(NEW.preview,NEW.validation_manifest,'train'); + ELSE + -- The service already holds the parent; direct insert follows the same order. + PERFORM 1 FROM backtests WHERE id=NEW.backtest_id AND archived_at IS NULL FOR UPDATE; + IF NOT FOUND THEN RAISE EXCEPTION 'Holdout requires an active parent' USING ERRCODE='23514'; END IF; + SELECT * INTO root FROM research_experiments WHERE id=NEW.validation_parent_id FOR UPDATE; + phase_id:=root.validation_selection#>>ARRAY['holdoutExperimentIds',NEW.validation_phase]; + IF (root.validation_phase='train' AND NOT root.cancel_requested AND root.validation_selection IS NOT NULL + AND root.backtest_id=NEW.backtest_id AND phase_id=NEW.id::text AND NEW.name=(root.validation_manifest#>>'{input,name}')||' · '||NEW.validation_phase + AND NEW.submission_principal=root.validation_selection->>'principal' + AND NEW.submission_key='validation-child:'||NEW.id::text) IS NOT TRUE THEN + RAISE EXCEPTION 'Holdout must belong to its uncancelled frozen training selection' USING ERRCODE='23514'; + END IF; + SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id + WHERE v.id::text=root.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s; + SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; + IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' + AND root.validation_selection->>'reviewId'=approval.id::text + AND root.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN + RAISE EXCEPTION 'Holdout requires current approval of the original frozen version' USING ERRCODE='23514'; + END IF; + PERFORM assert_validation_phase_preview(NEW.preview,root.validation_manifest,NEW.validation_phase,root.validation_selection->'winner',root.validation_selection->>'reviewId'); + END IF; + IF (NEW.preview->>'previewHash'=NEW.preview_hash AND NEW.preview#>>'{input,name}'=NEW.name + AND NEW.preview#>>'{input,backtestId}'=NEW.backtest_id::text) IS NOT TRUE THEN + RAISE EXCEPTION 'Validation phase row identity must match its preview' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS validation_experiment_admission ON research_experiments; +CREATE TRIGGER validation_experiment_admission BEFORE INSERT ON research_experiments FOR EACH ROW WHEN (NEW.validation_phase IS NOT NULL) EXECUTE FUNCTION require_validation_experiment(); + +-- Copies/provenance checks only. Existing Rust results and verified canonical reporting own economics. +CREATE OR REPLACE FUNCTION assert_validation_evidence(item JSONB, phase_experiment_id UUID, phase TEXT, source_index INTEGER) +RETURNS numeric LANGUAGE plpgsql AS $$ +DECLARE experiment research_experiments; run RECORD; result JSONB; expected_request JSONB; expected JSONB; candidate JSONB; analysis_policy JSONB; metric RECORD; +BEGIN + SELECT * INTO experiment FROM research_experiments WHERE id=phase_experiment_id; + SELECT r.*,br.canonical_result INTO run FROM runs r LEFT JOIN backtest_results br ON br.run_id=r.id + WHERE r.id::text=item->>'runId' AND r.experiment_id=phase_experiment_id; + result:=run.canonical_result; candidate:=experiment.preview->'candidates'->run.trial_index; + expected_request:=jsonb_set(experiment.preview->'request','{runId}',to_jsonb(run.id::text)); + expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,sessionId}',to_jsonb(run.id::text)); + expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||run.id::text)); + expected_request:=jsonb_set(expected_request,'{strategy,selection,parameters}',candidate->'parameters'); + analysis_policy:=(expected_request->'analyticsPolicy') || jsonb_build_object( + 'calendarId',expected_request#>'{policy,matching,risk,ledger,riskSession,calendarId}', + 'calendarRevision',expected_request#>'{policy,matching,risk,ledger,riskSession,calendarRevision}', + 'sampling','account-boundary-after-observations-v1','marks','last-available-no-per-session-freshness-certification', + 'returnUnit','fraction','variance','sample-n-minus-one','riskFreeConversion','annual-rate-divided-by-periods-per-year', + 'downside','full-series-rms-relative-to-risk-free','partialPeriods','visible-excluded-from-periodic-statistics', + 'drawdown','session-end-and-terminal-sampled','exposureBasis','elapsed-calendar-time', + 'cagrBasis','elapsed-calendar-days-365','zeroTerminalCagr','negative-one-for-positive-elapsed-time'); + IF (experiment.id IS NOT NULL AND NOT experiment.cancel_requested AND experiment.validation_phase=phase + AND run.id IS NOT NULL AND run.status='completed' AND NOT run.cancel_requested AND run.backtest_id=experiment.backtest_id + AND candidate->>'index'=run.trial_index::text AND candidate->>'trialKey'=run.trial_key + AND run.request_snapshot=expected_request AND run.dataset_hash=expected_request->>'datasetHash' + AND result->>'kind'='canonical-result/v1' AND result->>'status'='completed' + AND result->>'financialEngine'='rust' AND result->>'strategyExecution'='typescript-retained-builtin/v1' + AND result->>'runId'=run.id::text AND result->>'backtestId'=run.backtest_id::text AND result->'request'=expected_request + AND result#>'{financial,identity}'=jsonb_build_object('version',1,'sessionId',run.id::text,'datasetHash',run.dataset_hash) + AND result#>'{financial,policy}'=expected_request->'policy' + AND result#>'{analytics,version}'='1'::jsonb AND result#>'{analytics,policy}'=analysis_policy + AND jsonb_typeof(result#>'{analytics,metrics}')='object' AND jsonb_typeof(result#>'{analytics,unavailable}')='object' + AND jsonb_typeof(result#>'{financial,limitations}')='array' AND jsonb_typeof(result#>'{financial,modelLimitations}')='array') IS NOT TRUE THEN + RAISE EXCEPTION 'Validation evidence requires the exact complete uncancelled canonical phase result and policy' USING ERRCODE='23514'; + END IF; + FOR metric IN SELECT * FROM jsonb_each(result#>'{analytics,metrics}') LOOP + IF jsonb_typeof(metric.value) NOT IN ('null','number') OR (metric.value='null'::jsonb) IS DISTINCT FROM (result#>'{analytics,unavailable}' ? metric.key) THEN + RAISE EXCEPTION 'Validation metric availability must remain truthful' USING ERRCODE='23514'; + END IF; + END LOOP; + expected:=jsonb_build_object('phase',phase,'experimentId',phase_experiment_id::text,'runId',run.id::text, + 'sourceCandidateIndex',source_index,'trialKey',candidate->'trialKey','parameters',candidate->'parameters', + 'datasetHash',run.dataset_hash,'requestHash',item->'requestHash','economicHash',item->'economicHash', + '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}')); + IF (item=expected AND item->>'requestHash' ~ '^[a-f0-9]{64}$' AND item->>'economicHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN + RAISE EXCEPTION 'Validation evidence must copy the precise retained result facts' USING ERRCODE='23514'; + END IF; + IF phase='train' AND jsonb_typeof(result#>'{analytics,metrics,totalReturn}') IS DISTINCT FROM 'number' THEN + RAISE EXCEPTION 'Every training return must be a finite available number' USING ERRCODE='23514'; + END IF; + RETURN (result#>>'{analytics,metrics,totalReturn}')::numeric; +END $$; + +CREATE OR REPLACE FUNCTION protect_validation_evidence() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE document JSONB; candidate JSONB; item JSONB; idx INTEGER; winner_index INTEGER; best numeric; score numeric; + selected RECORD; approval RECORD; root research_experiments; phase TEXT; child_id UUID; +BEGIN + IF NEW.validation_manifest IS DISTINCT FROM OLD.validation_manifest OR NEW.validation_parent_id IS DISTINCT FROM OLD.validation_parent_id + OR NEW.validation_phase IS DISTINCT FROM OLD.validation_phase THEN + RAISE EXCEPTION 'Validation preparation and phase lineage are immutable' USING ERRCODE='23514'; + END IF; + IF OLD.validation_selection IS NOT NULL AND NEW.validation_selection IS DISTINCT FROM OLD.validation_selection THEN + RAISE EXCEPTION 'Validation selection is write once' USING ERRCODE='23514'; + END IF; + IF OLD.validation_report IS NOT NULL AND NEW.validation_report IS DISTINCT FROM OLD.validation_report THEN + RAISE EXCEPTION 'Validation report is write once' USING ERRCODE='23514'; + END IF; + IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL THEN + document:=NEW.validation_selection; + IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_report IS NULL + AND document->>'version'='chronological-validation-selection/v1' AND document->>'validationId'=NEW.id::text + AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash' ~ '^[a-f0-9]{64}$' + AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL + AND document->>'principal' IN ('operator','service') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$' + AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(document->'training')='array' + AND jsonb_array_length(document->'training')=jsonb_array_length(NEW.preview->'candidates') + AND (SELECT count(*) FROM runs WHERE experiment_id=NEW.id)=jsonb_array_length(NEW.preview->'candidates') + AND NOT EXISTS (SELECT 1 FROM research_experiments WHERE validation_parent_id=NEW.id) + AND document#>>'{holdoutExperimentIds,validation}' ~ '^[a-f0-9-]{36}$' + AND document#>>'{holdoutExperimentIds,test}' ~ '^[a-f0-9-]{36}$' + AND document#>>'{holdoutExperimentIds,validation}'<>document#>>'{holdoutExperimentIds,test}') IS NOT TRUE THEN + RAISE EXCEPTION 'Selection requires a complete uncancelled training experiment and immutable receipt' USING ERRCODE='23514'; + END IF; + idx:=0; best:=NULL; winner_index:=NULL; + FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP + score:=assert_validation_evidence(item,NEW.id,'train',idx); + candidate:=NEW.preview->'candidates'->idx; + IF item->>'trialKey' IS DISTINCT FROM candidate->>'trialKey' THEN RAISE EXCEPTION 'Training evidence must follow original candidate order' USING ERRCODE='23514'; END IF; + IF best IS NULL OR score>best THEN best:=score; winner_index:=idx; END IF; + idx:=idx+1; + END LOOP; + IF document->'winner' IS DISTINCT FROM NEW.preview->'candidates'->winner_index THEN + RAISE EXCEPTION 'Winner must maximize training return with original-index tie break' USING ERRCODE='23514'; + END IF; + SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id + WHERE v.id::text=NEW.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s; + SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; + IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' + AND document->>'reviewId'=approval.id::text AND NEW.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN + RAISE EXCEPTION 'New holdouts require current approval of their original version' USING ERRCODE='23514'; + END IF; + END IF; + IF OLD.validation_report IS NULL AND NEW.validation_report IS NOT NULL THEN + document:=NEW.validation_report; + IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_selection IS NOT NULL + AND document->>'version'='chronological-validation-report/v1' AND document->>'validationId'=NEW.id::text + AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash'=OLD.validation_selection->>'selectionHash' + AND document->>'reportHash' ~ '^[a-f0-9]{64}$' AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL + AND document->>'principal' IN ('operator','service') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$' + AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->'training'=OLD.validation_selection->'training' + AND document->>'reset'='initial-capital-empty-positions' AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN + RAISE EXCEPTION 'Report requires exact frozen selection and independent reset evidence' USING ERRCODE='23514'; + END IF; + idx:=0; + FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP + PERFORM assert_validation_evidence(item,NEW.id,'train',idx); idx:=idx+1; + END LOOP; + FOREACH phase IN ARRAY ARRAY['validation','test'] LOOP + child_id:=(OLD.validation_selection#>>ARRAY['holdoutExperimentIds',phase])::uuid; + IF NOT EXISTS (SELECT 1 FROM research_experiments WHERE id=child_id AND validation_parent_id=NEW.id AND validation_phase=phase AND NOT cancel_requested) + OR (SELECT count(*) FROM runs WHERE experiment_id=child_id)<>1 THEN + RAISE EXCEPTION 'Report requires each exact complete holdout child' USING ERRCODE='23514'; + END IF; + PERFORM assert_validation_evidence(document->phase,child_id,phase,(OLD.validation_selection#>>'{winner,index}')::integer); + END LOOP; + END IF; + RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS validation_evidence_identity ON research_experiments; +CREATE TRIGGER validation_evidence_identity BEFORE UPDATE ON research_experiments FOR EACH ROW EXECUTE FUNCTION protect_validation_evidence(); + +CREATE OR REPLACE FUNCTION require_complete_validation_admission() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE current research_experiments; child research_experiments; candidate JSONB; phase TEXT; +BEGIN + SELECT * INTO current FROM research_experiments WHERE id=NEW.id; + IF current.validation_phase IS NULL THEN RETURN NULL; END IF; + IF (SELECT count(*) FROM runs WHERE experiment_id=current.id)<>jsonb_array_length(current.preview->'candidates') + OR EXISTS (SELECT 1 FROM runs r LEFT JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=current.id AND d.run_id IS NULL) THEN + RAISE EXCEPTION 'Validation admission requires its complete exact run and durable outbox set' USING ERRCODE='23514'; + END IF; + IF current.validation_phase='train' AND current.validation_selection IS NOT NULL THEN + IF (SELECT count(*) FROM research_experiments WHERE validation_parent_id=current.id)<>2 THEN + RAISE EXCEPTION 'Selection must atomically admit both holdout experiments' USING ERRCODE='23514'; + END IF; + FOREACH phase IN ARRAY ARRAY['validation','test'] LOOP + SELECT * INTO child FROM research_experiments WHERE id::text=current.validation_selection#>>ARRAY['holdoutExperimentIds',phase] + AND validation_parent_id=current.id AND validation_phase=phase; + IF child.id IS NULL OR (SELECT count(*) FROM runs WHERE experiment_id=child.id)<>1 + OR NOT EXISTS (SELECT 1 FROM runs r JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=child.id) THEN + RAISE EXCEPTION 'Selection must atomically retain each singleton holdout and durable outbox' USING ERRCODE='23514'; + END IF; + END LOOP; + END IF; + RETURN NULL; +END $$; +DROP TRIGGER IF EXISTS validation_admission_complete ON research_experiments; +CREATE CONSTRAINT TRIGGER validation_admission_complete AFTER INSERT OR UPDATE OF validation_selection ON research_experiments + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_validation_admission(); + +CREATE OR REPLACE FUNCTION cascade_validation_cancellation() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE child RECORD; +BEGIN + -- UPDATE already owns this row. Never lock upward to the parent from this trigger. + IF NEW.validation_phase='train' AND NEW.cancel_requested AND NOT OLD.cancel_requested THEN + FOR child IN SELECT id FROM research_experiments WHERE validation_parent_id=NEW.id ORDER BY CASE validation_phase WHEN 'validation' THEN 0 ELSE 1 END LOOP + UPDATE research_experiments SET cancel_requested=TRUE WHERE id=child.id; + END LOOP; + UPDATE runs SET cancel_requested=TRUE,status=CASE WHEN status='pending' THEN 'cancelled'::run_status ELSE status END, + completed_at=CASE WHEN status='pending' THEN NOW() ELSE completed_at END,updated_at=NOW() + WHERE (experiment_id=NEW.id OR experiment_id IN (SELECT id FROM research_experiments WHERE validation_parent_id=NEW.id)) AND status IN ('pending','running','paused'); + END IF; + RETURN NULL; +END $$; +DROP TRIGGER IF EXISTS validation_cancellation_cascade ON research_experiments; +CREATE TRIGGER validation_cancellation_cascade AFTER UPDATE OF cancel_requested ON research_experiments FOR EACH ROW EXECUTE FUNCTION cascade_validation_cancellation(); diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 564947e4..792fdae0 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -**First twenty-eight waves committed; R08 chronological preflight is validated and awaits commit.** Retry work is committed as `b373410`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The new workbench input check verifies exact train/validation/test slices, warmup and independent account clocks. Full R08 remains incomplete until durable phase execution, selection and reports; R05/R07 remain partial. Performance work stays paused. +**First twenty-nine waves committed; durable R08 chronological validation is validated and awaits commit.** Preflight is committed as `67ab30c`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The workbench now runs training, freezes its winner, evaluates validation/test and reopens immutable reports using existing durable experiments and Rust accounting. Full R08 remains partial for multi-window walk-forward and cost sensitivity; R05/R07 remain partial. Performance work stays paused. -Authorization update: the owner requested “commit and continue”. R06 is complete and committed as `b373410`; R08 now starts with an explicitly partial, read-only preflight foundation. No performance work, new-wave commits/pushes/PRs, SQL admission changes, candidate execution or trading/default activation are included. +Authorization update: the owner requested “commit and continue”. R08 preflight is accepted and committed as `67ab30c`; the next component implements a complete single chronological recipe through the existing engine and durable runner. No performance work, new-wave commits/pushes/PRs, candidate execution or trading/default activation are included. ## Strategy and review outcome @@ -627,3 +627,17 @@ All gates passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 786 i The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; worktrees/logs remain under `/tmp/stock-bot-wave29.kK85O1/`. Existing warnings remain; development data/services were untouched. Next after acceptance/commit: **R08 immutable recipe and staged admission**. Freeze windows and selection rules before execution, retain all training candidates, then atomically freeze the winner before validation/test admission. Extend existing one-dataset admission/retry assumptions explicitly; do not add another scheduler. R09 stays blocked, and performance/default/trading/AI activation remains excluded. No new-wave commit, push or PR occurred. + +## Thirtieth wave handoff — 2026-10-24 + +The accepted preflight is committed as `67ab30c`. The next R08 component is implemented, independently reviewed and validated, with changes left uncommitted. Full R08 remains in progress. Thirty-eight implementation/test files add a complete single train/validation/test workflow through the existing durable runner and authoritative Rust engine. + +SQL24 extends `research_experiments`: the training root owns the immutable prepared manifest, write-once selection and final report; validation/test are ordinary singleton children. Existing SQL22 run admission and SQL23 retries remain unchanged. The ordinary manifest guard is mechanically extracted without semantic changes. SQL verifies exact source slices, availability, metadata, calendar clocks, candidate completeness and copied result facts; deferred checks prevent partial training or holdout admission. Root cancellation propagates through old/new APIs and direct SQL without upward trigger locks. + +The web explicitly submits training, freezes the complete verified winner while atomically admitting both heldouts, and saves an immutable report. GET never advances work. Selection maximizes finite comparable training total return with original-index tie breaking; all training candidates are required. Full existing native-result/analytics verification precedes irreversible evidence. Accepted receipts survive subsequent eligibility changes; new holdouts require current original-version approval/build, while historical finalization works after archival/revocation. Failed phase trials reuse existing retry/history controls. Distinct phase names, reset assumptions, sample counts, unavailable reasons and precise report/run identities remain visible. + +All gates passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 825 integration and 150 Rust tests; four existing manual Rust tests ignored); PostgreSQL/Redis (205 tests /1773 assertions); Chromium (13 workflows /357 assertions); strict new-test types, scoped lint, formatting and whitespace checks. New native/database tests cover atomic rollback, receipt conflicts/races, direct SQL tampering, migration preservation, failed phase retries, cancellation races and unchanged training selection after modifying future test prices. The real browser completes the full lifecycle, finalizes after archival and reopens the exact report. Source hashes, overlays, independent review and logs are recorded in `manifest.json` → `thirtieth_wave_validation`. + +The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; logs/worktrees and the exact 38-file archive remain under `/tmp/stock-bot-wave30.K6IDyj/`. Initial manual browser setup hit the fixture network guard because a local VITE override was present; the corrected same-origin build passed both focused and final suites. Existing bundle-size/Rust warnings remain; development data/services were untouched. + +Next after acceptance/commit: finish R08 with repeated nonoverlapping walk-forward windows and bounded cost sensitivity, reusing these durable recipe/experiment paths. Keep independent reset-account reporting explicit; do not imply a continuous portfolio or untouched external holdout. R09 remains blocked; R05/R07 and AI/default/trading gates are unchanged. No performance work, candidate execution, new scheduler/simulator, new-wave commit, push or PR occurred. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 7d6a1d09..b6f9dc64 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First twenty-eight waves committed; R08 chronological preflight is validated and awaits commit.** Retry work is committed as `b373410`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The new workbench input check verifies exact train/validation/test slices, warmup and independent account clocks. Full R08 remains incomplete until durable phase execution, selection and reports; R05/R07 remain partial. Performance work stays paused. +**First twenty-nine waves committed; durable R08 chronological validation is validated and awaits commit.** Preflight is committed as `67ab30c`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The workbench now runs training, freezes its winner, evaluates validation/test and reopens immutable reports using existing durable experiments and Rust accounting. Full R08 remains partial for multi-window walk-forward and cost sensitivity; R05/R07 remain partial. Performance work stays paused. ## One source of truth @@ -79,7 +79,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M | | [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M | | [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (component) | R06 component API pinned; release after integration, ADR-006 | W04 | Full-stack research product / M | -| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / in_progress (preflight validated) | R06, ADR-006 | — | Quantitative research integrity / M | +| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / in_progress (durable recipe validated) | R06, ADR-006 | — | Quantitative research integrity / M | | [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M | | [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M | | [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M | @@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. -The R06/R07 retained-input components are committed as `6f64ef6`. Current work completes failed-trial retry with preserved diagnostics and attempt fencing plus focused UI controls. Full R05 stays partial; R08/A01/S06 are not released before accepted integration and their own approval gates. Provider preparation is independent of sweeps over retained data. Performance and multi-asset/default/paper activation remain excluded. +R06 is complete and committed as `b373410`; R08 preflight is committed as `67ab30c`. The durable single-recipe R08 component is independently reviewed and fully validated, awaiting commit. Full R08 still needs repeated walk-forward windows and cost sensitivity. R05/R07 remain partial; R09 and AI/default/trading activation retain their gates. Provider preparation is independent of experiments over retained data, and performance work remains paused. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 59cf9358..097ad061 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,14 +1,14 @@ { "schema_version": 1, - "plan_revision": "2026-10-24.62", + "plan_revision": "2026-10-24.64", "repository_base": "b7aeca4", - "plan_status": "twenty_ninth_wave_validated_awaiting_commit", + "plan_status": "thirtieth_wave_validated_awaiting_commit", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue after validated R06 retry handoff recommended R08 chronological validation; retry work committed b373410", + "authorized_by": "User: commit and continue; accepted chronological preflight committed 67ab30cb7a578591262cb0218fa9f6a135924c7f", "tasks": ["R08"], "permissions": [ - "R08 preflight foundation: verified chronological dataset windows, prepared reset-account requests and input-only web preview; isolated implementation/review and full validation" + "R08 durable single chronological recipe: immutable source and phase datasets, ordinary training experiment and fixed-winner holdout children, write-once selection/report, explicit web workflow and full regression gates" ], "excluded": [ "performance_profiling_or_optimization", @@ -24,9 +24,8 @@ "AI_execution_or_credentials", "historical_binary_provisioning", "cross_experiment_ranking", - "durable_validation_admission", - "validation_selection_or_performance_claims", - "validation_report_persistence" + "multi_window_walk_forward_and_cost_sensitivity_execution", + "strategy_performance_conclusions" ], "pending_policy_decisions": [ "ADR-007", @@ -1445,32 +1444,34 @@ "blocker": null, "release_gates": [], "integration_state": "component_validated_uncommitted", - "integration_base": "b373410320e987ddce1ee8dd5e8a691cf183d527", + "integration_base": "67ab30cb7a578591262cb0218fa9f6a135924c7f", "worktree": "/home/boki/repos/stock-bot", - "execution_component": "Chronological validation preflight and exact dataset slicing", + "execution_component": "Durable single train/fixed-winner validation/test recipe with immutable report", "component_exclusions": [ - "durable experiment/phase admission and immutable selection/report", - "walk-forward aggregation and cost-sensitivity execution" + "multi-window walk-forward/reset-series aggregation", + "cost-sensitivity execution", + "findings/regime evidence integration" ], "reviewed_by": "/root/r04_review", - "verification_reference": "ROADMAP.md#twenty-ninth-wave-handoff--2026-10-24", - "review_notes": "Preflight foundation independently reviewed and all integrated gates passed. Full task stays in progress: no durable recipe/admission, selection, report, walk-forward or cost-sensitivity execution yet.", + "verification_reference": "ROADMAP.md#thirtieth-wave-handoff--2026-10-24", + "review_notes": "Single durable chronological recipe independently accepted and all integrated gates passed. Full R08 stays in progress for multi-window walk-forward/reset-series aggregation and cost sensitivity; R09 remains blocked.", "implementation_slices": [ { "owner": "/root/r12_backend", - "worktree": "/tmp/stock-bot-wave29.kK85O1/backend", - "scope": "Exact v2 slice export, prepared phase requests and extracted unchanged risk clock, authenticated preview API and pure/API/PostgreSQL regressions" + "worktree": "/tmp/stock-bot-wave30.K6IDyj/backend", + "scope": "SQL24, validation service/routes, ordinary experiment compatibility, new pure/API/PostgreSQL regressions" }, { "owner": "/root/r12_frontend", - "worktree": "/tmp/stock-bot-wave29.kK85O1/frontend", - "scope": "Explicit UTC preflight panel/client and interaction tests; ordinary sweep remains distinct" + "worktree": "/tmp/stock-bot-wave30.K6IDyj/frontend", + "scope": "Explicit training/selection/report UI, saved validations and focused interaction tests; symmetric submission ownership" }, { "owner": "/root", - "scope": "Shared DTO/export, native reset/suffix regression, actual browser no-write workflow, full integration and planning" + "scope": "Shared DTO, migration registry and old fixture chains, web route composition, native/browser workflow, full gates and planning" } - ] + ], + "partial_commit": "67ab30cb7a578591262cb0218fa9f6a135924c7f" }, { "id": "R09", @@ -6806,7 +6807,7 @@ "Future fixed selection protocol: every train candidate must have a comparable finite totalReturn; maximize then tie by original candidate.index. Validation and test assess only that frozen winner." ], "twenty_ninth_wave_validation": { - "state": "component_validated_uncommitted", + "state": "component_committed", "scope": "R08 read-only chronological preflight foundation; full R08 remains in_progress and R09 blocked", "integration_base": "b373410320e987ddce1ee8dd5e8a691cf183d527", "log_directory": "/tmp/stock-bot-wave29.kK85O1", @@ -6885,6 +6886,137 @@ "No performance measurements/optimization, new scheduler/simulator, candidate code, multi-asset/default/paper/live/AI activation, new-wave commit, push or PR. Chromium only; existing bundle-size/Rust warnings remain." ], "cleanup": "Both exact --rm disposable PostgreSQL/Redis containers stopped successfully. Nineteen source/test files archived and hashed; worktrees and logs retained. Development/production services and data untouched.", - "next": "After acceptance/commit, continue R08 with immutable experiment-owned recipe and a coordinated guarded admission branch. Freeze all windows/source/phase inputs and selection policy before training; commit the write-once complete-training winner before admitting the same winner to validation/test. Extend existing one-dataset admission/retry/result assumptions explicitly, preserve normal experiments and recovery, and persist immutable evidence. Do not call preflight OOS validation or release R09 prematurely; performance remains paused." + "next": "After acceptance/commit, continue R08 with immutable experiment-owned recipe and a coordinated guarded admission branch. Freeze all windows/source/phase inputs and selection policy before training; commit the write-once complete-training winner before admitting the same winner to validation/test. Extend existing one-dataset admission/retry/result assumptions explicitly, preserve normal experiments and recovery, and persist immutable evidence. Do not call preflight OOS validation or release R09 prematurely; performance remains paused.", + "committed_as": "67ab30cb7a578591262cb0218fa9f6a135924c7f", + "completed_commit": "67ab30cb7a578591262cb0218fa9f6a135924c7f" + }, + "thirtieth_wave": ["R08"], + "thirtieth_wave_base": "67ab30cb7a578591262cb0218fa9f6a135924c7f", + "thirtieth_wave_notes": [ + "Use training research_experiments row as immutable recipe root; two ordinary singleton child experiments reuse runs/outbox/retry. No run schema or financial-engine change.", + "Explicit submit, select-and-admit and finalize operations; read-only GET; full existing financial-result verification before irreversible evidence.", + "All training candidates must complete with comparable finite scores; deterministic total-return maximum then original candidate-index tie break. Same winner for validation/test; independent reset accounts.", + "Freeze write-once selection/report with atomic child admission and accepted receipt replay before current eligibility. Historical finalization does not need current execution approval.", + "Root cancellation propagates through both new and old endpoints and SQL guard; no future holdout admission after cancellation.", + "R08 remains partial for multiple walk-forward windows and cost sensitivity. R09 and performance/default/trading/AI gates unchanged." + ], + "thirtieth_wave_validation": { + "state": "component_validated_uncommitted", + "scope": "R08 durable single train/fixed-winner validation/test recipe and immutable report; full R08 remains in_progress and R09 blocked", + "integration_base": "67ab30cb7a578591262cb0218fa9f6a135924c7f", + "log_directory": "/tmp/stock-bot-wave30.K6IDyj", + "source_archive": "/tmp/stock-bot-wave30.K6IDyj/validated-source.tar.gz", + "source_archive_sha256": "f2f0f6e6b462263198cf0bdbf3d8d20dfa30c3338a9425e23e97c166078b3117", + "source_files": { + "apps/stock/config/src/contracts/chronological-validation.ts": "1ec526f04d27073c6c459009e4a17a16f089bf8ffddf66e603a4075eed3b0848", + "apps/stock/web-api/src/migrations/migration-runner.ts": "d4cb8b0f07b1ac394aafb4f60a8185fe2e43d13112ecc64132d7406243f051a2", + "apps/stock/web-api/src/routes/experiments.routes.ts": "1f6d02774e54e470959a94f82ce9196c0e4bdbdf34d0914f8bf6cf64bc43420c", + "apps/stock/web-api/src/services/chronological-validation.service.ts": "1d0797b893edf382fa1b3987ee3b680b2b574743c0934c19a9bde418556416ed", + "apps/stock/web-api/src/services/experiments.service.ts": "a17132c7ae7e7fe73c4a814802995888a4d1e7dd48233cdfd81bd498d0be5ce9", + "apps/stock/web-api/src/services/validation-evidence.ts": "fa1d04ab56ae66a0c11001ead4e75e98e011193a580702ffe992cf8e0075cf11", + "apps/stock/web-app/src/app/App.tsx": "2f947e9870924422534dbdf3d7703999974cc02f3c6bd3e323f5a5e1c0102c7c", + "apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx": "ef968704864118b053c3730cbb1ec13bdcc36dcb0e1ba73648da8ebb9389ee4f", + "apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx": "c0d7d944b84a80a8c49f6d4bca0ee87543cf39b627a7ee68d3d6a3a76a684f3b", + "apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx": "c7a1288e225bca65a13e533ece08c5e67e34ccce54af515e1c3b3ef3d9884a31", + "apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx": "4bbb2763742f23a684873318d4756d22dfbcf5dac153c2167707f34b9c4c98ec", + "apps/stock/web-app/src/features/experiments/components/SavedChronologicalValidations.tsx": "2aefdb987f98281a942779c92576abe6c793a673c2aa1957264b583921dfc2f8", + "apps/stock/web-app/src/features/experiments/components/ValidationEvidence.tsx": "597e5b09c67ae5063f684155506f9fff66f51d197eedf33edafbe150a7762e0d", + "apps/stock/web-app/src/features/experiments/index.ts": "2e0eb7a33673aca7b64489e8f9529ff2d0444bda5010c21ebcd3161f043e5461", + "apps/stock/web-app/src/features/experiments/services/chronologicalValidationApi.ts": "266ea263386a1be777fa5edc13286f1beaf2e3388fc0ee22791a15dce3880077", + "apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts": "b35af5f939805eb9df65bbe4f6adad07550f8997700ca702d9af96b943d50809", + "apps/stock/web-app/src/features/experiments/services/experimentApi.ts": "6c9049ff40516f0a703f6bad02c1a8c5e1bedfb173abde48a9e1a58f01eafd27", + "database/postgres/init/24-chronological-validation.sql": "b90b3b23ecec5b753a6d091fd34af988fc8f2292c22aabb1b3ad6c75d8410f6d", + "test/e2e/fixture.ts": "fc95265629b7f11b58c0ada55d110a4434b4c899973ca7e7ae09b2428195f4f4", + "test/e2e/workbench.test.ts": "9011a4add29fcd05f80d1102dd9ac6ea5d80ed618d9641f8f20f5b7b87fee815", + "test/integration/chronological-validation-durable-api.test.ts": "61ce6a165a61d55e912168eb3d27cb675a9f15a5a26f50b99fc051e7be222018", + "test/integration/chronological-validation-durable-ui.test.tsx": "45c8d1a5740896c8e0f953f1df7e30a876235faffceb6506db256f6402d20e10", + "test/integration/chronological-validation-durable.test.ts": "bbba830783dc0e09bae54b9f95dd31a6cb7959ddbd3c2876aea11b6c934446c1", + "test/integration/chronological-validation-ui.test.tsx": "e7c4bfc7009d010569a3ed3d0fe1fa436bfc8e12c7032ff0a89b989266299531", + "test/postgres/canonical-durable-backtest.test.ts": "8bc3fce8749f712169205daa8b9b3f5183df60915017af27c8e1b2f3c976773b", + "test/postgres/canonical-research.test.ts": "8f049d38aa21a108725b8aa162fac9dac2fa4b061b17a05e5d866288eec09ddc", + "test/postgres/catalog-backtest-drafts.test.ts": "6ac07c481bbeeeabf922a5eacadafa0488392020da76d7a76c77fdebb0d836fd", + "test/postgres/chronological-validation-durable.test.ts": "6f54c297db2dff9c2ea2a92065674a976a00bf91cde1cdf38cbbb4e75c39386f", + "test/postgres/chronological-validation.test.ts": "ccaa4b41ede6b4a3b595622cede1ecad90ed660cc58ad03dd643a4e829ed68fb", + "test/postgres/dataset-catalog.test.ts": "e0fb89186cd73f6381fa49ca6b0218eb8d08d2b4677fb5f51be0adf620419b1e", + "test/postgres/durable-backtest.test.ts": "ec55ecd29abf352654bde4b4aaf668d7a962be808452c5110bd279c145f0e187", + "test/postgres/experiment-retries.test.ts": "4d3fabb6ffa22cb7ddb7719e84d0537281e61ae673a79ef6f44def3d1f7e6fb1", + "test/postgres/experiments.test.ts": "718bf826bb712e0e5de2d63fc915f6a1977f02ca56055e4174e5194f4aaf9f42", + "test/postgres/migration-runner.test.ts": "b58107cedee0530620bdce2f6d1b016d37cda67073a4ed958e03bb7442b385f3", + "test/postgres/research-retention.test.ts": "fdb9c1341b37fe78b7819f5293d54d5c5856ef7b225be300bd3c5bceef10af05", + "test/postgres/research-runtime-isolation.test.ts": "9b19c0f303c09b05a0c4cbe3387a9573de0432f926f2fe4efdbf6b2598a0a86a", + "test/postgres/research-workspace.test.ts": "5895749d199016497f0bebfa869921f4eadb79ecb3760dd64b6bc713d08dea58", + "test/postgres/run-reproduction.test.ts": "afe9c571de64cfd07a0bcc1fd5bb4ae2312b489c8ecf9d27cdd74aa243d05e73" + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave30.K6IDyj/check.log", + "outcome": "All repository gates passed: build, source/contracts types, secrets, lint; 93 tooling, 43 utility, 44 calculation, 825 integration and 150 Rust tests. Zero failures; four existing manual Rust tests ignored." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:postgres", + "log": "/tmp/stock-bot-wave30.K6IDyj/postgres.log", + "outcome": "205 tests /1773 assertions passed across 23 files, including 11 new chronological validation tests." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:e2e", + "log": "/tmp/stock-bot-wave30.K6IDyj/e2e.log", + "outcome": "13 Chromium workflows /357 assertions passed. Real native training, explicit winner/heldout admission, finalization after archival, exact receipts, report reopening and child experiment navigation." + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave30.K6IDyj/integrated-tests-tsconfig.json --noEmit", + "log": "/tmp/stock-bot-wave30.K6IDyj/integrated-test-types-final.log", + "outcome": "Strict types passed for all new durable pure/API/UI/PostgreSQL tests plus updated preflight UI and browser fixture/workflow." + }, + { + "command": "bunx eslint ", + "log": "/tmp/stock-bot-wave30.K6IDyj/integrated-test-lint.log", + "outcome": "Scoped test lint passed; source lint passed full gate." + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "log": "/tmp/stock-bot-wave30.K6IDyj/native-release.log", + "outcome": "Release addon restored before final PostgreSQL/Chromium suites; SHA256 unchanged." + }, + { + "command": "bunx prettier --check <38 source/test files excluding SQL> docs/development/backlog/manifest.json; git diff --check; manifest references/DAG/hash verification", + "log": "/tmp/stock-bot-wave30.K6IDyj/final-format-check.log", + "outcome": "Formatting, whitespace, task references/DAG and exact source/archive verification passed. Final formatter delta preserves identical whitespace-stripped source." + } + ], + "native_release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "reviews": [ + { + "owner": "/root/r04_review", + "scope": "Backend eight-file final overlay; exact source/SQL contracts and adversarial tests", + "outcome": "ACCEPT, all 8 hashes verified. Independently ran 6 pure/HTTP tests /86 assertions and reviewed author 11 native/PostgreSQL tests /118 assertions. Ordinary SQL22 source guard extraction mechanically identical; run/retry guards unchanged. Root final formatting changes only whitespace in two backend files; whitespace-stripped source exactly matches the accepted overlay.", + "archive_sha256": "cd82011090d0206e8757f75cfe7b736dad3cbc753f908cc246b7a2aa68095300" + }, + { + "owner": "/root/r04_review", + "scope": "Frontend eleven-file final overlay", + "outcome": "ACCEPT, all 11 hashes verified. Independently ran 66 UI tests /285 assertions; author combined 235 UI tests /1151 assertions. Reviewed intent ownership, ambiguous receipts, retained evidence consistency and synchronous refresh/action fencing.", + "archive_sha256": "cc4c5dbd58a4905ddf980d65ad266feb7e58d3bee0969b995bbd28412a22709d" + } + ], + "behaviors": [ + "Atomic retention of three exact slices and training grid; only training runs admitted initially. Selection and two ordinary singleton holdout experiments/runs/outbox commit together.", + "Every complete comparable training result is verified through existing canonical financial/analytics reader; finite total-return maximum and original-index tie break. Training evidence retains original candidate order. Validation/test use exactly the same fixed winner.", + "Immutable source recipe, phase lineage, selection and report; SQL independently verifies source bars/availability/metadata/account clocks, candidate completeness and copied result facts. No second financial engine.", + "Accepted receipts replay before current eligibility; fresh holdout execution verifies original retained build/version and current approval. Historical report finalization works after archive/revocation.", + "Old/new root cancellation and direct SQL propagate to child phases; race tests reject or cancel all admitted work. Failed phase trials reuse existing retry receipts and fencing.", + "Single bounded web lifecycle with exact ambiguous-intent retry, independent reset-account results, truthful unavailable metrics/sample counts, saved report reopening and existing phase retry/history links." + ], + "limitations": [ + "Only one explicit train/validation/test recipe and deterministic unfitted retained built-ins with zero label horizon. Multi-window walk-forward/reset-series aggregation and cost sensitivity remain R08 acceptance work; R09 remains blocked and R05/R07 remain partial.", + "Selection is training-only within this workflow; no guarantee that source data has never been inspected in other research. Saved evidence does not establish strategy quality or statistical adequacy.", + "Prepared preview identity keeps execution=preview-only unchanged; durable stage and immutable action evidence are separate. Each phase is an independent reset account; no stitched portfolio curve.", + "No performance/profiling/benchmark work, new scheduler/simulator, candidate execution, multi-asset/default/paper/live/AI activation, new-wave commit, push or PR. Chromium only; existing build warnings remain." + ], + "validation_notes": [ + "An initial manually built browser fixture used the local VITE API override; its network guard rejected login. Rebuilding with explicit same-origin VITE_API_BASE_URL fixed the setup; both focused and final complete browser suites passed. No application change or test retry hid a source failure." + ], + "cleanup": "Both exact disposable PostgreSQL/Redis containers stopped successfully after all suites completed. 38 source/test files archived and hashed; worktrees/logs retained. Development/production services and data untouched.", + "next": "Accept/commit this durable single-recipe component, then finish R08 with explicit repeated nonoverlapping walk-forward windows and bounded cost sensitivity through the existing recipe/experiment paths. Preserve immutable per-window winners and separate reset-account reports; avoid a general workflow scheduler. Keep performance, candidate/AI execution and default/trading activation gated." } } diff --git a/docs/development/backlog/tasks/R08.md b/docs/development/backlog/tasks/R08.md index 97e63901..44f54291 100644 --- a/docs/development/backlog/tasks/R08.md +++ b/docs/development/backlog/tasks/R08.md @@ -84,3 +84,17 @@ The first component is independently reviewed and `component_validated_uncommitt Full repository checks passed (786 integration /150 Rust tests), PostgreSQL (194 tests /1655 assertions), Chromium (12 workflows /306 assertions), strict test types, lint and formatting. Native regressions prove independent initial cash/positions/state, no warmup orders/fills and earlier-phase invariance to a changed test suffix. Browser/database tests prove preview makes no retained-data/job/template writes. Hashes and logs: `manifest.json` → `twenty_ninth_wave_validation`. Next: immutable experiment-owned recipe and guarded staged admission, with all candidate training evidence complete before a write-once winner selection and validation/test admission. Existing ordinary experiment/retry behavior must remain intact. This preflight does not satisfy immutable report reopening, holdout access history, walk-forward aggregation or cost-sensitivity execution; R09 remains blocked. + +## Authorized durable single-recipe component — 2026-10-24 + +Preflight is accepted and committed as `67ab30c`. Extend the training experiment with the immutable preparation manifest and write-once selection/report. Validation and test are ordinary singleton child experiments linked to the root, preserving existing run, outbox and retry contracts. Reuse full `getRunResults` financial/analytics validation before sealing evidence; compact UI summaries are insufficient. + +Explicit receipt-bearing submit, select-and-admit and finalize endpoints; GET remains read-only. Retain all three slices atomically with training admission. All training candidates must complete and be comparable before selection. Freeze selection and both same-winner heldout experiments/runs/outbox in one transaction. Each phase resets capital/state as declared. Accepted receipt replay precedes current eligibility checks; current original approval/build gates new execution only. Finalization assembles verified historical evidence even after archival/build changes. Root cancellation propagates through existing cancellation routes and SQL guards. + +The web supports saved validations, training admission, selection, heldout progress and report reopen; ambiguous requests retain exact intent/key and exclude conflicting editor actions. Child experiment links reuse existing retry/history UI. SQL guards protect recipe lineage, phase linkage, candidate completeness, selection and report immutability. Test native full lifecycle, prefix independence, all-candidate failures, atomic rollback, concurrent receipts/cancellation, upgrade preservation and browser recovery. No new scheduler, simulator, run schema, AI/candidate activation or performance work. Multi-window walk-forward/reset-series aggregation and cost sensitivity remain outstanding after this component. + +### Validated durable handoff + +The single-recipe component is independently accepted and `component_validated_uncommitted`. Shared Rust economics, ordinary runs/outbox, SQL22/23 retry semantics and original evidence are preserved. All repository gates pass (825 integration /150 Rust tests), PostgreSQL/Redis 205 tests /1773 assertions, Chromium 13 workflows /357 assertions, strict test types and lint. Exact source hashes and review evidence: `manifest.json` → `thirtieth_wave_validation`. + +The UI supports the complete staged lifecycle and immutable report reopening. Native regressions prove unchanged training scores/winner after modifying only future test prices; malformed or missing candidate evidence cannot seal selection. Atomicity, SQL tamper, receipt/cancel races, migration preservation and phase retries pass. Full R08 remains incomplete for repeated walk-forward windows/reset-series aggregation and bounded cost sensitivity. R09 remains blocked. No performance or trading/default/AI activation occurred. diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index a867fcd1..27121334 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -295,6 +295,7 @@ export async function fixture(browser: Browser, native = false) { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index f0485ea8..4b39d752 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -5,7 +5,11 @@ import { canonicalResearchSettingsSchema, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; -import type { ChronologicalValidationPreview } from '@stock-bot/stock-config/chronological-validation'; +import type { + ChronologicalValidationActionResult, + ChronologicalValidationDetail, + ChronologicalValidationPreview, +} from '@stock-bot/stock-config/chronological-validation'; import type { ExperimentDetail, ExperimentPreview, @@ -127,7 +131,7 @@ test('chronological_preflight_checks_explicit_windows_without_admitting_or_savin .getByText('Exact chronological preview inputs and policies', { exact: true }) .click(); expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash); - await visible(f.page, /No datasets, experiments or runs are saved/); + await visible(f.page, /Previewing does not save datasets, experiments or runs/); for (const partition of preview.partitions) { await visible(f.page, partition.dataset.hash); expect(partition.requiredWarmup).toBe(4); @@ -166,6 +170,203 @@ test('chronological_preflight_checks_explicit_windows_without_admitting_or_savin } }); +test('durable_chronological_training_fixed_holdouts_report_and_reopen_browser', async () => { + const f = await fixture(true); + f.page.on('dialog', dialog => void dialog.accept()); + try { + const { dataset, recipe } = chronologicalDataset(); + await retainResearchDataset(f.pool, dataset); + const version = (await f.seedCatalog()).find( + item => item.package.program.strategyId === 'sma_crossover' + )!; + const approve = () => + f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', { + decision: 'approve', + reason: 'Reviewed chronological durable browser fixture', + }); + await approve(); + const definition = { + name: 'Chronological durable template', + strategy: 'catalog', + strategyVersionId: version.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: dataset.manifest.executionSeries.map(series => series.instrumentId), + startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: dataset.manifest.hash, + dataFrequency: dataset.manifest.series[0]!.interval, + canonical: canonicalSettings, + }, + }; + const backtest = await f.request('/api/v2/backtests', 'POST', { + ...definition, + autoStart: false, + }); + await f.login(); + await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`); + await f.page.getByLabel('Saved backtest').selectOption(backtest.id); + await f.page + .getByLabel('Experiment name', { exact: true }) + .fill('Frozen chronological research'); + await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}'); + for (const phase of ['Train', 'Validation', 'Test'] as const) { + const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test']; + for (const [label, value] of [ + ['warmup start', window.warmupStart], + ['trading start', window.tradeStart], + ['trading end', window.tradeEnd], + ] as const) { + await f.page + .getByLabel(`${phase} ${label} (UTC)`, { exact: true }) + .fill(new Date(value).toISOString()); + } + } + const previewing = f.page.waitForResponse(r => + r.url().endsWith('/api/v2/experiments/validation/preview') + ); + await f.page + .getByRole('button', { name: 'Preview chronological validation', exact: true }) + .click(); + const { preview } = (await (await previewing).json()) as { + preview: ChronologicalValidationPreview; + }; + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); + const submitting = f.page.waitForResponse( + r => r.request().method() === 'POST' && r.url().endsWith('/api/v2/experiments/validation') + ); + await f.page.getByRole('button', { name: 'Submit training runs', exact: true }).click(); + const accepted = await submitting; + expect(accepted.status()).toBe(202); + const { validation: admitted } = (await accepted.json()) as { + validation: ChronologicalValidationDetail; + }; + const endpoint = `/api/v2/experiments/validation/${admitted.id}`; + expect(accepted.headers().location).toBe(endpoint); + expect(admitted.preview).toEqual(preview); + expect(admitted.selection).toBeNull(); + expect(admitted.report).toBeNull(); + expect(admitted.phases.map(p => p.status)).toEqual([ + 'admitted', + 'not-admitted', + 'not-admitted', + ]); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); + expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(1); + await f.page.waitForURL(`${f.origin}/experiments/validation/${admitted.id}`); + await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click(); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2); + // Holdouts must retain the original recipe despite subsequent template edits and approval changes. + await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', { + ...definition, + name: 'Changed template', + initialCapital: 20000, + strategyParameters: { fastPeriod: 1, slowPeriod: 2 }, + }); + await approve(); + f.dispatcher.start(); + await until( + async () => + (await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count === + '2', + 'training finishes through native durable runner' + ); + await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click(); + const selecting = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/select`)); + await f.page + .getByRole('button', { name: 'Freeze selection and run holdouts', exact: true }) + .click(); + const selectionResponse = await selecting; + expect(selectionResponse.status()).toBe(202); + const selected = (await selectionResponse.json()) as ChronologicalValidationActionResult; + expect(selected.receipt.operation).toBe('select-and-admit-holdouts'); + expect(selected.receipt.id).toBe(selected.validation.selection!.id); + expect(selected.validation.selection!.training).toHaveLength(2); + expect(selected.validation.phases.map(p => p.status)).toEqual([ + 'admitted', + 'admitted', + 'admitted', + ]); + expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(3); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(4); + const winner = [...selected.validation.selection!.training].sort( + (a, b) => + b.metrics.totalReturn! - a.metrics.totalReturn! || + a.sourceCandidateIndex - b.sourceCandidateIndex + )[0]!; + expect(selected.validation.selection!.winner.index).toBe(winner.sourceCandidateIndex); + await until( + async () => + (await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count === + '4', + 'both same-winner heldouts finish through native runner' + ); + // Finalization saves historical evidence and does not require permission to start new work. + await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [backtest.id]); + await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]); + await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click(); + const finalizing = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/finalize`)); + await f.page.getByRole('button', { name: 'Save validation report', exact: true }).click(); + const reportResponse = await finalizing; + expect(reportResponse.status()).toBe(202); + const completed = (await reportResponse.json()) as ChronologicalValidationActionResult; + expect(completed.receipt.operation).toBe('finalize-report'); + expect(completed.receipt.id).toBe(completed.validation.report!.id); + expect(completed.validation.stage).toBe('reported'); + const report = completed.validation.report!; + expect(report.training).toEqual(selected.validation.selection!.training); + expect(report.reset).toBe('initial-capital-empty-positions'); + expect(report.validation.parameters).toEqual(selected.validation.selection!.winner.parameters); + expect(report.test.parameters).toEqual(report.validation.parameters); + expect(report.validation.sourceCandidateIndex).toBe(winner.sourceCandidateIndex); + expect(report.test.sourceCandidateIndex).toBe(winner.sourceCandidateIndex); + for (const evidence of [...report.training, report.validation, report.test]) { + const result = (await f.request( + `/api/v2/runs/${evidence.runId}/results` + )) as CanonicalRunResult; + expect(evidence.metrics).toEqual(result.analytics.metrics); + expect(evidence.unavailable).toEqual(result.analytics.unavailable); + expect(evidence.datasetHash).toBe(result.request.datasetHash); + expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe( + '10000.00000000' + ); + } + await visible(f.page, 'Execution complete · report saved'); + const read = (await f.request(endpoint)) as { validation: ChronologicalValidationDetail }; + expect(read.validation.report).toEqual(report); + const originalRuns = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows; + // Retrying the accepted selection after archival returns its same receipt, never finalizes again. + const replay = (await f.request( + `${endpoint}/select`, + 'POST', + selectionResponse.request().postDataJSON(), + { 'Idempotency-Key': selectionResponse.request().headers()['idempotency-key']! } + )) as ChronologicalValidationActionResult; + expect(replay.receipt).toEqual(selected.receipt); + expect(replay.validation.report).toEqual(report); + expect((await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows).toEqual( + originalRuns + ); + await f.page.reload(); + await visible(f.page, 'Execution complete · report saved'); + expect((await f.request(endpoint)).validation.report).toEqual(report); + await f.page.getByRole('link', { name: 'Open test experiment', exact: true }).click(); + await f.page.waitForURL( + `${f.origin}/experiments/${selected.validation.selection!.holdoutExperimentIds.test}` + ); + await visible(f.page, /completed: 1/); + await f.page.goto(`${f.origin}/experiments`); + await visible(f.page, 'Saved chronological validations'); + await f.page.locator(`a[href="/experiments/validation/${admitted.id}"]`).click(); + await visible(f.page, 'Execution complete · report saved'); + expect(f.historicalDataReads).toEqual([]); + expect(f.unexpectedNetwork).toEqual([]); + } finally { + await f.close(); + } +}); + test('failed_experiment_trial_retry_preserves_history_and_reopens_native_result_browser', async () => { const f = await fixture(true); f.page.on('dialog', dialog => void dialog.accept()); diff --git a/test/integration/chronological-validation-durable-api.test.ts b/test/integration/chronological-validation-durable-api.test.ts new file mode 100644 index 00000000..bf625d4f --- /dev/null +++ b/test/integration/chronological-validation-durable-api.test.ts @@ -0,0 +1,133 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import { z } from 'zod'; +import { createHttpSecurity } from '@stock-bot/di'; +import type { IServiceContainer } from '@stock-bot/services'; +import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; +import { chronologicalDataset } from '../fixtures/chronological-validation'; + +const tokens = { + operator: 'validation-admin-fixture-not-a-real-secret-1234', + service: 'validation-service-fixture-not-a-real-secret-1234', + read: 'validation-read-fixture-not-a-real-secret-1234', +}; +const input = { + backtestId: randomUUID(), + name: 'Validation preview', + grid: { fastPeriod: [1, 2] }, + recipe: chronologicalDataset().recipe, +}; +type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record[] }>; +function fixture( + mode: 'enabled' | 'disabled' | 'absent' = 'enabled', + query: Query = async () => ({ rows: [] }) +) { + const client = { query: mock(query) }; + const database = { + ...client, + transaction: mock(async (work: (client: { query: Query }) => Promise) => work(client)), + }; + const app = new Hono(); + if (mode !== 'absent') { + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + readToken: tokens.read, + environment: 'test', + hostname: '127.0.0.1', + disabled: mode === 'disabled', + }).mount(app); + } + app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer)); + return { + database, + request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) { + return app.request('/api/v2/experiments/validation' + path, { + method, + headers: { + 'Content-Type': 'application/json', + ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), + ...(key ? { 'Idempotency-Key': key } : {}), + }, + ...(body === undefined ? {} : { body }), + }); + }, + }; +} + +const id = randomUUID(), + previewHash = 'a'.repeat(64), + selectionHash = 'b'.repeat(64); +const actions = [ + ['', JSON.stringify({ ...input, previewHash })], + [`/${id}/select`, JSON.stringify({ previewHash })], + [`/${id}/finalize`, JSON.stringify({ previewHash, selectionHash })], + [`/${id}/cancel`, '{}'], +]; +describe('durable validation HTTP gates', () => { + test('all writes require real operator/service proof including disabled development auth; readers only inspect', async () => { + for (const mode of ['enabled', 'disabled', 'absent'] as const) { + const f = fixture(mode); + for (const [path, body] of actions) { + expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401); + } + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + const f = fixture(); + for (const [path, body] of actions) { + expect((await f.request(path, 'POST', body, 'read', 'key')).status).toBe(403); + } + expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200); + expect((await f.request(`/${id}`, 'GET', undefined, 'read')).status).toBe(404); + expect((await f.request()).status).toBe(401); + }); + test('strict bodies, unknown winners/actions, raw reserved grids and missing receipts reject before any transaction', async () => { + for (const [path, body, key] of [ + ['', '{', 'key'], + ['', JSON.stringify({ ...input, previewHash, winner: 1 }), 'key'], + [ + '', + JSON.stringify({ ...input, previewHash }).replace('"fastPeriod":[1,2]', '"__proto__":[1]'), + 'key', + ], + [`/${id}/select`, JSON.stringify({ previewHash, winner: 0 }), 'key'], + [`/${id}/select`, JSON.stringify({ previewHash }), undefined], + [`/${id}/finalize`, JSON.stringify({ previewHash }), 'key'], + [ + `/${id}/finalize`, + JSON.stringify({ previewHash, selectionHash, operation: 'select' }), + 'key', + ], + [`/${id}/cancel`, '{"restart":true}', undefined], + ['/bad/select', JSON.stringify({ previewHash }), 'key'], + ]) { + const f = fixture(); + expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400); + expect(f.database.transaction.mock.calls).toHaveLength(0); + expect(f.database.query.mock.calls).toHaveLength(0); + } + }); + test('correct operation routes return missing404 and sanitize unexpected database/schema errors500', async () => { + for (const role of ['operator', 'service'] as const) { + const f = fixture(); + for (const [path, body] of actions) { + expect((await f.request(path, 'POST', body, role, 'key')).status).toBe(404); + } + } + for (const error of [new Error('private storage failure'), new z.ZodError([])]) { + const f = fixture('enabled', async () => { + throw error; + }); + const response = await f.request( + `/${id}/select`, + 'POST', + JSON.stringify({ previewHash }), + 'operator', + 'key' + ); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' }); + } + }); +}); diff --git a/test/integration/chronological-validation-durable-ui.test.tsx b/test/integration/chronological-validation-durable-ui.test.tsx new file mode 100644 index 00000000..5fca5920 --- /dev/null +++ b/test/integration/chronological-validation-durable-ui.test.tsx @@ -0,0 +1,1029 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { GlobalWindow } from 'happy-dom'; +import { act, createElement } from 'react'; +import type { Root } from 'react-dom/client'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import { + chronologicalValidationPolicy, + type ChronologicalValidationInput, + type ChronologicalValidationPreview, +} from '@stock-bot/stock-config/chronological-validation'; +import type { + ChronologicalValidationActionReceipt, + ChronologicalValidationDetail, + ValidationResultEvidence, +} from '@stock-bot/stock-config/chronological-validation'; +import type { + ExperimentDetail, + ExperimentPreview, + ExperimentTrial, +} from '@stock-bot/stock-config/experiments'; +import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; +import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +const browser = new GlobalWindow({ url: 'http://localhost:5173' }); +const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const; +const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); +let createRoot: typeof import('react-dom/client').createRoot; +let router: typeof import('react-router-dom'); +let ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage; +let root: Root | undefined; +let host: HTMLDivElement; +let navigate: ReturnType; +let location = ''; +const backtestId = '11111111-1111-4111-8111-111111111111'; +const otherBacktestId = '22222222-2222-4222-8222-222222222222'; +const versionId = '55555555-5555-4555-8555-555555555555'; +const endpoint = '/api/v2/experiments/validation/preview'; +function deferred() { + let resolve!: (value: T) => void; + let reject!: (cause: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +type Pending = ReturnType> & { + path: string; + method: string; + body: unknown; + rawBody: unknown; + headers: Headers; + settled: boolean; + signal?: AbortSignal | null; + credentials?: RequestCredentials; +}; +const requests: Pending[] = []; +function request(path: string, method = 'GET') { + const found = requests.find( + item => item.path === path && item.method === method && !item.settled + ); + if (!found) { + throw new Error(`Missing ${method} ${path}`); + } + return found; +} +function reply(item: Pending, value: unknown, status = 200) { + item.settled = true; + item.resolve(Response.json(value, { status })); +} +async function flush(action: () => void = () => {}) { + await act(async () => { + action(); + await Promise.resolve(); + }); +} +function button(label: string) { + const found = [...host.querySelectorAll('button')].find( + item => item.textContent?.trim() === label + ); + if (!found) { + throw new Error(`Missing button ${label}: ${host.textContent}`); + } + return found; +} +function field(label: string) { + const found = [...host.querySelectorAll('label')] + .find( + item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label + ) + ?.querySelector('input,select,textarea'); + if (!found) { + throw new Error(`Missing field ${label}`); + } + return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; +} +function change(label: string, value: string) { + const input = field(label); + const prototype = + input.tagName === 'SELECT' + ? browser.HTMLSelectElement.prototype + : input.tagName === 'TEXTAREA' + ? browser.HTMLTextAreaElement.prototype + : browser.HTMLInputElement.prototype; + Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value); + input.dispatchEvent( + new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', { + bubbles: true, + }) as unknown as Event + ); +} +function Probe() { + navigate = router.useNavigate(); + location = router.useLocation().pathname + router.useLocation().search; + return null; +} +const template = (id = backtestId): Backtest => ({ + id, + name: `Template ${id}`, + strategy: 'sma', + strategyVersionId: versionId, + symbols: ['X0.US'], + startDate: '2024-01-01', + endDate: '2024-01-02', + initialCapital: 100, + config: { canonical: {}, datasetHash: 'a'.repeat(64) }, + archivedAt: null, + createdAt: '2026-10-24', + updatedAt: '2026-10-24', +}); + +let ChronologicalValidationDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage').ChronologicalValidationDetailPage; +function sourcePreview(count = 2, parent = backtestId): ExperimentPreview { + const owner = `strategy:${versionId}`; + const { config, dataset } = nativeReplayFixture(60, 1, [owner]); + const previewId = '00000000-0000-4000-8000-000000000001'; + config.matching.risk.ledger.sessionId = previewId; + config.matching.risk.ledger.accountId = `research:${previewId}`; + const builtin = builtinCatalogDescriptors[0]!; + const candidates = Array.from({ length: count }, (_, index) => ({ + index, + trialKey: String(index + 1).padStart(64, '0'), + parameters: { fastPeriod: index + 2, slowPeriod: 20 }, + })); + return { + version: 'research-experiment-preview/v1', + previewHash: 'e'.repeat(64), + input: { + backtestId: parent, + name: 'Trend study', + grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, + }, + dataset: dataset.manifest, + candidates, + request: canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId: previewId, + backtestId: parent, + name: 'Frozen template name', + strategy: { + familyId: '66666666-6666-4666-8666-666666666666', + versionId, + origin: 'builtin', + reviewId: '88888888-8888-4888-8888-888888888888', + package: { + version: 1, + program: builtin.program, + parameterSchema: builtin.parameterSchema, + artifact: { + format: 'esm-bundle/v1', + entryExport: builtin.entryExport, + content: 'Never execute fixture code', + sha256: 'a'.repeat(64), + }, + dependencyLock: { + format: 'bun-lock/v1', + content: 'Retained lock', + sha256: 'b'.repeat(64), + }, + source: { revision: 'c'.repeat(40), dirty: false }, + build: { tool: 'bun', version: '1.2.17', target: 'browser' }, + }, + selection: { + strategyId: builtin.program.strategyId, + strategyVersion: builtin.program.strategyVersion, + ownerId: owner, + seed: 17, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '100', + parameters: { fastPeriod: 2, slowPeriod: 20 }, + }, + }, + datasetHash: dataset.manifest.hash, + policy: config, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: '1.2.17', + platform: 'linux', + arch: 'x64', + }, + modelArtifacts: [], + }), + }; +} + +function prepared(): ChronologicalValidationPreview { + const source = sourcePreview(); + const start = source.dataset.bounds.warmupStart; + const minute = 60000; + const bounds = (offset: number) => ({ + warmupStart: start + offset * minute, + tradeStart: start + (offset + 22) * minute, + tradeEnd: start + (offset + 30) * minute, + }); + const input: ChronologicalValidationInput = { + ...source.input, + recipe: { + version: 1, + train: bounds(0), + validation: bounds(10), + test: bounds(20), + labelHorizonMs: 0, + }, + }; + const phases = ['train', 'validation', 'test'] as const; + const partitions = phases.map((phase, index) => { + const dataset = { + ...structuredClone(source.dataset), + hash: ['a', 'b', 'c'][index]!.repeat(64), + bounds: input.recipe[phase], + barCount: 30, + }; + const request = { ...structuredClone(source.request), datasetHash: dataset.hash }; + return { + phase, + dataset, + request, + counts: { + totalBars: 30, + availableWarmup: 21, + admittedWarmup: 21, + ignoredLateWarmup: 0, + availableEvaluation: 8, + terminalAtEnd: 1, + unavailableAtEnd: 0, + }, + requiredWarmup: 21, + warnings: ['Input history sufficiency does not establish statistical adequacy.'], + }; + }) as ChronologicalValidationPreview['partitions']; + return { + version: 'chronological-validation-preview/v1', + execution: 'preview-only', + previewHash: 'f'.repeat(64), + input, + source, + policy: chronologicalValidationPolicy, + partitions, + }; +} +function metrics(): NonNullable { + return { + totalReturn: 0, + cagr: null, + maxDrawdown: 0, + exposureTime: 0, + volatility: null, + downsideDeviation: null, + sharpeRatio: null, + sortinoRatio: null, + var95: null, + cvar95: null, + var99: null, + alpha: null, + beta: null, + informationRatio: null, + roundTripCount: null, + winRate: null, + profitFactor: null, + avgWin: null, + avgLoss: null, + }; +} + +const validationId = '33333333-3333-4333-8333-333333333333'; +const otherId = '44444444-4444-4444-8444-444444444444'; +const childIds = { + train: validationId, + validation: '66666666-6666-4666-8666-666666666666', + test: '77777777-7777-4777-8777-777777777777', +}; +const basePath = '/api/v2/experiments/validation'; +const detailPath = `${basePath}/${validationId}`; +const currentReview = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; +function phaseExperiment( + source: ChronologicalValidationPreview, + phase: 'train' | 'validation' | 'test', + completed: boolean +): ExperimentDetail { + const index = ['train', 'validation', 'test'].indexOf(phase), + prototype = source.partitions[index]!; + const winner = source.source.candidates[1]!; + const candidates = phase === 'train' ? source.source.candidates : [{ ...winner, index: 0 }]; + const input = { + ...source.source.input, + name: `${source.input.name} · ${phase}`, + grid: phase === 'train' ? source.input.grid : {}, + }; + const request = structuredClone(prototype.request); + if (phase !== 'train') { + request.strategy.reviewId = currentReview; + request.strategy.selection.parameters = winner.parameters as never; + } + const preview: ExperimentPreview = { + version: 'research-experiment-preview/v1', + previewHash: String(index + 1).repeat(64), + input, + dataset: prototype.dataset, + request, + candidates, + }; + const trials: ExperimentTrial[] = candidates.map((candidate, item) => ({ + ...candidate, + runId: `99999999-9999-4999-8999-${String(index * 10 + item + 1).padStart(12, '0')}`, + attemptNumber: completed ? 1 : 0, + retryCount: 0, + status: completed ? 'completed' : 'pending', + progress: completed ? 100 : 0, + cancelRequested: false, + error: null, + comparable: completed, + diagnostic: null, + metrics: completed + ? { ...metrics(), totalReturn: phase === 'train' && item === 0 ? -0.1 : 0 } + : null, + unavailable: completed ? { sharpeRatio: 'insufficient-periods' } : null, + limitations: [], + })); + return { + id: childIds[phase], + name: input.name, + backtestId: source.input.backtestId, + createdAt: '2026-10-24T10:00:00Z', + cancelRequested: false, + trialCount: trials.length, + counts: { + pending: completed ? 0 : trials.length, + running: 0, + paused: 0, + completed: completed ? trials.length : 0, + failed: 0, + cancelled: 0, + }, + datasetHash: prototype.dataset.hash, + strategyVersionId: versionId, + previewHash: preview.previewHash, + preview, + trials, + }; +} +function evidenceFor( + phase: 'train' | 'validation' | 'test', + experiment: ExperimentDetail, + index: number +): ValidationResultEvidence { + const trial = experiment.trials[index]!; + return { + phase, + experimentId: experiment.id, + runId: trial.runId!, + sourceCandidateIndex: phase === 'train' ? index : 1, + trialKey: trial.trialKey, + parameters: trial.parameters, + datasetHash: experiment.datasetHash, + requestHash: 'b'.repeat(64), + economicHash: 'c'.repeat(64), + metrics: trial.metrics!, + unavailable: trial.unavailable!, + completePeriodCount: 1, + periodicSampleCount: 1, + fillCount: 0, + limitations: trial.limitations, + }; +} +function document( + stage: 'training' | 'ready' | 'holdouts' | 'holdouts-ready' | 'reported' = 'training' +): ChronologicalValidationDetail { + const preview = prepared(); + const train = phaseExperiment(preview, 'train', stage !== 'training'); + const heldout = stage === 'holdouts' || stage === 'holdouts-ready' || stage === 'reported'; + const validation = phaseExperiment(preview, 'validation', stage !== 'holdouts'); + const test = phaseExperiment(preview, 'test', stage !== 'holdouts'); + const selection: ChronologicalValidationDetail['selection'] = heldout + ? { + version: 'chronological-validation-selection/v1', + id: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + validationId, + previewHash: preview.previewHash, + selectionHash: 'd'.repeat(64), + createdAt: '2026-10-24T11:00:00Z', + principal: 'operator', + reviewId: currentReview, + winner: preview.source.candidates[1]!, + training: train.trials.map((_, index) => evidenceFor('train', train, index)), + holdoutExperimentIds: { validation: childIds.validation, test: childIds.test }, + } + : null; + return { + id: validationId, + name: preview.input.name, + backtestId, + createdAt: train.createdAt, + cancelRequested: false, + previewHash: preview.previewHash, + trainingCandidateCount: 2, + stage: stage === 'reported' ? 'reported' : heldout ? 'holdouts' : 'training', + preview, + phases: [ + { phase: 'train', status: 'admitted', experimentId: train.id, experiment: train }, + { + phase: 'validation', + status: heldout ? 'admitted' : 'not-admitted', + experimentId: heldout ? validation.id : null, + experiment: heldout ? validation : null, + }, + { + phase: 'test', + status: heldout ? 'admitted' : 'not-admitted', + experimentId: heldout ? test.id : null, + experiment: heldout ? test : null, + }, + ], + selection, + report: + stage === 'reported' + ? { + version: 'chronological-validation-report/v1', + id: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', + validationId, + previewHash: preview.previewHash, + selectionHash: selection!.selectionHash, + reportHash: 'e'.repeat(64), + createdAt: '2026-10-24T12:00:00Z', + principal: 'operator', + reset: 'initial-capital-empty-positions', + training: selection!.training, + validation: evidenceFor('validation', validation, 0), + test: evidenceFor('test', test, 0), + limitations: ['Independent reset accounts; no continuous portfolio claim.'], + } + : null, + actions: { + select: { + available: stage === 'ready', + reason: + stage === 'training' + ? 'Every training candidate must complete with a comparable finite score.' + : null, + }, + finalize: { + available: stage === 'holdouts-ready', + reason: stage === 'holdouts' ? 'Waiting for validation and test results.' : null, + }, + }, + }; +} +function receipt( + value: ChronologicalValidationDetail, + operation: 'select' | 'finalize' +): ChronologicalValidationActionReceipt { + const saved = operation === 'select' ? value.selection! : value.report!; + return { + id: saved.id, + validationId: value.id, + operation: operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report', + previewHash: value.previewHash, + selectionHash: value.selection!.selectionHash, + createdAt: saved.createdAt, + principal: saved.principal, + }; +} +async function mount(path = `/experiments?backtestId=${backtestId}`) { + root ??= createRoot(host); + const routes = createElement( + router.Routes, + null, + createElement(router.Route, { + path: '/experiments', + element: createElement(ExperimentListPage), + }), + createElement(router.Route, { + path: '/experiments/validation/:validationId', + element: createElement(ChronologicalValidationDetailPage), + }) + ); + await flush(() => + root!.render( + createElement(router.MemoryRouter, { initialEntries: [path] }, routes, createElement(Probe)) + ) + ); +} +async function show(value = document()) { + await mount(`/experiments/validation/${value.id}`); + await flush(() => reply(request(`${basePath}/${value.id}`), { validation: value })); +} +async function editor() { + const value = prepared(); + await mount(); + await flush(() => { + reply(request('/api/v2/backtests?limit=50&offset=0'), [template(), template(otherBacktestId)]); + reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] }); + reply(request(`${basePath}?backtestId=${backtestId}`), { validations: [] }); + }); + await flush(() => { + change('Experiment name', value.input.name); + change('Parameter grid (JSON)', JSON.stringify(value.input.grid)); + for (const phase of ['train', 'validation', 'test'] as const) { + const name = phase[0]!.toUpperCase() + phase.slice(1); + change( + `${name} warmup start (UTC)`, + new Date(value.input.recipe[phase].warmupStart).toISOString() + ); + change( + `${name} trading start (UTC)`, + new Date(value.input.recipe[phase].tradeStart).toISOString() + ); + change( + `${name} trading end (UTC)`, + new Date(value.input.recipe[phase].tradeEnd).toISOString() + ); + } + }); + await flush(() => button('Preview chronological validation').click()); + await flush(() => reply(request(endpoint, 'POST'), { preview: value })); + return value; +} +async function lose(post: Pending) { + await flush(() => { + post.settled = true; + post.reject(new Error('Response lost')); + }); +} +beforeAll(async () => { + for (const [key, value] of Object.entries({ + window: browser, + document: browser.document, + Event: browser.Event, + ResizeObserver: browser.ResizeObserver, + IS_REACT_ACT_ENVIRONMENT: true, + })) { + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + } + ({ createRoot } = await import('react-dom/client')); + router = await import('react-router-dom'); + ({ ExperimentListPage } = await import('../../apps/stock/web-app/src/features/experiments')); + ({ ChronologicalValidationDetailPage } = await import( + '../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage' + )); +}); +beforeEach(() => { + requests.length = 0; + location = ''; + host = browser.document.createElement('div') as unknown as HTMLDivElement; + browser.document.body.append(host as never); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + Object.defineProperty(browser, 'fetch', { + configurable: true, + value: (input: unknown, init?: RequestInit) => { + const url = new URL(String(input)); + const item: Pending = { + ...deferred(), + path: url.pathname + url.search, + method: init?.method ?? 'GET', + rawBody: init?.body, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + headers: new Headers(init?.headers), + signal: init?.signal, + credentials: init?.credentials, + settled: false, + }; + requests.push(item); + return item.promise; + }, + }); +}); +afterEach(async () => { + if (root) { + await flush(() => root!.unmount()); + } + root = undefined; + host.remove(); +}); +afterAll(async () => { + await browser.happyDOM.close(); + for (const key of keys) { + const value = originals.get(key); + if (value) { + Object.defineProperty(globalThis, key, value); + } else { + Reflect.deleteProperty(globalThis, key); + } + } +}); + +describe('durable chronological training admission', () => { + test('preflight remains read-only until explicit duplicate-safe training admission', async () => { + const source = await editor(); + expect(host.textContent).toContain('No saved chronological validations.'); + expect(requests.filter(item => item.path === basePath && item.method === 'POST')).toHaveLength( + 0 + ); + await flush(() => { + button('Submit training runs').click(); + button('Submit training runs').click(); + }); + const post = request(basePath, 'POST'); + expect(post.body).toEqual({ ...source.input, previewHash: source.previewHash }); + expect(post.headers.get('Idempotency-Key')).toBeTruthy(); + expect(post.credentials).toBe('include'); + expect(requests.filter(item => item.path === basePath && item.method === 'POST')).toHaveLength( + 1 + ); + expect(field('Experiment name').disabled).toBe(true); + expect(field('Saved backtest').disabled).toBe(true); + expect(button('Preview experiment').disabled).toBe(true); + await flush(() => reply(post, { validation: document() }, 202)); + expect(location).toBe(`/experiments/validation/${validationId}`); + await flush(() => reply(request(detailPath), { validation: document() })); + expect(host.textContent).toContain('Not admitted. No validation run exists'); + }); + test.each(['ordinary', 'chronological'] as const)( + '%s wins synchronous shared-editor admission ownership', + async winner => { + const source = await editor(); + await flush(() => button('Preview experiment').click()); + await flush(() => + reply(request('/api/v2/experiments/preview', 'POST'), { preview: source.source }) + ); + const ordinary = button('Confirm experiment'), + chronological = button('Submit training runs'); + await flush(() => { + if (winner === 'ordinary') { + ordinary.click(); + chronological.click(); + } else { + chronological.click(); + ordinary.click(); + } + }); + const admitted = requests.filter( + item => item.method === 'POST' && [basePath, '/api/v2/experiments'].includes(item.path) + ); + expect(admitted).toHaveLength(1); + expect(admitted[0]!.path).toBe(winner === 'ordinary' ? '/api/v2/experiments' : basePath); + await lose(admitted[0]!); + expect(field('Experiment name').disabled).toBe(true); + expect( + button(winner === 'ordinary' ? 'Preview chronological validation' : 'Preview experiment') + .disabled + ).toBe(true); + } + ); + test.each(['network', 'malformed', 'foreign'] as const)( + '%s training response retains exact body/key and locks shared fields until explicit release', + async kind => { + await editor(); + await flush(() => button('Submit training runs').click()); + const first = request(basePath, 'POST'); + if (kind === 'network') { + await lose(first); + } else { + const foreign = document(); + foreign.backtestId = otherBacktestId; + await flush(() => + reply( + first, + kind === 'malformed' ? { validation: { id: validationId } } : { validation: foreign }, + 202 + ) + ); + } + expect(host.textContent).toContain('Training admission is unconfirmed'); + expect(field('Parameter grid (JSON)').disabled).toBe(true); + await flush(() => button('Refresh chronological validations').click()); + await flush(() => + reply(request(`${basePath}?backtestId=${backtestId}`), { validations: [document()] }) + ); + await flush(() => button('Retry training submission').click()); + const retry = request(basePath, 'POST'); + expect(retry.rawBody).toBe(first.rawBody); + expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); + await flush(() => reply(retry, { validation: document('reported') }, 202)); + expect(location).toBe(`/experiments/validation/${validationId}`); + } + ); + test('training intent is discarded only explicitly, and requires a fresh preview afterward', async () => { + await editor(); + await flush(() => button('Submit training runs').click()); + await lose(request(basePath, 'POST')); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); + await flush(() => button('Discard training submission').click()); + expect(field('Experiment name').disabled).toBe(true); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + await flush(() => button('Discard training submission').click()); + expect(field('Experiment name').disabled).toBe(false); + expect(host.textContent).not.toContain('Retry training submission'); + expect(button('Preview experiment').disabled).toBe(false); + expect( + [...host.querySelectorAll('button')].some(item => item.textContent === 'Submit training runs') + ).toBe(false); + }); + test('late accepted training response cannot navigate a different selected template', async () => { + await editor(); + await flush(() => button('Submit training runs').click()); + const old = request(basePath, 'POST'); + await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); + await flush(() => reply(old, { validation: document() }, 202)); + expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`); + expect(field('Experiment name').value).toBe(''); + }); +}); + +describe('explicit selection and immutable reporting', () => { + test('training → fixed selection → holdouts → report requires separate POSTs; refresh never advances', async () => { + await show(document()); + expect(button('Freeze selection and run holdouts').disabled).toBe(true); + expect(host.textContent).toContain('Every training candidate must complete'); + await flush(() => button('Refresh validation').click()); + await flush(() => reply(request(detailPath), { validation: document('ready') })); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + await flush(() => { + button('Freeze selection and run holdouts').click(); + button('Freeze selection and run holdouts').click(); + }); + const select = request(`${detailPath}/select`, 'POST'); + expect(select.body).toEqual({ previewHash: prepared().previewHash }); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + await flush(() => + reply( + select, + { receipt: receipt(document('holdouts'), 'select'), validation: document('holdouts') }, + 202 + ) + ); + expect(host.textContent).toContain('Selected training candidate 2'); + expect(button('Save validation report').disabled).toBe(true); + for (const phase of ['train', 'validation', 'test'] as const) { + expect(host.querySelector(`a[href="/experiments/${childIds[phase]}"]`)?.textContent).toBe( + `Open ${phase} experiment` + ); + } + await flush(() => button('Refresh validation').click()); + await flush(() => reply(request(detailPath), { validation: document('holdouts-ready') })); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + await flush(() => button('Save validation report').click()); + const finalize = request(`${detailPath}/finalize`, 'POST'); + expect(finalize.body).toEqual({ + previewHash: prepared().previewHash, + selectionHash: 'd'.repeat(64), + }); + const reported = document('reported'); + await flush(() => + reply(finalize, { receipt: receipt(reported, 'finalize'), validation: reported }, 202) + ); + expect(host.textContent).toContain('Execution complete · report saved'); + expect(host.textContent).toContain(reported.report!.reportHash); + expect(host.textContent).toContain('Insufficient periodic samples'); + expect(host.textContent).toContain('Unavailable: insufficient-periods'); + const firstHoldout = host.querySelector( + '[aria-label="Retained validation and test evidence"] tbody tr' + )!; + expect(firstHoldout.querySelectorAll('td')[2]!.textContent).toBe('0'); + expect(host.textContent).not.toContain('strategy validated'); + await flush(() => button('Refresh validation').click()); + await flush(() => reply(request(detailPath), { validation: reported })); + expect(host.textContent).toContain(reported.report!.id); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(2); + }); + test.each(['select', 'finalize'] as const)( + 'lost %s receipt survives refresh to reported/cancelled state and retains its original operation', + async operation => { + await show(document(operation === 'select' ? 'ready' : 'holdouts-ready')); + await flush(() => + button( + operation === 'select' ? 'Freeze selection and run holdouts' : 'Save validation report' + ).click() + ); + const first = request(`${detailPath}/${operation}`, 'POST'); + await lose(first); + const current = document('reported'); + current.cancelRequested = true; + await flush(() => button('Refresh validation').click()); + await flush(() => reply(request(detailPath), { validation: current })); + expect(host.textContent).toContain('Action acceptance is unconfirmed'); + const label = operation === 'select' ? 'Retry selection request' : 'Retry report request'; + await flush(() => button(label).click()); + const repeated = request(`${detailPath}/${operation}`, 'POST'); + expect(repeated.rawBody).toBe(first.rawBody); + expect(repeated.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); + await flush(() => + reply(repeated, { receipt: receipt(current, operation), validation: current }, 202) + ); + expect(host.textContent).not.toContain('Action acceptance is unconfirmed'); + expect(host.textContent).toContain('Execution complete · report saved'); + expect( + requests + .filter(item => item.method === 'POST') + .every(item => item.path.endsWith(`/${operation}`)) + ).toBe(true); + } + ); + test('read failure preserves unresolved action and exact replay while cancellation remains separate', async () => { + await show(document('ready')); + await flush(() => button('Freeze selection and run holdouts').click()); + const first = request(`${detailPath}/select`, 'POST'); + await lose(first); + await flush(() => button('Refresh validation').click()); + await flush(() => reply(request(detailPath), { error: 'Read unavailable' }, 500)); + expect(host.textContent).toContain('Showing the last loaded state'); + await flush(() => button('Cancel remaining validation work').click()); + const cancelled = document('holdouts'); + cancelled.cancelRequested = true; + await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { validation: cancelled })); + expect(host.textContent).toContain('Action acceptance is unconfirmed'); + await flush(() => button('Retry selection request').click()); + const repeated = request(`${detailPath}/select`, 'POST'); + expect(repeated.rawBody).toBe(first.rawBody); + expect(repeated.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); + await flush(() => + reply(repeated, { receipt: receipt(cancelled, 'select'), validation: cancelled }, 202) + ); + expect(host.textContent).toContain('Selection and holdout admission accepted.'); + }); + test.each([ + 'receipt-id', + 'receipt-actor', + 'receipt-operation', + 'receipt-hash', + 'evidence-metric', + 'evidence-status', + 'evidence-order', + 'winner-index', + ] as const)( + 'malformed %s select result does not fabricate success and keeps the exact request', + async kind => { + await show(document('ready')); + await flush(() => button('Freeze selection and run holdouts').click()); + const first = request(`${detailPath}/select`, 'POST'); + const value = document('holdouts'), + accepted = receipt(value, 'select'); + if (kind === 'receipt-id') { + accepted.id = otherId; + } + if (kind === 'receipt-actor') { + accepted.principal = 'service'; + } + if (kind === 'receipt-operation') { + accepted.operation = 'finalize-report'; + } + if (kind === 'receipt-hash') { + accepted.selectionHash = '1'.repeat(64); + } + if (kind === 'evidence-metric') { + value.selection!.training[0]!.metrics = { + ...value.selection!.training[0]!.metrics, + totalReturn: 5, + }; + } + if (kind === 'evidence-status') { + const train = value.phases[0].experiment!; + train.trials[0]!.status = 'failed'; + train.trials[0]!.comparable = false; + train.counts.failed = 1; + train.counts.completed = 1; + } + if (kind === 'evidence-order') { + value.selection!.training.reverse(); + } + if (kind === 'winner-index') { + value.selection!.winner = { ...value.selection!.winner, index: 0 }; + } + await flush(() => reply(first, { receipt: accepted, validation: value }, 202)); + expect(host.textContent).toContain('could not be verified'); + expect(host.textContent).toContain('Action acceptance is unconfirmed'); + expect(host.textContent).not.toContain('Selection and holdout admission accepted.'); + await flush(() => button('Retry selection request').click()); + const retry = request(`${detailPath}/select`, 'POST'); + expect(retry.rawBody).toBe(first.rawBody); + expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); + } + ); + test('failed, missing and not-admitted phases remain distinct with no invented pending jobs', async () => { + const value = document('holdouts'); + value.phases[2] = { ...value.phases[2], status: 'missing', experiment: null }; + const heldout = value.phases[1].experiment!; + heldout.trials[0]!.status = 'failed'; + heldout.trials[0]!.error = 'Worker failed'; + heldout.counts.pending = 0; + heldout.counts.failed = 1; + await show(value); + expect(host.textContent).toContain('Expected test experiment is missing'); + expect(host.textContent).toContain('Worker failed'); + expect(host.textContent).toContain('Total return (fraction): Unavailable'); + expect(button('Save validation report').disabled).toBe(true); + expect(host.textContent).not.toContain('No test run exists before'); + }); + test.each([400, 401, 404, 409, 500])( + 'action HTTP %s preserves explicit error and performs no automatic next step', + async status => { + await show(document('ready')); + await flush(() => button('Freeze selection and run holdouts').click()); + await flush(() => + reply(request(`${detailPath}/select`, 'POST'), { error: 'Selection not available' }, status) + ); + expect(host.textContent).toContain('Selection not available'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); + await flush(() => button('Discard action request').click()); + expect(host.textContent).toContain('Retry selection request'); + } + ); +}); + +describe('durable validation read and navigation isolation', () => { + test.each(['Freeze selection and run holdouts', 'Cancel remaining validation work'])( + 'same-event refresh fences %s before another action captures an intent', + async label => { + await show(document('ready')); + await flush(() => { + button('Refresh validation').click(); + button(label).click(); + }); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + expect(host.textContent).not.toContain('Retry selection request'); + await flush(() => reply(request(detailPath), { validation: document('ready') })); + await flush(() => button(label).click()); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + } + ); + test('select/cancel and refresh share synchronous mutation exclusion', async () => { + await show(document('ready')); + await flush(() => { + button('Cancel remaining validation work').click(); + button('Freeze selection and run holdouts').click(); + button('Refresh validation').click(); + }); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(requests.filter(item => item.path === detailPath && item.method === 'GET')).toHaveLength( + 1 + ); + expect(requests.find(item => item.method === 'POST')!.path).toBe(`${detailPath}/cancel`); + }); + test('owned navigation preserves the unresolved action when discard is declined', async () => { + await show(document('ready')); + await flush(() => button('Freeze selection and run holdouts').click()); + const first = request(`${detailPath}/select`, 'POST'); + await lose(first); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); + await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click()); + await flush(() => + (host.querySelector(`a[href="/experiments/${validationId}"]`) as HTMLAnchorElement).click() + ); + expect(location).toBe(`/experiments/validation/${validationId}`); + await flush(() => button('Retry selection request').click()); + expect(request(`${detailPath}/select`, 'POST').headers.get('Idempotency-Key')).toBe( + first.headers.get('Idempotency-Key') + ); + }); + test('late action and read responses cannot overwrite a different validation route', async () => { + await show(document('ready')); + await flush(() => button('Freeze selection and run holdouts').click()); + const old = request(`${detailPath}/select`, 'POST'); + await flush(() => navigate(`/experiments/validation/${otherId}`)); + await flush(() => + reply(request(`${basePath}/${otherId}`), { error: 'Other validation unavailable' }, 404) + ); + const value = document('holdouts'); + await flush(() => reply(old, { receipt: receipt(value, 'select'), validation: value }, 202)); + expect(host.textContent).toContain('Other validation unavailable'); + expect(host.textContent).not.toContain('Selected training candidate'); + await flush(() => button('Refresh validation').click()); + const read = request(`${basePath}/${otherId}`); + await flush(() => navigate(`/experiments/validation/${validationId}`)); + await flush(() => reply(request(detailPath), { validation: document('ready') })); + await flush(() => reply(read, { error: 'Stale failure' }, 500)); + expect(host.textContent).not.toContain('Stale failure'); + expect(button('Freeze selection and run holdouts').disabled).toBe(false); + }); + test('saved validation list loads independently, recovers errors and reopens exact root identity', async () => { + await mount(); + expect(host.textContent).toContain('Loading chronological validations...'); + await flush(() => + reply(request(`${basePath}?backtestId=${backtestId}`), { error: 'List unavailable' }, 500) + ); + expect(host.textContent).toContain('List unavailable'); + await flush(() => button('Refresh chronological validations').click()); + const saved = document('reported'); + await flush(() => + reply(request(`${basePath}?backtestId=${backtestId}`), { validations: [saved] }) + ); + const link = host.querySelector( + `a[href="/experiments/validation/${validationId}"]` + ) as HTMLAnchorElement; + expect(link.textContent).toBe(saved.name); + await flush(() => link.click()); + await flush(() => reply(request(detailPath), { validation: saved })); + expect(host.textContent).toContain(saved.report!.id); + expect(host.textContent).toContain(saved.report!.reportHash); + }); + test('old list filter response cannot expose another template validation', async () => { + await mount(); + const old = request(`${basePath}?backtestId=${backtestId}`); + await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); + await flush(() => + reply(request(`${basePath}?backtestId=${otherBacktestId}`), { validations: [] }) + ); + await flush(() => reply(old, { validations: [document()] })); + expect(host.textContent).toContain('No saved chronological validations.'); + expect(host.querySelector(`a[href="/experiments/validation/${validationId}"]`)).toBeNull(); + }); +}); diff --git a/test/integration/chronological-validation-durable.test.ts b/test/integration/chronological-validation-durable.test.ts new file mode 100644 index 00000000..763d0231 --- /dev/null +++ b/test/integration/chronological-validation-durable.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, test } from 'bun:test'; +import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation'; +import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments'; +import { + parseValidationFinalization, + parseValidationSelection, + selectValidationWinner, +} from '../../apps/stock/web-api/src/services/validation-evidence'; + +function fixture(scores: (number | null)[]) { + const candidates: ExperimentCandidate[] = scores.map((_, index) => ({ + index, + trialKey: String(index).padStart(64, '0'), + parameters: { fastPeriod: index + 1, slowPeriod: 5 }, + })); + const evidence: ValidationResultEvidence[] = scores.map((totalReturn, index) => ({ + phase: 'train', + experimentId: 'training', + runId: String(index), + sourceCandidateIndex: index, + trialKey: candidates[index]!.trialKey, + parameters: candidates[index]!.parameters, + datasetHash: 'a'.repeat(64), + requestHash: 'b'.repeat(64), + economicHash: 'c'.repeat(64), + metrics: { + totalReturn, + cagr: null, + maxDrawdown: null, + exposureTime: null, + volatility: null, + downsideDeviation: null, + sharpeRatio: null, + sortinoRatio: null, + var95: null, + cvar95: null, + var99: null, + alpha: null, + beta: null, + informationRatio: null, + roundTripCount: null, + winRate: null, + profitFactor: null, + avgWin: null, + avgLoss: null, + }, + unavailable: {}, + completePeriodCount: 0, + periodicSampleCount: 0, + fillCount: 0, + limitations: [], + })); + return { candidates, evidence }; +} +describe('sealed chronological selection contract', () => { + test('maximizes finite zero/negative training scores, ties choose original index without reordering evidence', () => { + for (const [scores, expected] of [ + [[-0.2, -0.1, -0.1], 1], + [[0, -0.1, 0], 0], + [[0.2, 0.4, 0.3], 1], + ] as const) { + const { candidates, evidence } = fixture([...scores]), + before = structuredClone(evidence); + expect(selectValidationWinner(candidates, evidence)).toEqual(candidates[expected]!); + expect(evidence).toEqual(before); + } + }); + test('missing/null/nonfinite/reordered or holdout evidence can never silently disappear from ranking', () => { + for (const scores of [[1, null], [1, Infinity], [1, NaN], []]) { + const f = fixture(scores); + expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow(); + } + const f = fixture([0, 1]); + expect(() => selectValidationWinner(f.candidates, f.evidence.slice(1))).toThrow(); + expect(() => selectValidationWinner(f.candidates, [...f.evidence].reverse())).toThrow(); + f.evidence[0]!.phase = 'test'; + expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow(); + f.evidence[0]!.phase = 'train'; + f.evidence[0]!.parameters = { fastPeriod: 99 }; + expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow(); + }); + test('selection/finalization bodies cannot supply winners, scores, changed recipes or a different action', () => { + const previewHash = 'a'.repeat(64), + selectionHash = 'b'.repeat(64); + expect(parseValidationSelection({ previewHash })).toEqual({ previewHash }); + expect(parseValidationFinalization({ previewHash, selectionHash })).toEqual({ + previewHash, + selectionHash, + }); + for (const extra of [ + { winner: 1 }, + { metrics: { totalReturn: 2 } }, + { recipe: {} }, + { operation: 'finalize-report' }, + ]) { + expect(() => parseValidationSelection({ previewHash, ...extra })).toThrow(); + expect(() => parseValidationFinalization({ previewHash, selectionHash, ...extra })).toThrow(); + } + expect(() => parseValidationFinalization({ previewHash })).toThrow(); + }); +}); diff --git a/test/integration/chronological-validation-ui.test.tsx b/test/integration/chronological-validation-ui.test.tsx index e281ad44..eb81a960 100644 --- a/test/integration/chronological-validation-ui.test.tsx +++ b/test/integration/chronological-validation-ui.test.tsx @@ -362,9 +362,7 @@ describe('chronological validation preflight', () => { test('explicit UTC preparation sends only read-only preview and displays all phase assumptions and counts', async () => { const value = await fill(); expect(host.textContent).toContain('No chronological preview prepared'); - expect(host.textContent).toContain( - 'Preview only. No datasets, experiments or runs are saved. Staged execution and immutable reports are not available yet.' - ); + expect(host.textContent).toContain('Previewing does not save datasets, experiments or runs.'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => { button('Preview chronological validation').click(); @@ -393,7 +391,7 @@ describe('chronological validation preflight', () => { host .querySelector('[aria-label="Chronological validation preflight"]')! .querySelectorAll('button') - ).toHaveLength(1); + ).toHaveLength(2); expect(host.textContent).not.toContain('Confirm experiment'); expect(location).toBe(`/experiments?backtestId=${backtestId}`); }); diff --git a/test/postgres/canonical-durable-backtest.test.ts b/test/postgres/canonical-durable-backtest.test.ts index 63296da1..8e6c76f3 100644 --- a/test/postgres/canonical-durable-backtest.test.ts +++ b/test/postgres/canonical-durable-backtest.test.ts @@ -65,6 +65,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/canonical-research.test.ts b/test/postgres/canonical-research.test.ts index fed79226..86954d10 100644 --- a/test/postgres/canonical-research.test.ts +++ b/test/postgres/canonical-research.test.ts @@ -64,6 +64,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/catalog-backtest-drafts.test.ts b/test/postgres/catalog-backtest-drafts.test.ts index e9611824..b4521ed5 100644 --- a/test/postgres/catalog-backtest-drafts.test.ts +++ b/test/postgres/catalog-backtest-drafts.test.ts @@ -103,6 +103,7 @@ async function fixture() { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query(sql(name)); } diff --git a/test/postgres/chronological-validation-durable.test.ts b/test/postgres/chronological-validation-durable.test.ts new file mode 100644 index 00000000..4e27247d --- /dev/null +++ b/test/postgres/chronological-validation-durable.test.ts @@ -0,0 +1,917 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { Pool } from 'pg'; +import { createHttpSecurity } from '@stock-bot/di'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; +import type { + ChronologicalValidationInput, + ChronologicalValidationPreview, +} from '@stock-bot/stock-config/chronological-validation'; +import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; +import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; +import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; +import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service'; +import { experimentHash } from '../../apps/stock/web-api/src/services/experiment-input'; +import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; +import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; +import { + selectValidationWinner, + validationEqual, + validationEvidence, + validationPhasePreview, +} from '../../apps/stock/web-api/src/services/validation-evidence'; +import { retainResearchDataset } from '../../scripts/import-research-dataset'; +import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; +import { canonicalSettings } from '../fixtures/canonical-research'; +import { chronologicalDataset } from '../fixtures/chronological-validation'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('chronological-validation'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +let packages: ReturnType | undefined; +const tokens = { + operator: 'chronological-operator-fixture-not-a-real-secret-1234', + service: 'chronological-service-fixture-not-a-real-secret-1234', +}; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +async function fixture(poolMax = 1, withValidation = true) { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Disposable safety database required'); + } + const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + // A single connection detects accidental nested pool reads while the admission lock is held. + const pool = new Pool({ + connectionString: url, + application_name: schema, + max: poolMax, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + for (const name of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '12-historical-datasets.sql', + '14-backtest-submission.sql', + '16-strategy-catalog.sql', + '17-research-retention.sql', + '18-backtest-strategy-versions.sql', + '19-canonical-research.sql', + '21-run-reproduction.sql', + '22-experiments.sql', + '23-experiment-retries.sql', + ...(withValidation ? ['24-chronological-validation.sql'] : []), + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') + ); + } + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); + const container = { postgres, logger }, + api = new BacktestServiceV2(container), + experiments = new ExperimentsService(container), + catalog = new StrategyCatalogService(container); + const version = await catalog.seedBuiltin( + 'Validation SMA', + (await (packages ??= packageBuiltinStrategies()))[0]!, + 'seed' + ); + const data = chronologicalDataset(), + dataset = data.dataset; + await retainResearchDataset(pool, dataset); + const draft = await api.createBacktest( + { + name: 'Validation template', + strategy: 'catalog', + strategyVersionId: version.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: ['X0.US'], + startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: dataset.manifest.hash, + dataFrequency: '1m', + canonical: canonicalSettings, + }, + }, + { autoStart: false } + ); + const input: ChronologicalValidationInput = { + backtestId: draft.id, + name: 'Three explicit windows', + grid: { fastPeriod: [1, 2], slowPeriod: [3] }, + recipe: data.recipe, + }; + const app = new Hono(); + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + environment: 'test', + hostname: '127.0.0.1', + }).mount(app); + app.route('/', createExperimentRoutes(container)); + const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') => + app.request('/api/v2/experiments/validation/preview', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` }, + body: JSON.stringify(raw), + }); + const review = async (decision: 'approve' | 'revoke' = 'approve') => { + await catalog.reviewVersion( + version.id, + { decision, reason: 'Disposable validation proof' }, + 'operator' + ); + return (await catalog.getVersionReviews(version.id)).at(-1)!; + }; + const snapshot = async () => { + const tables = ( + await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [ + schema, + ]) + ).rows; + const rows: Record = {}; + for (const { tablename } of tables) { + const quoted = '"' + String(tablename).replaceAll('"', '""') + '"'; + rows[String(tablename)] = ( + await pool.query( + `SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t` + ) + ).rows[0].rows; + } + return rows; + }; + const validations = new ChronologicalValidationService(container); + const repository = new PostgresBacktestRunRepository(postgres); + const execute = async (id: string) => { + const engine = new RustBacktestAdapter({ + logger, + storage: { + async getHistoricalBars() { + throw new Error('No provider reads allowed'); + }, + }, + }); + const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger }); + try { + await runner.runQueued(id); + } finally { + await runner.shutdown(); + } + }; + return { + cloneTemplate: async (sourceDataset = dataset) => + api.createBacktest( + { + name: 'Other validation template', + strategy: 'catalog', + strategyVersionId: version.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: ['X0.US'], + startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: sourceDataset.manifest.hash, + dataFrequency: '1m', + canonical: canonicalSettings, + }, + }, + { autoStart: false } + ), + validations, + repository, + execute, + api, + pool, + postgres, + experiments, + catalog, + version, + draft, + dataset, + input, + request, + review, + snapshot, + }; +} + +const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key }); +async function submit(f: Awaited>, key = randomUUID()) { + await f.review(); + const preview = await f.experiments.previewValidation(f.input); + const body = { ...f.input, previewHash: preview.previewHash }, + identity = actor(key); + return { preview, body, identity, validation: await f.validations.submit(body, identity) }; +} +async function train(f: Awaited>, id: string) { + const detail = await f.validations.get(id); + for (const trial of detail.phases[0].experiment!.trials) { + await f.execute(trial.runId!); + } +} + +describe.skipIf(!url)('durable chronological validation', () => { + test('native training→write-once winner→same-winner holdouts→historical report and immutable receipt reopen', async () => { + const f = await fixture(), + start = await submit(f), + id = start.validation.id; + expect(start.validation.name).toBe(f.input.name); + expect(start.validation.phases.map(p => p.status)).toEqual([ + 'admitted', + 'not-admitted', + 'not-admitted', + ]); + expect(start.validation.phases[0].experiment!.name).toBe(f.input.name + ' · train'); + expect(await f.experiments.list()).toEqual([]); + expect((await f.validations.list())[0]!.id).toBe(id); + expect(await f.validations.submit(start.body, start.identity)).toEqual(start.validation); + await expect( + f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow('Every train'); + await train(f, id); + const before = await f.validations.get(id); + expect(before.actions.select.available).toBe(true); + const newest = await f.review(); + await f.pool.query( + 'UPDATE backtests SET name=\'Changed template\',strategy_parameters=\'{"fastPeriod":1,"slowPeriod":4}\' WHERE id=$1', + [f.draft.id] + ); + const selectActor = actor(), + selectBody = { previewHash: start.preview.previewHash }; + const selected = await f.validations.select(id, selectBody, selectActor); + expect(selected.receipt.operation).toBe('select-and-admit-holdouts'); + const selection = selected.validation.selection!; + expect(selection.training.map(e => e.sourceCandidateIndex)).toEqual([0, 1]); + expect(selection.reviewId).toBe(newest.id); + expect(selection.training.every(e => e.metrics.totalReturn !== null)).toBe(true); + const ranked = [...selection.training].sort( + (a, b) => + b.metrics.totalReturn! - a.metrics.totalReturn! || + a.sourceCandidateIndex - b.sourceCandidateIndex + ); + expect(selection.winner.index).toBe(ranked[0]!.sourceCandidateIndex); + for (const phase of selected.validation.phases.slice(1)) { + expect(phase.experiment!.trials).toHaveLength(1); + expect(phase.experiment!.name).toBe(f.input.name + ' · ' + phase.phase); + expect(phase.experiment!.preview.request.strategy.reviewId).toBe(newest.id); + expect( + validationEqual( + phase.experiment!.preview.request.strategy.selection.parameters, + selection.winner.parameters + ) + ).toBe(true); + expect(phase.experiment!.preview.request.name).toBe(start.preview.source.request.name); + await f.execute(phase.experiment!.trials[0]!.runId!); + } + expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual( + selected.receipt + ); + await expect(f.validations.select(id, selectBody, actor())).rejects.toThrow('another receipt'); + await f.review('revoke'); + await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ + f.version.strategyId, + ]); + await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); + const finalActor = actor(), + finalBody = { + previewHash: start.preview.previewHash, + selectionHash: selection.selectionHash, + }; + const finalized = await f.validations.finalize(id, finalBody, finalActor), + report = finalized.validation.report!; + expect(report.training).toEqual(selection.training); + expect(report.validation.sourceCandidateIndex).toBe(selection.winner.index); + expect(report.test.sourceCandidateIndex).toBe(selection.winner.index); + expect(report.validation.parameters).toEqual(report.test.parameters); + expect(report.reset).toBe('initial-capital-empty-positions'); + expect(finalized.validation.stage).toBe('reported'); + expect((await f.validations.get(id)).report).toEqual(report); + await f.validations.cancel(id); + expect((await f.validations.finalize(id, finalBody, finalActor)).receipt).toEqual( + finalized.receipt + ); + expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual( + selected.receipt + ); + expect((await f.validations.submit(start.body, start.identity)).id).toBe(id); + await expect(f.validations.finalize(id, finalBody, actor())).rejects.toThrow('another receipt'); + expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(4); + expect( + (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n + ).toBe(3); + for (const field of [ + 'validation_manifest', + 'validation_selection', + 'validation_report', + 'validation_phase', + ]) { + await expect( + f.pool.query(`UPDATE research_experiments SET ${field}=NULL WHERE id=$1`, [id]) + ).rejects.toThrow(); + } + }, 60_000); + test('ordinary and direct SQL cancellation latch the whole workflow, including pending heldout claims', async () => { + const f = await fixture(), + first = await submit(f); + await f.experiments.cancel(first.validation.id); + expect( + (await f.validations.get(first.validation.id)).phases[0].experiment!.trials.every( + t => t.status === 'cancelled' + ) + ).toBe(true); + await expect( + f.validations.select(first.validation.id, { previewHash: first.preview.previewHash }, actor()) + ).rejects.toThrow('uncancelled'); + const second = await submit(f); + await train(f, second.validation.id); + const selected = await f.validations.select( + second.validation.id, + { previewHash: second.preview.previewHash }, + actor() + ); + await f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [ + second.validation.id, + ]); + const detail = await f.validations.get(second.validation.id); + expect(detail.phases.every(p => p.experiment!.cancelRequested)).toBe(true); + for (const child of selected.validation.phases.slice(1)) { + const id = child.experiment!.trials[0]!.runId!; + await f.execute(id); + expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe( + 'cancelled' + ); + } + await expect( + f.validations.finalize( + detail.id, + { previewHash: detail.previewHash, selectionHash: detail.selection!.selectionHash }, + actor() + ) + ).rejects.toThrow('uncancelled'); + await expect( + f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [ + detail.id, + ]) + ).rejects.toThrow(); + }, 60_000); + test('a corrupted heldout dataset or numerically forged training analytics cannot seal selection', async () => { + const f = await fixture(), + start = await submit(f); + await train(f, start.validation.id); + const heldout = start.preview.partitions[1].dataset.hash; + await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER'); + await f.pool.query( + "UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1", + [heldout] + ); + await expect( + f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow('content validation'); + expect((await f.validations.get(start.validation.id)).selection).toBeNull(); + const sourceDataset = ( + await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [ + start.preview.source.dataset.hash, + ]) + ).rows[0].payload; + const { prepareChronologicalValidation } = await import( + '../../apps/stock/web-api/src/services/validation-preview' + ); + const prepared = prepareChronologicalValidation(f.input, start.preview.source, sourceDataset); + await f.pool.query('UPDATE backtest_datasets SET payload=$2 WHERE hash=$1', [ + heldout, + prepared.datasets.validation, + ]); + const runId = start.validation.phases[0].experiment!.trials[0]!.runId!; + await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); + await f.pool.query( + "UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','900') WHERE run_id=$1", + [runId] + ); + await expect( + f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow('analytics validation'); + expect((await f.validations.get(start.validation.id)).selection).toBeNull(); + expect( + (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n + ).toBe(1); + }, 60_000); +}); + +async function selectionDocument(f: Awaited>, validationId: string) { + const detail = await f.validations.get(validationId), + training = []; + for (const trial of detail.phases[0].experiment!.trials) { + const result = (await f.api.getRunResults(trial.runId!)) as CanonicalRunResult; + training.push(validationEvidence('train', validationId, trial, trial.index, result)); + } + const manifest = { + version: 'chronological-validation-selection/v1' as const, + id: randomUUID(), + validationId, + previewHash: detail.previewHash, + createdAt: new Date().toISOString(), + principal: 'operator' as const, + reviewId: (await f.catalog.getVersionReviews(f.version.id)).at(-1)!.id, + winner: selectValidationWinner(detail.preview.source.candidates, training), + training, + holdoutExperimentIds: { validation: randomUUID(), test: randomUUID() }, + }; + return { + ...manifest, + selectionHash: experimentHash(manifest), + _receipt: { key: randomUUID(), hash: 'a'.repeat(64) }, + }; +} + +describe.skipIf(!url)('durable validation adversarial boundaries', () => { + test('first/idempotent SQL24 upgrade preserves ordinary requests/results/receipts and active leases', async () => { + const f = await fixture(1, false); + await f.review(); + const ordinaryInput = { + backtestId: f.draft.id, + name: 'Existing ordinary sweep', + grid: { fastPeriod: [1, 2] }, + }; + const preview = await f.experiments.preview(ordinaryInput); + const ordinary = await f.experiments.submit( + { ...ordinaryInput, previewHash: preview.previewHash }, + actor() + ); + await f.execute(ordinary.trials[0]!.runId!); + const pending = ordinary.trials[1]!.runId!, + request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending])) + .rows[0].request_snapshot; + await f.repository.startCanonical(request); + const before = await f.snapshot(); + const names = [ + 'require_active_backtest_for_new_run', + 'require_experiment_retry_failure', + 'guard_manual_trial_retry', + 'require_consumed_trial_retry', + ]; + const functionBodies = async () => + ( + await f.pool.query( + 'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace AND proname=ANY($1) ORDER BY proname', + [names] + ) + ).rows; + const priorFunctions = await functionBodies(); + const migration = readFileSync( + new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), + 'utf8' + ); + await f.pool.query(migration); + const after = await f.snapshot(); + after.research_experiments = (after.research_experiments as Record[]).map( + ({ + validation_manifest: _manifest, + validation_parent_id: _parent, + validation_phase: _phase, + validation_selection: _selection, + validation_report: _report, + ...row + }) => row + ); + expect(after).toEqual(before); + expect(await functionBodies()).toEqual(priorFunctions); + const first = await f.snapshot(); + await f.pool.query(migration); + expect(await f.snapshot()).toEqual(first); + expect((await f.experiments.list())[0]!.id).toBe(ordinary.id); + const current = await submit(f); + expect(current.validation.stage).toBe('training'); + expect( + (await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0] + ).toMatchObject({ status: 'running', attempt_number: 1 }); + }, 60_000); + test('SQL independently rejects mixed shapes, changed source/slice/policy, premature or incorrect winners and incomplete commits', async () => { + const f = await fixture(), + start = await submit(f), + id = start.validation.id; + const sourceRow = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [id])) + .rows[0]; + const insertRoot = async ( + manifest: ChronologicalValidationPreview, + phase: string | null = 'train' + ) => { + const trainPreview = validationPhasePreview(manifest, 'train'); + return f.pool.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,'operator',$6,$7,$8,$9)`, + [ + randomUUID(), + f.draft.id, + trainPreview.input.name, + trainPreview, + trainPreview.previewHash, + randomUUID(), + 'a'.repeat(64), + manifest, + phase, + ] + ); + }; + for (const mutate of [ + (p: ChronologicalValidationPreview) => { + p.source.request.policy.matching.risk.feeRate = + '0.02000000' as typeof p.source.request.policy.matching.risk.feeRate; + }, + (p: ChronologicalValidationPreview) => { + p.partitions[0].request.policy.matching.risk.maxGrossExposure = + '999999.00000000' as (typeof p.partitions)[0]['request']['policy']['matching']['risk']['maxGrossExposure']; + }, + (p: ChronologicalValidationPreview) => { + p.partitions[0].counts.admittedWarmup++; + }, + (p: ChronologicalValidationPreview) => { + p.partitions[0].dataset = structuredClone(p.source.dataset); + }, + (p: ChronologicalValidationPreview) => { + p.input.recipe.train.tradeStart++; + }, + (p: ChronologicalValidationPreview) => { + p.source.candidates[0]!.parameters.fastPeriod = 99; + }, + ]) { + const manifest = structuredClone(start.preview); + mutate(manifest); + await expect(insertRoot(manifest)).rejects.toThrow(); + } + await expect(insertRoot(start.preview, null)).rejects.toThrow(); + // A correct root without its run/outbox set fails at COMMIT, not merely at service validation. + await expect(insertRoot(start.preview)).rejects.toThrow('complete exact run'); + expect( + (await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n + ).toBe(1); + await train(f, id); + const correct = await selectionDocument(f, id); + for (const mutate of [ + (s: typeof correct) => { + s.winner = structuredClone(start.preview.source.candidates[1 - correct.winner.index]!); + }, + (s: typeof correct) => { + s.training[0]!.metrics.totalReturn = 999; + }, + (s: typeof correct) => { + s.training.reverse(); + }, + (s: typeof correct) => { + s.training.pop(); + }, + (s: typeof correct) => { + s.training[0]!.datasetHash = start.preview.partitions[1].dataset.hash; + }, + ]) { + const changed = structuredClone(correct); + mutate(changed); + await expect( + f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [ + id, + changed, + ]) + ).rejects.toThrow(); + } + await expect( + f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [ + id, + correct, + ]) + ).rejects.toThrow('atomically admit both'); + expect((await f.validations.get(id)).selection).toBeNull(); + expect( + ( + await f.pool.query('SELECT preview,submission_key FROM research_experiments WHERE id=$1', [ + id, + ]) + ).rows[0] + ).toEqual({ preview: sourceRow.preview, submission_key: sourceRow.submission_key }); + }, 60_000); + test('injected training/outbox/second-holdout insert failures roll back every new input, receipt and selection', async () => { + const f = await fixture(); + await f.review(); + const preview = await f.experiments.previewValidation(f.input), + body = { ...f.input, previewHash: preview.previewHash }; + const fail = async (table: string, name: string, condition: string) => { + await f.pool.query( + `CREATE OR REPLACE FUNCTION ${name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected ${name}'; END IF; RETURN NEW; END $$` + ); + await f.pool.query( + `CREATE TRIGGER ${name} BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION ${name}()` + ); + }; + for (const [table, condition] of [ + ['runs', 'NEW.trial_index=1'], + ['backtest_dispatch', 'TRUE'], + ]) { + await fail(table!, 'injected_root_failure', condition!); + const before = await f.snapshot(); + await expect(f.validations.submit(body, actor())).rejects.toThrow('Injected'); + expect(await f.snapshot()).toEqual(before); + await f.pool.query(`DROP TRIGGER injected_root_failure ON ${table}`); + } + const root = await f.validations.submit(body, actor()); + await train(f, root.id); + await fail('research_experiments', 'injected_holdout_failure', "NEW.validation_phase='test'"); + const before = await f.snapshot(); + await expect( + f.validations.select(root.id, { previewHash: preview.previewHash }, actor()) + ).rejects.toThrow('Injected'); + expect(await f.snapshot()).toEqual(before); + await f.pool.query('DROP TRIGGER injected_holdout_failure ON research_experiments'); + expect( + (await f.validations.select(root.id, { previewHash: preview.previewHash }, actor())) + .validation.phases + ).toHaveLength(3); + }, 60_000); + test('same and cross-parent receipt races have exactly one atomic owner; conflicting intent never gains children', async () => { + const f = await fixture(5); + await f.review(); + const preview = await f.experiments.previewValidation(f.input), + body = { ...f.input, previewHash: preview.previewHash }, + same = actor(); + const [first, replay] = await Promise.all([ + f.validations.submit(body, same), + f.validations.submit(body, same), + ]); + expect(first.id).toBe(replay.id); + const other = await f.cloneTemplate(), + otherInput = { ...f.input, backtestId: other.id }; + const otherPreview = await f.experiments.previewValidation(otherInput), + otherBody = { ...otherInput, previewHash: otherPreview.previewHash }; + const key = actor(), + results = await Promise.allSettled([ + f.validations.submit(body, key), + f.validations.submit(otherBody, key), + ]); + expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1); + expect(results.filter(r => r.status === 'rejected')).toHaveLength(1); + const second = await f.validations.submit(otherBody, actor()); + await train(f, first.id); + await train(f, second.id); + const action = actor(), + selections = await Promise.allSettled([ + f.validations.select(first.id, { previewHash: preview.previewHash }, action), + f.validations.select(second.id, { previewHash: otherPreview.previewHash }, action), + ]); + expect(selections.filter(r => r.status === 'fulfilled')).toHaveLength(1); + expect(selections.filter(r => r.status === 'rejected')).toHaveLength(1); + const selectedRoot = selections[0]!.status === 'fulfilled' ? first : second; + const selectedBody = { previewHash: selectedRoot.previewHash }; + const a = await f.validations.select(selectedRoot.id, selectedBody, action); + const [b, c] = await Promise.all([ + f.validations.select(selectedRoot.id, selectedBody, action), + f.validations.select(selectedRoot.id, selectedBody, action), + ]); + expect(b.receipt).toEqual(a.receipt); + expect(c.receipt).toEqual(a.receipt); + expect( + ( + await f.pool.query( + "SELECT count(*)::int AS n FROM research_experiments WHERE validation_phase IN ('validation','test')" + ) + ).rows[0].n + ).toBe(2); + }, 60_000); + test('failed training and holdout trials reuse existing manual retry receipts and immutable requests', async () => { + const f = await fixture(), + start = await submit(f), + training = start.validation.phases[0].experiment!.trials[0]!, + runId = training.runId!; + const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) + .rows[0].request_snapshot; + const claim = await f.repository.startCanonical(request); + await f.repository.fail(runId, 'Training fixture failure', claim.attemptId); + await expect( + f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow('Every train'); + await f.experiments.retryTrial( + start.validation.id, + runId, + { expectedAttemptNumber: 1, expectedRetryCount: 0 }, + actor() + ); + await train(f, start.validation.id); + await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); + const selected = await f.validations.select( + start.validation.id, + { previewHash: start.preview.previewHash }, + actor() + ), + child = selected.validation.phases[1].experiment!, + childRun = child.trials[0]!.runId!; + await f.pool.query( + "UPDATE runs SET status='failed',error='Before claim',completed_at=NOW() WHERE id=$1", + [childRun] + ); + await f.experiments.retryTrial( + child.id, + childRun, + { expectedAttemptNumber: 0, expectedRetryCount: 0 }, + actor() + ); + await f.execute(childRun); + await f.execute(selected.validation.phases[2].experiment!.trials[0]!.runId!); + const saved = await f.validations.finalize( + start.validation.id, + { + previewHash: start.preview.previewHash, + selectionHash: selected.validation.selection!.selectionHash, + }, + actor() + ); + expect(saved.validation.report).not.toBeNull(); + expect( + (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] + .request_snapshot + ).toEqual(request); + expect( + (await f.experiments.listTrialRetries(start.validation.id, runId))[0]!.previousAttemptNumber + ).toBe(1); + expect( + (await f.experiments.listTrialRetries(child.id, childRun))[0]!.previousAttemptNumber + ).toBe(0); + }, 60_000); +}); + +describe.skipIf(!url)('durable validation isolation proofs', () => { + test('selection racing direct SQL cancellation leaves no live orphan holdout work', async () => { + const f = await fixture(4), + start = await submit(f); + await train(f, start.validation.id); + const outcomes = await Promise.allSettled([ + f.validations.select( + start.validation.id, + { previewHash: start.preview.previewHash }, + actor() + ), + f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [ + start.validation.id, + ]), + ]); + expect(outcomes[1]!.status).toBe('fulfilled'); + const detail = await f.validations.get(start.validation.id); + expect(detail.cancelRequested).toBe(true); + const children = ( + await f.pool.query( + 'SELECT id,cancel_requested FROM research_experiments WHERE validation_parent_id=$1', + [detail.id] + ) + ).rows; + expect(children.length).toBe(detail.selection ? 2 : 0); + expect(children.every(c => c.cancel_requested)).toBe(true); + const childRuns = ( + await f.pool.query( + 'SELECT r.status,r.cancel_requested FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_parent_id=$1', + [detail.id] + ) + ).rows; + expect(childRuns.every(r => r.status === 'cancelled' && r.cancel_requested)).toBe(true); + expect(detail.report).toBeNull(); + }, 60_000); + test('changing only future test prices cannot change native training scores or frozen winner', async () => { + const f = await fixture(), + first = await submit(f); + await train(f, first.validation.id); + const chosen = await f.validations.select( + first.validation.id, + { previewHash: first.preview.previewHash }, + actor() + ); + const changed = chronologicalDataset(900).dataset; + await retainResearchDataset(f.pool, changed); + const template = await f.cloneTemplate(changed), + secondInput = { ...f.input, backtestId: template.id }; + const preview = await f.experiments.previewValidation(secondInput); + const second = await f.validations.submit( + { ...secondInput, previewHash: preview.previewHash }, + actor() + ); + expect(preview.partitions[0].dataset.hash).toBe(first.preview.partitions[0].dataset.hash); + expect(preview.partitions[2].dataset.hash).not.toBe(first.preview.partitions[2].dataset.hash); + await train(f, second.id); + const next = await f.validations.select( + second.id, + { previewHash: preview.previewHash }, + actor() + ); + expect(next.validation.selection!.winner).toEqual(chosen.validation.selection!.winner); + expect(next.validation.selection!.training.map(e => e.metrics)).toEqual( + chosen.validation.selection!.training.map(e => e.metrics) + ); + expect( + ( + await f.pool.query( + "SELECT count(*)::int AS n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_phase IN ('validation','test') AND r.status<>'pending'" + ) + ).rows[0].n + ).toBe(0); + }, 60_000); + test('missing, failed, incomparable and unavailable training candidates each block durable selection', async () => { + const f = await fixture(), + start = await submit(f), + id = start.validation.id, + trial = start.validation.phases[0].experiment!.trials[0]!; + await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); + await f.pool.query( + 'UPDATE runs SET experiment_id=NULL,trial_index=NULL,trial_key=NULL WHERE id=$1', + [trial.runId] + ); + expect((await f.validations.get(id)).phases[0].experiment!.trials[0]!.status).toBe('missing'); + await expect( + f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow('Every train'); + await f.pool.query('UPDATE runs SET experiment_id=$2,trial_index=$3,trial_key=$4 WHERE id=$1', [ + trial.runId, + id, + trial.index, + trial.trialKey, + ]); + await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); + await f.pool.query( + "UPDATE runs SET status='failed',error='Incomplete candidate',completed_at=NOW() WHERE id=$1", + [trial.runId] + ); + await expect( + f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow('Every train'); + await f.experiments.retryTrial( + id, + trial.runId!, + { expectedAttemptNumber: 0, expectedRetryCount: 0 }, + actor() + ); + await train(f, id); + const result = ( + await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [ + trial.runId, + ]) + ).rows[0].canonical_result; + await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER'); + for (const changed of [ + { + ...result, + financial: { + ...result.financial, + identity: { ...result.financial.identity, datasetHash: 'a'.repeat(64) }, + }, + }, + { + ...result, + analytics: { + ...result.analytics, + metrics: { ...result.analytics.metrics, totalReturn: null }, + unavailable: { ...result.analytics.unavailable, totalReturn: 'nonfinite-result' }, + }, + }, + ]) { + await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ + trial.runId, + changed, + ]); + await expect( + f.validations.select(id, { previewHash: start.preview.previewHash }, actor()) + ).rejects.toThrow(); + expect((await f.validations.get(id)).selection).toBeNull(); + expect( + ( + await f.pool.query( + 'SELECT count(*)::int AS n FROM research_experiments WHERE validation_parent_id=$1', + [id] + ) + ).rows[0].n + ).toBe(0); + } + await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [ + trial.runId, + result, + ]); + }, 60_000); +}); diff --git a/test/postgres/chronological-validation.test.ts b/test/postgres/chronological-validation.test.ts index ba826ad3..73d79213 100644 --- a/test/postgres/chronological-validation.test.ts +++ b/test/postgres/chronological-validation.test.ts @@ -68,6 +68,7 @@ async function fixture() { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/dataset-catalog.test.ts b/test/postgres/dataset-catalog.test.ts index 06024ae6..a349d80a 100644 --- a/test/postgres/dataset-catalog.test.ts +++ b/test/postgres/dataset-catalog.test.ts @@ -76,6 +76,7 @@ async function fixture() { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 2cf1a2d9..32ed4e6e 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -87,6 +87,7 @@ async function fixture() { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/experiment-retries.test.ts b/test/postgres/experiment-retries.test.ts index 42b960ad..96b4ebdf 100644 --- a/test/postgres/experiment-retries.test.ts +++ b/test/postgres/experiment-retries.test.ts @@ -69,7 +69,7 @@ async function fixture(poolMax = 4, withRetries = true) { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', - ...(withRetries ? ['23-experiment-retries.sql'] : []), + ...(withRetries ? ['23-experiment-retries.sql', '24-chronological-validation.sql'] : []), ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') @@ -745,6 +745,13 @@ describe.skipIf(!url)('guarded failed experiment trial retry', () => { expect( (await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows ).toEqual(outbox); + // Current services require the later validation columns; verify SQL23 evidence first. + await f.pool.query( + readFileSync( + new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), + 'utf8' + ) + ); expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([]); const accepted = await f.experiments.retryTrial(experimentId, runId, observed(), receipt()); const after = await row(f, runId); diff --git a/test/postgres/experiments.test.ts b/test/postgres/experiments.test.ts index 3dc6bd88..597feef0 100644 --- a/test/postgres/experiments.test.ts +++ b/test/postgres/experiments.test.ts @@ -64,7 +64,9 @@ async function fixture(poolMax = 4, withExperiments = true) { '18-backtest-strategy-versions.sql', '19-canonical-research.sql', '21-run-reproduction.sql', - ...(withExperiments ? ['22-experiments.sql', '23-experiment-retries.sql'] : []), + ...(withExperiments + ? ['22-experiments.sql', '23-experiment-retries.sql', '24-chronological-validation.sql'] + : []), ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') @@ -709,6 +711,12 @@ describe.skipIf(!url)('retained-input experiments', () => { 'utf8' ) ); + await f.pool.query( + readFileSync( + new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url), + 'utf8' + ) + ); const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} }; const preview = await f.experiments.preview(input); expect( diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index ebb22132..64a8a45b 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -26,6 +26,7 @@ const migrations = [ '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { diff --git a/test/postgres/research-retention.test.ts b/test/postgres/research-retention.test.ts index 185196bd..bf0679b0 100644 --- a/test/postgres/research-retention.test.ts +++ b/test/postgres/research-retention.test.ts @@ -29,7 +29,9 @@ const retention = sql('21-run-reproduction.sql') + sql('22-experiments.sql') + '\n' + - sql('23-experiment-retries.sql'); + sql('23-experiment-retries.sql') + + '\n' + + sql('24-chronological-validation.sql'); const request = { name: 'Retained evidence', strategy: 'sma-crossover', diff --git a/test/postgres/research-runtime-isolation.test.ts b/test/postgres/research-runtime-isolation.test.ts index 96e64e54..3c4128bb 100644 --- a/test/postgres/research-runtime-isolation.test.ts +++ b/test/postgres/research-runtime-isolation.test.ts @@ -72,6 +72,7 @@ async function fixture() { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/research-workspace.test.ts b/test/postgres/research-workspace.test.ts index 1d637a3e..c1e12266 100644 --- a/test/postgres/research-workspace.test.ts +++ b/test/postgres/research-workspace.test.ts @@ -63,6 +63,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) { '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', + '24-chronological-validation.sql', ]) { await pool.query(sql(name)); } diff --git a/test/postgres/run-reproduction.test.ts b/test/postgres/run-reproduction.test.ts index 9f421d23..56c2a664 100644 --- a/test/postgres/run-reproduction.test.ts +++ b/test/postgres/run-reproduction.test.ts @@ -62,7 +62,12 @@ async function fixture(poolMax = 4, withReproduction = true) { '18-backtest-strategy-versions.sql', '19-canonical-research.sql', ...(withReproduction - ? ['21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql'] + ? [ + '21-run-reproduction.sql', + '22-experiments.sql', + '23-experiment-retries.sql', + '24-chronological-validation.sql', + ] : []), ]) { await pool.query(