feat(research): run durable chronological validation and retain reports
This commit is contained in:
parent
67ab30cb7a
commit
abd1c5b83d
42 changed files with 5345 additions and 74 deletions
|
|
@ -63,7 +63,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '20-research-workspace.sql' ||
|
||||
f === '21-run-reproduction.sql' ||
|
||||
f === '22-experiments.sql' ||
|
||||
f === '23-experiment-retries.sql')
|
||||
f === '23-experiment-retries.sql' ||
|
||||
f === '24-chronological-validation.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { z } from 'zod';
|
|||
import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { ChronologicalValidationService } from '../services/chronological-validation.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentId,
|
||||
|
|
@ -12,12 +13,18 @@ import {
|
|||
} from '../services/experiment-input';
|
||||
import { parseExperimentRetry } from '../services/experiment-retry';
|
||||
import { ExperimentsService } from '../services/experiments.service';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
parseValidationSubmission,
|
||||
} from '../services/validation-evidence';
|
||||
import { parseChronologicalValidation } from '../services/validation-preview';
|
||||
|
||||
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
|
||||
export function createExperimentRoutes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const service = new ExperimentsService(container);
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const logger = getLogger('experiments-api');
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
@ -47,6 +54,66 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
const input = parseChronologicalValidation(await body(c.req.raw));
|
||||
return c.json({ preview: await service.previewValidation(input) });
|
||||
});
|
||||
app.post('/api/v2/experiments/validation', async c => {
|
||||
const input = parseValidationSubmission(await body(c.req.raw));
|
||||
const validation = await validations.submit(
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
);
|
||||
c.header('Location', `/api/v2/experiments/validation/${validation.id}`);
|
||||
return c.json({ validation }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments/validation', async c =>
|
||||
c.json({ validations: await validations.list(c.req.query('backtestId')) })
|
||||
);
|
||||
app.get('/api/v2/experiments/validation/:id', async c =>
|
||||
c.json({ validation: await validations.get(experimentId(c.req.param('id'))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/validation/:id/select', async c => {
|
||||
const id = experimentId(c.req.param('id')),
|
||||
input = parseValidationSelection(await body(c.req.raw));
|
||||
return c.json(
|
||||
await validations.select(
|
||||
id,
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
),
|
||||
202
|
||||
);
|
||||
});
|
||||
app.post('/api/v2/experiments/validation/:id/finalize', async c => {
|
||||
const id = experimentId(c.req.param('id')),
|
||||
input = parseValidationFinalization(await body(c.req.raw));
|
||||
return c.json(
|
||||
await validations.finalize(
|
||||
id,
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
),
|
||||
202
|
||||
);
|
||||
});
|
||||
app.post('/api/v2/experiments/validation/:id/cancel', async c => {
|
||||
const id = experimentId(c.req.param('id'));
|
||||
if (
|
||||
!z
|
||||
.object({})
|
||||
.strict()
|
||||
.safeParse(await body(c.req.raw)).success
|
||||
) {
|
||||
throw new ExperimentError(400, 'Cancellation accepts an empty object only');
|
||||
}
|
||||
return c.json({ validation: await validations.cancel(id) });
|
||||
});
|
||||
app.post('/api/v2/experiments/preview', async c => {
|
||||
const input = parseExperimentInput(await body(c.req.raw));
|
||||
return c.json({ preview: await service.preview(input) });
|
||||
|
|
|
|||
|
|
@ -0,0 +1,673 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ChronologicalValidationActionReceipt,
|
||||
ChronologicalValidationActionResult,
|
||||
ChronologicalValidationDetail,
|
||||
ChronologicalValidationReport,
|
||||
ChronologicalValidationSelection,
|
||||
ChronologicalValidationSummary,
|
||||
ValidationPhase,
|
||||
ValidationPhaseState,
|
||||
ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
|
||||
import { BacktestServiceV2 } from './backtest-v2.service';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
experimentTrialRequest,
|
||||
} from './experiment-input';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
parseValidationSubmission,
|
||||
publicValidationDocument,
|
||||
retainedValidationPreview,
|
||||
selectValidationWinner,
|
||||
validationEqual,
|
||||
validationEvidence,
|
||||
validationPhasePreview,
|
||||
type PrivateValidationDocument,
|
||||
} from './validation-evidence';
|
||||
import { prepareChronologicalValidation } from './validation-preview';
|
||||
|
||||
type Actor = { principal: string; key: string };
|
||||
type Operation = 'select-and-admit-holdouts' | 'finalize-report';
|
||||
type Field = 'validation_selection' | 'validation_report';
|
||||
|
||||
const summary = (row: QueryResultRow): ChronologicalValidationSummary => ({
|
||||
id: row.id,
|
||||
name: row.validation_manifest.input.name,
|
||||
backtestId: row.backtest_id,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
cancelRequested: row.cancel_requested,
|
||||
previewHash: row.validation_manifest.previewHash,
|
||||
trainingCandidateCount: row.validation_manifest.source.candidates.length,
|
||||
stage: row.validation_report ? 'reported' : row.validation_selection ? 'holdouts' : 'training',
|
||||
});
|
||||
const receipt = (
|
||||
document: ChronologicalValidationSelection | ChronologicalValidationReport,
|
||||
operation: Operation
|
||||
): ChronologicalValidationActionReceipt => ({
|
||||
id: document.id,
|
||||
validationId: document.validationId,
|
||||
operation,
|
||||
previewHash: document.previewHash,
|
||||
selectionHash: document.selectionHash,
|
||||
createdAt: document.createdAt,
|
||||
principal: document.principal,
|
||||
});
|
||||
/** A bounded staged recipe, using ordinary immutable experiments/runs for every phase. */
|
||||
export class ChronologicalValidationService {
|
||||
private readonly database;
|
||||
private readonly experiments;
|
||||
private readonly results;
|
||||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.experiments = new ExperimentsService(container);
|
||||
this.results = new BacktestServiceV2(container);
|
||||
}
|
||||
async submit(raw: unknown, actor: Actor): Promise<ChronologicalValidationDetail> {
|
||||
const submission = parseValidationSubmission(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const { previewHash, ...input } = submission;
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: 'submit-chronological-validation',
|
||||
submission,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'SELECT id,submission_hash,validation_phase FROM research_experiments WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.submission_hash !== hash || row.validation_phase !== 'train') {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different experiment intent'
|
||||
);
|
||||
}
|
||||
return this.readDetail(client, row.id);
|
||||
};
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const sourceDataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
const prepared = prepareChronologicalValidation(input, source, sourceDataset);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Validation preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
for (const dataset of Object.values(prepared.datasets)) {
|
||||
await client.query(
|
||||
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
|
||||
[dataset.manifest.hash, JSON.stringify(dataset)]
|
||||
);
|
||||
const saved = (
|
||||
await client.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
dataset.manifest.hash,
|
||||
])
|
||||
).rows[0];
|
||||
if (!saved || !validationEqual(validateDatasetV2(saved.payload), dataset)) {
|
||||
throw new Error('Retained validation slice identity mismatch');
|
||||
}
|
||||
}
|
||||
const id = randomUUID(),
|
||||
train = validationPhasePreview(prepared.preview, 'train');
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'train') ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
id,
|
||||
input.backtestId,
|
||||
train.input.name,
|
||||
train,
|
||||
train.previewHash,
|
||||
identity.principal,
|
||||
identity.key,
|
||||
hash,
|
||||
prepared.preview,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent validation receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await this.insertRuns(client, id, train);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<ChronologicalValidationSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT * FROM research_experiments WHERE validation_phase='train' ${backtestId === undefined ? '' : 'AND backtest_id=$1'} ORDER BY created_at DESC,id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(row => {
|
||||
retainedValidationPreview(row.validation_manifest);
|
||||
return summary(row);
|
||||
});
|
||||
}
|
||||
async get(id: string): Promise<ChronologicalValidationDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(client => this.readDetail(client, id));
|
||||
}
|
||||
async cancel(id: string): Promise<ChronologicalValidationDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
await this.lockRoot(client, id);
|
||||
// SQL cascade also covers the existing ordinary cancel endpoint and direct SQL.
|
||||
await client.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [id]);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async select(
|
||||
id: string,
|
||||
raw: unknown,
|
||||
actor: Actor
|
||||
): Promise<ChronologicalValidationActionResult> {
|
||||
experimentId(id);
|
||||
const input = parseValidationSelection(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const operation = 'select-and-admit-holdouts' as const;
|
||||
const hash = experimentHash({ version: 1, operation, validationId: id, input });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = () =>
|
||||
this.actionReplay(client, 'validation_selection', operation, identity, hash);
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
const { root, parent } = await this.lockRoot(client, id);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (root.validation_selection) {
|
||||
throw new ExperimentError(409, 'Selection is already frozen under another receipt');
|
||||
}
|
||||
const preview = retainedValidationPreview(root.validation_manifest);
|
||||
if (preview.previewHash !== input.previewHash) {
|
||||
throw new ExperimentError(409, 'Validation input identity changed');
|
||||
}
|
||||
if (root.cancel_requested || parent.archived_at !== null) {
|
||||
throw new ExperimentError(409, 'Selection requires active uncancelled validation');
|
||||
}
|
||||
await client.query(
|
||||
'SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index FOR UPDATE',
|
||||
[id]
|
||||
);
|
||||
const training = await this.evidence(client, id, 'train');
|
||||
const winner = selectValidationWinner(preview.source.candidates, training);
|
||||
let reviewId;
|
||||
try {
|
||||
reviewId = await verifyReproductionInputs(
|
||||
client,
|
||||
this.container,
|
||||
preview.partitions[0].request
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
throw new ExperimentError(409, error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
for (const partition of preview.partitions.slice(1)) {
|
||||
let dataset;
|
||||
try {
|
||||
dataset = await readCanonicalDataset(client, partition.dataset.hash);
|
||||
} catch (error) {
|
||||
if (error instanceof HistoricalDataRequestError) {
|
||||
throw new ExperimentError(409, error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!validationEqual(dataset.manifest, partition.dataset)) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Retained holdout dataset differs from the frozen validation recipe'
|
||||
);
|
||||
}
|
||||
}
|
||||
const manifest = {
|
||||
version: 'chronological-validation-selection/v1' as const,
|
||||
id: randomUUID(),
|
||||
validationId: id,
|
||||
previewHash: preview.previewHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: identity.principal,
|
||||
reviewId,
|
||||
winner,
|
||||
training,
|
||||
holdoutExperimentIds: { validation: randomUUID(), test: randomUUID() },
|
||||
};
|
||||
const selection: ChronologicalValidationSelection = {
|
||||
...manifest,
|
||||
selectionHash: experimentHash(manifest),
|
||||
};
|
||||
const stored: PrivateValidationDocument<ChronologicalValidationSelection> = {
|
||||
...selection,
|
||||
_receipt: { key: identity.key, hash },
|
||||
};
|
||||
// The operation-scoped advisory lock resolves cross-parent receipt races before a unique-index error aborts the transaction.
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
||||
`validation-select:${identity.principal}:${identity.key}`,
|
||||
]);
|
||||
const race = await replay();
|
||||
if (race) {
|
||||
return race;
|
||||
}
|
||||
await client.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [
|
||||
id,
|
||||
stored,
|
||||
]);
|
||||
for (const phase of ['validation', 'test'] as const) {
|
||||
const childId = selection.holdoutExperimentIds[phase],
|
||||
child = validationPhasePreview(preview, phase, winner, reviewId);
|
||||
await client.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_parent_id,validation_phase)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
|
||||
[
|
||||
childId,
|
||||
root.backtest_id,
|
||||
child.input.name,
|
||||
child,
|
||||
child.previewHash,
|
||||
identity.principal,
|
||||
`validation-child:${childId}`,
|
||||
experimentHash({
|
||||
version: 1,
|
||||
validationId: id,
|
||||
selectionHash: selection.selectionHash,
|
||||
phase,
|
||||
}),
|
||||
id,
|
||||
phase,
|
||||
]
|
||||
);
|
||||
await this.insertRuns(client, childId, child);
|
||||
}
|
||||
return {
|
||||
receipt: receipt(selection, operation),
|
||||
validation: await this.readDetail(client, id),
|
||||
};
|
||||
});
|
||||
}
|
||||
async finalize(
|
||||
id: string,
|
||||
raw: unknown,
|
||||
actor: Actor
|
||||
): Promise<ChronologicalValidationActionResult> {
|
||||
experimentId(id);
|
||||
const input = parseValidationFinalization(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const operation = 'finalize-report' as const,
|
||||
hash = experimentHash({ version: 1, operation, validationId: id, input });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = () =>
|
||||
this.actionReplay(client, 'validation_report', operation, identity, hash);
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
const { root } = await this.lockRoot(client, id);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (root.validation_report) {
|
||||
throw new ExperimentError(409, 'Report is already sealed under another receipt');
|
||||
}
|
||||
const preview = retainedValidationPreview(root.validation_manifest);
|
||||
if (root.cancel_requested || !root.validation_selection) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Finalization requires uncancelled validation with frozen selection'
|
||||
);
|
||||
}
|
||||
const selection = publicValidationDocument<ChronologicalValidationSelection>(
|
||||
root.validation_selection,
|
||||
'selectionHash'
|
||||
);
|
||||
if (
|
||||
input.previewHash !== preview.previewHash ||
|
||||
input.selectionHash !== selection.selectionHash
|
||||
) {
|
||||
throw new ExperimentError(409, 'Validation or selection identity changed');
|
||||
}
|
||||
for (const childId of [
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query('SELECT id FROM research_experiments WHERE id=$1 FOR UPDATE', [childId]);
|
||||
}
|
||||
for (const experimentId of [
|
||||
id,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
selection.holdoutExperimentIds.test,
|
||||
]) {
|
||||
await client.query(
|
||||
'SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index FOR UPDATE',
|
||||
[experimentId]
|
||||
);
|
||||
}
|
||||
const training = await this.evidence(client, id, 'train');
|
||||
if (!validationEqual(training, selection.training)) {
|
||||
throw new ExperimentError(409, 'Training evidence differs from the frozen selection');
|
||||
}
|
||||
const validation = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.validation,
|
||||
'validation',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
const test = at(
|
||||
await this.evidence(
|
||||
client,
|
||||
selection.holdoutExperimentIds.test,
|
||||
'test',
|
||||
selection.winner.index
|
||||
),
|
||||
0
|
||||
);
|
||||
const manifest = {
|
||||
version: 'chronological-validation-report/v1' as const,
|
||||
id: randomUUID(),
|
||||
validationId: id,
|
||||
previewHash: preview.previewHash,
|
||||
selectionHash: selection.selectionHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: identity.principal,
|
||||
reset: 'initial-capital-empty-positions' as const,
|
||||
training,
|
||||
validation,
|
||||
test,
|
||||
limitations: [
|
||||
'Independent accounts reset initial capital and positions for every phase; no continuous portfolio curve is implied.',
|
||||
'This workflow selects using training evidence only. It does not certify that the source data was never inspected elsewhere.',
|
||||
'Completed execution is not proof of profitability or statistical adequacy.',
|
||||
],
|
||||
};
|
||||
const report: ChronologicalValidationReport = {
|
||||
...manifest,
|
||||
reportHash: experimentHash(manifest),
|
||||
};
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
||||
`validation-finalize:${identity.principal}:${identity.key}`,
|
||||
]);
|
||||
const race = await replay();
|
||||
if (race) {
|
||||
return race;
|
||||
}
|
||||
await client.query('UPDATE research_experiments SET validation_report=$2 WHERE id=$1', [
|
||||
id,
|
||||
{ ...report, _receipt: { key: identity.key, hash } },
|
||||
]);
|
||||
return { receipt: receipt(report, operation), validation: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async lockRoot(client: PoolClient, id: string) {
|
||||
const parent = (
|
||||
await client.query(
|
||||
"SELECT id,archived_at FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=$1 AND validation_phase='train') FOR UPDATE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Chronological validation not found');
|
||||
}
|
||||
const root = (
|
||||
await client.query(
|
||||
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR UPDATE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!root) {
|
||||
throw new ExperimentError(404, 'Chronological validation not found');
|
||||
}
|
||||
return { root, parent };
|
||||
}
|
||||
private async actionReplay(
|
||||
client: PoolClient,
|
||||
field: Field,
|
||||
operation: Operation,
|
||||
identity: ReturnType<typeof experimentReceipt>,
|
||||
hash: string
|
||||
): Promise<ChronologicalValidationActionResult | null> {
|
||||
const row = (
|
||||
await client.query(
|
||||
`SELECT id,${field} AS document FROM research_experiments WHERE ${field}->>'principal'=$1 AND ${field}#>>'{_receipt,key}'=$2`,
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.document._receipt.hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different validation action'
|
||||
);
|
||||
}
|
||||
const document = publicValidationDocument<
|
||||
ChronologicalValidationSelection | ChronologicalValidationReport
|
||||
>(row.document, field === 'validation_selection' ? 'selectionHash' : 'reportHash');
|
||||
return {
|
||||
receipt: receipt(document, operation),
|
||||
validation: await this.readDetail(client, row.id),
|
||||
};
|
||||
}
|
||||
private async insertRuns(client: PoolClient, id: string, preview: ExperimentPreview) {
|
||||
let number = Number(
|
||||
(
|
||||
await client.query(
|
||||
'SELECT COALESCE(MAX(run_number),0) AS n FROM runs WHERE backtest_id=$1',
|
||||
[preview.input.backtestId]
|
||||
)
|
||||
).rows[0].n
|
||||
);
|
||||
for (const candidate of preview.candidates) {
|
||||
const runId = randomUUID(),
|
||||
request = experimentTrialRequest(preview, candidate, runId);
|
||||
await client.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
||||
[
|
||||
runId,
|
||||
preview.input.backtestId,
|
||||
++number,
|
||||
request,
|
||||
request.datasetHash,
|
||||
id,
|
||||
candidate.trialKey,
|
||||
candidate.index,
|
||||
]
|
||||
);
|
||||
await client.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
}
|
||||
}
|
||||
private async evidence(
|
||||
client: PoolClient,
|
||||
id: string,
|
||||
phase: ValidationPhase,
|
||||
sourceIndex?: number
|
||||
): Promise<ValidationResultEvidence[]> {
|
||||
const detail = await this.experiments.readDetail(client, id);
|
||||
if (
|
||||
detail.cancelRequested ||
|
||||
detail.trials.some(
|
||||
t => t.cancelRequested || t.status !== 'completed' || !t.comparable || !t.runId
|
||||
)
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
`Every ${phase} trial must be complete, uncancelled and comparable`
|
||||
);
|
||||
}
|
||||
const evidence: ValidationResultEvidence[] = [];
|
||||
for (const trial of detail.trials) {
|
||||
const runId = trial.runId;
|
||||
if (!runId) {
|
||||
throw new ExperimentError(409, 'Expected phase run is missing');
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = await this.results.getRunResults(runId, client);
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof z.ZodError ||
|
||||
(error instanceof Error &&
|
||||
(error.message === 'Saved canonical result does not match its admitted request' ||
|
||||
error.message.startsWith('Native replay ')))
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
`Retained ${phase} result failed financial or analytics validation`
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
|
||||
throw new ExperimentError(409, `Retained ${phase} result is unavailable`);
|
||||
}
|
||||
if (!validationEqual(result.request, experimentTrialRequest(detail.preview, trial, runId))) {
|
||||
throw new ExperimentError(409, `Retained ${phase} result input mismatch`);
|
||||
}
|
||||
evidence.push(
|
||||
validationEvidence(
|
||||
phase,
|
||||
id,
|
||||
trial,
|
||||
sourceIndex ?? trial.index,
|
||||
result as CanonicalRunResult
|
||||
)
|
||||
);
|
||||
}
|
||||
return evidence;
|
||||
}
|
||||
private async readDetail(client: PoolClient, id: string): Promise<ChronologicalValidationDetail> {
|
||||
const row = (
|
||||
await client.query(
|
||||
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR SHARE",
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Chronological validation not found');
|
||||
}
|
||||
const preview = retainedValidationPreview(row.validation_manifest);
|
||||
const selection = row.validation_selection
|
||||
? publicValidationDocument<ChronologicalValidationSelection>(
|
||||
row.validation_selection,
|
||||
'selectionHash'
|
||||
)
|
||||
: null;
|
||||
const report = row.validation_report
|
||||
? publicValidationDocument<ChronologicalValidationReport>(row.validation_report, 'reportHash')
|
||||
: null;
|
||||
const phases: ValidationPhaseState[] = [];
|
||||
for (const phase of ['train', 'validation', 'test'] as const) {
|
||||
const expected = phase === 'train' ? id : selection?.holdoutExperimentIds[phase];
|
||||
if (!expected) {
|
||||
phases.push({ phase, status: 'not-admitted', experimentId: null, experiment: null });
|
||||
continue;
|
||||
}
|
||||
const exists =
|
||||
phase === 'train' ||
|
||||
(
|
||||
await client.query(
|
||||
'SELECT id FROM research_experiments WHERE id=$1 AND validation_parent_id=$2 AND validation_phase=$3',
|
||||
[expected, id, phase]
|
||||
)
|
||||
).rows.length > 0;
|
||||
phases.push({
|
||||
phase,
|
||||
status: exists ? 'admitted' : 'missing',
|
||||
experimentId: expected,
|
||||
experiment: exists ? await this.experiments.readDetail(client, expected) : null,
|
||||
});
|
||||
}
|
||||
const ready = (phase: ValidationPhaseState) =>
|
||||
phase.experiment &&
|
||||
!phase.experiment.cancelRequested &&
|
||||
phase.experiment.trials.every(
|
||||
t => t.status === 'completed' && t.comparable && !t.cancelRequested
|
||||
);
|
||||
const trainingPhase = at(phases, 0);
|
||||
const trainingExperiment = trainingPhase.experiment;
|
||||
const canSelect =
|
||||
!row.cancel_requested &&
|
||||
!selection &&
|
||||
!!ready(trainingPhase) &&
|
||||
!!trainingExperiment &&
|
||||
trainingExperiment.trials.every(
|
||||
t => typeof t.metrics?.totalReturn === 'number' && Number.isFinite(t.metrics.totalReturn)
|
||||
);
|
||||
const canFinalize = !row.cancel_requested && !!selection && !report && phases.every(ready);
|
||||
return {
|
||||
...summary(row),
|
||||
preview,
|
||||
phases: phases as ChronologicalValidationDetail['phases'],
|
||||
selection,
|
||||
report,
|
||||
actions: {
|
||||
select: {
|
||||
available: canSelect,
|
||||
reason: canSelect
|
||||
? null
|
||||
: row.cancel_requested
|
||||
? 'Validation is cancelled'
|
||||
: selection
|
||||
? 'Selection is already frozen'
|
||||
: 'Every training candidate needs complete comparable evidence and finite total return',
|
||||
},
|
||||
finalize: {
|
||||
available: canFinalize,
|
||||
reason: canFinalize
|
||||
? null
|
||||
: report
|
||||
? 'Report is already saved'
|
||||
: row.cancel_requested
|
||||
? 'Validation is cancelled'
|
||||
: 'Selection and complete uncancelled phase evidence are required',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -118,10 +118,7 @@ export class ExperimentsService {
|
|||
return prepareChronologicalValidation(input, source, dataset).preview;
|
||||
});
|
||||
}
|
||||
private async lockedPreview(
|
||||
client: PoolClient,
|
||||
input: ExperimentInput
|
||||
): Promise<ExperimentPreview> {
|
||||
async lockedPreview(client: PoolClient, input: ExperimentInput): Promise<ExperimentPreview> {
|
||||
const parent = (
|
||||
await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId])
|
||||
).rows[0];
|
||||
|
|
@ -272,7 +269,7 @@ export class ExperimentsService {
|
|||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT ${summaryColumns} FROM research_experiments e
|
||||
${backtestId === undefined ? '' : 'WHERE e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
WHERE e.validation_phase IS NULL ${backtestId === undefined ? '' : 'AND e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(summary);
|
||||
|
|
@ -482,7 +479,7 @@ export class ExperimentsService {
|
|||
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
const row = (
|
||||
await database.query(
|
||||
`SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`,
|
||||
|
|
|
|||
182
apps/stock/web-api/src/services/validation-evidence.ts
Normal file
182
apps/stock/web-api/src/services/validation-evidence.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { z } from 'zod';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
chronologicalValidationFinalizationSchema,
|
||||
chronologicalValidationSelectionSchema,
|
||||
chronologicalValidationSubmissionSchema,
|
||||
type ChronologicalValidationPreview,
|
||||
type ChronologicalValidationReport,
|
||||
type ChronologicalValidationSelection,
|
||||
type ValidationPhase,
|
||||
type ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
|
||||
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { canonicalReproductionHash } from './reproduction-comparison';
|
||||
import { parseChronologicalValidation } from './validation-preview';
|
||||
|
||||
export const validationEqual = (a: unknown, b: unknown) =>
|
||||
a !== undefined && b !== undefined && canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
export function parseValidationSubmission(raw: unknown) {
|
||||
return parse(chronologicalValidationSubmissionSchema, raw);
|
||||
}
|
||||
export function parseValidationSelection(raw: unknown) {
|
||||
return parse(chronologicalValidationSelectionSchema, raw);
|
||||
}
|
||||
export function parseValidationFinalization(raw: unknown) {
|
||||
return parse(chronologicalValidationFinalizationSchema, raw);
|
||||
}
|
||||
function parse<T extends z.ZodTypeAny>(schema: T, raw: unknown): z.infer<T> {
|
||||
try {
|
||||
assertStrategyJsonText(raw);
|
||||
return schema.parse(raw);
|
||||
} catch {
|
||||
throw new ExperimentError(400, 'Invalid chronological validation operation');
|
||||
}
|
||||
}
|
||||
export function retainedValidationPreview(value: unknown): ChronologicalValidationPreview {
|
||||
const preview = value as ChronologicalValidationPreview;
|
||||
const { previewHash, ...manifest } = preview;
|
||||
if (
|
||||
preview.version !== 'chronological-validation-preview/v1' ||
|
||||
preview.execution !== 'preview-only' ||
|
||||
experimentHash(manifest) !== previewHash
|
||||
) {
|
||||
throw new Error('Retained validation preparation integrity failure');
|
||||
}
|
||||
parseChronologicalValidation(preview.input);
|
||||
retainedExperimentPreview(preview.source);
|
||||
if (preview.partitions.length !== 3) {
|
||||
throw new Error('Retained validation phase identity mismatch');
|
||||
}
|
||||
for (const [index, phase] of (['train', 'validation', 'test'] as const).entries()) {
|
||||
const partition = at(preview.partitions, index);
|
||||
if (
|
||||
partition.phase !== phase ||
|
||||
partition.request.datasetHash !== partition.dataset.hash ||
|
||||
!validationEqual(partition.dataset.bounds, preview.input.recipe[phase])
|
||||
) {
|
||||
throw new Error('Retained validation phase identity mismatch');
|
||||
}
|
||||
canonicalRunRequestSchema.parse(partition.request);
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
export function validationPhasePreview(
|
||||
preview: ChronologicalValidationPreview,
|
||||
phase: ValidationPhase,
|
||||
winner?: ExperimentCandidate,
|
||||
reviewId?: string
|
||||
) {
|
||||
const partition = preview.partitions.find(p => p.phase === phase);
|
||||
if (!partition) {
|
||||
throw new Error('Missing prepared validation phase');
|
||||
}
|
||||
const request = structuredClone(partition.request);
|
||||
if (phase !== 'train') {
|
||||
if (!winner || !reviewId) {
|
||||
throw new Error('Holdout admission requires a frozen winner and current approval');
|
||||
}
|
||||
request.strategy.selection.parameters = structuredClone(
|
||||
winner.parameters
|
||||
) as typeof request.strategy.selection.parameters;
|
||||
request.strategy.reviewId = reviewId;
|
||||
}
|
||||
return buildExperimentPreview(
|
||||
{
|
||||
backtestId: preview.input.backtestId,
|
||||
name: `${preview.input.name} · ${phase}`,
|
||||
grid: phase === 'train' ? preview.input.grid : {},
|
||||
},
|
||||
canonicalRunRequestSchema.parse(request),
|
||||
partition.dataset
|
||||
);
|
||||
}
|
||||
export function validationEvidence(
|
||||
phase: ValidationPhase,
|
||||
experimentId: string,
|
||||
candidate: ExperimentCandidate,
|
||||
sourceCandidateIndex: number,
|
||||
result: CanonicalRunResult
|
||||
): ValidationResultEvidence {
|
||||
return {
|
||||
phase,
|
||||
experimentId,
|
||||
runId: result.runId,
|
||||
sourceCandidateIndex,
|
||||
trialKey: candidate.trialKey,
|
||||
parameters: candidate.parameters,
|
||||
datasetHash: result.request.datasetHash,
|
||||
requestHash: experimentHash(result.request),
|
||||
economicHash: canonicalReproductionHash(result),
|
||||
metrics: result.analytics.metrics,
|
||||
unavailable: result.analytics.unavailable,
|
||||
completePeriodCount: result.analytics.completePeriodCount,
|
||||
periodicSampleCount: result.analytics.periodicSampleCount,
|
||||
fillCount: result.analytics.fillCount,
|
||||
limitations: [...result.financial.limitations, ...result.financial.modelLimitations],
|
||||
};
|
||||
}
|
||||
export function selectValidationWinner(
|
||||
candidates: ExperimentCandidate[],
|
||||
evidence: ValidationResultEvidence[]
|
||||
): ExperimentCandidate {
|
||||
if (
|
||||
candidates.length !== evidence.length ||
|
||||
!candidates.length ||
|
||||
candidates.some((candidate, index) => {
|
||||
const item = evidence[index];
|
||||
return (
|
||||
candidate.index !== index ||
|
||||
!item ||
|
||||
item.phase !== 'train' ||
|
||||
item.sourceCandidateIndex !== candidate.index ||
|
||||
item.trialKey !== candidate.trialKey ||
|
||||
!validationEqual(item.parameters, candidate.parameters) ||
|
||||
typeof item.metrics.totalReturn !== 'number' ||
|
||||
!Number.isFinite(item.metrics.totalReturn)
|
||||
);
|
||||
})
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Every training candidate needs complete comparable evidence and a finite total return'
|
||||
);
|
||||
}
|
||||
let winner = at(candidates, 0),
|
||||
bestScore = Number.NEGATIVE_INFINITY;
|
||||
for (const candidate of candidates) {
|
||||
const score = at(evidence, candidate.index).metrics.totalReturn;
|
||||
if (typeof score !== 'number' || !Number.isFinite(score)) {
|
||||
throw new ExperimentError(409, 'Training return is unavailable');
|
||||
}
|
||||
if (score > bestScore) {
|
||||
winner = candidate;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
export type PrivateValidationDocument<T> = T & { _receipt: { key: string; hash: string } };
|
||||
export function publicValidationDocument<
|
||||
T extends ChronologicalValidationSelection | ChronologicalValidationReport,
|
||||
>(value: PrivateValidationDocument<T>, key: 'selectionHash' | 'reportHash'): T {
|
||||
const { _receipt, ...document } = value;
|
||||
const manifest: Record<string, unknown> = { ...document };
|
||||
const hash = manifest[key];
|
||||
delete manifest[key];
|
||||
if (!_receipt || experimentHash(manifest) !== hash) {
|
||||
throw new Error('Retained validation evidence integrity failure');
|
||||
}
|
||||
return document as unknown as T;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue