768 lines
28 KiB
TypeScript
768 lines
28 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import type { PoolClient, QueryResultRow } from 'pg';
|
|
import { z } from 'zod';
|
|
import { at } from '@stock-bot/invariants';
|
|
import { validateDatasetV2 } from '@stock-bot/research/datasets';
|
|
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 type { ResearchActor } from '@stock-bot/types';
|
|
import { HistoricalDataRequestError } from '@stock-bot/types';
|
|
import type { BacktestResults } from './backtests/results';
|
|
import { readCanonicalDataset } from './canonical-research.service';
|
|
import {
|
|
ExperimentError,
|
|
experimentHash,
|
|
experimentId,
|
|
experimentReceipt,
|
|
experimentTrialRequest,
|
|
} from './experiment-input';
|
|
import type { ExperimentsService } from './experiments.service';
|
|
import { insertExperimentTrial } from './insert-experiment-trial';
|
|
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
|
|
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,
|
|
collaborators: {
|
|
experiments: Pick<ExperimentsService, 'lockedPreview' | 'readParameterDetail'>;
|
|
results: Pick<BacktestResults, 'getRunResults'>;
|
|
}
|
|
) {
|
|
this.database = requireServices(container, 'postgres').postgres;
|
|
this.experiments = collaborators.experiments;
|
|
this.results = collaborators.results;
|
|
}
|
|
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 => {
|
|
await lockResearchAgent(client, identity.principal);
|
|
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, identity.principal);
|
|
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'
|
|
);
|
|
}
|
|
const id = randomUUID();
|
|
const inserted = await this.admitPrepared(client, prepared, { id, ...identity, hash });
|
|
if (!inserted) {
|
|
const winner = await replay();
|
|
if (!winner) {
|
|
throw new Error('Concurrent validation receipt disappeared');
|
|
}
|
|
return winner;
|
|
}
|
|
return this.readDetail(client, id);
|
|
});
|
|
}
|
|
/** Caller owns the parent lock and transaction; no nested transaction or eligibility shortcut. */
|
|
async admitPrepared(
|
|
client: PoolClient,
|
|
prepared: ReturnType<typeof prepareChronologicalValidation>,
|
|
identity: {
|
|
id: string;
|
|
principal: ResearchActor;
|
|
key: string;
|
|
hash: string;
|
|
membership?: { id: string; index: number };
|
|
}
|
|
): Promise<boolean> {
|
|
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 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,walk_forward_id,walk_forward_index)
|
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'train',$10,$11) ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
|
[
|
|
identity.id,
|
|
prepared.preview.input.backtestId,
|
|
train.input.name,
|
|
train,
|
|
train.previewHash,
|
|
identity.principal,
|
|
identity.key,
|
|
identity.hash,
|
|
prepared.preview,
|
|
identity.membership?.id ?? null,
|
|
identity.membership?.index ?? null,
|
|
]
|
|
);
|
|
if (!inserted.rows.length) {
|
|
return false;
|
|
}
|
|
await this.insertRuns(client, identity.id, train);
|
|
return true;
|
|
}
|
|
async list(backtestId?: string, agentId?: string): Promise<ChronologicalValidationSummary[]> {
|
|
if (backtestId !== undefined) {
|
|
experimentId(backtestId);
|
|
}
|
|
const conditions = ["validation_phase='train'"];
|
|
const values: unknown[] = [];
|
|
if (backtestId !== undefined) {
|
|
values.push(backtestId);
|
|
conditions.push(`backtest_id=$${values.length}`);
|
|
}
|
|
if (agentId !== undefined) {
|
|
values.push(agentId);
|
|
conditions.push(`submission_principal=$${values.length}`);
|
|
}
|
|
const rows = await this.database.query(
|
|
`SELECT * FROM research_experiments WHERE ${conditions.join(' AND ')} ORDER BY created_at DESC,id DESC`,
|
|
values
|
|
);
|
|
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 => {
|
|
await lockResearchAgent(client, identity.principal);
|
|
const replay = () =>
|
|
this.actionReplay(client, 'validation_selection', operation, identity, hash);
|
|
const prior = await replay();
|
|
if (prior) {
|
|
return prior;
|
|
}
|
|
await lockExperimentResearchAgent(client, id, identity.principal, true);
|
|
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 => {
|
|
await lockResearchAgent(client, identity.principal);
|
|
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');
|
|
}
|
|
const { training, validation, test } = await this.verifySelectionEvidence(
|
|
client,
|
|
id,
|
|
selection
|
|
);
|
|
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 verifySelectionEvidence(
|
|
client: PoolClient,
|
|
id: string,
|
|
selection: ChronologicalValidationSelection
|
|
) {
|
|
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
|
|
);
|
|
return { training, validation, test };
|
|
}
|
|
/** Re-verifies every native result behind an immutable member report; no current execution gates. */
|
|
async verifiedSealedReport(
|
|
client: PoolClient,
|
|
id: string
|
|
): Promise<ChronologicalValidationReport> {
|
|
const root = (
|
|
await client.query(
|
|
"SELECT * FROM research_experiments WHERE id=$1 AND validation_phase='train' FOR UPDATE",
|
|
[id]
|
|
)
|
|
).rows[0];
|
|
if (!root || root.cancel_requested || !root.validation_selection || !root.validation_report) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Every walk-forward member needs an uncancelled sealed validation report'
|
|
);
|
|
}
|
|
const preview = retainedValidationPreview(root.validation_manifest);
|
|
const selection = publicValidationDocument<ChronologicalValidationSelection>(
|
|
root.validation_selection,
|
|
'selectionHash'
|
|
);
|
|
const report = publicValidationDocument<ChronologicalValidationReport>(
|
|
root.validation_report,
|
|
'reportHash'
|
|
);
|
|
if (
|
|
report.validationId !== id ||
|
|
report.previewHash !== preview.previewHash ||
|
|
report.selectionHash !== selection.selectionHash
|
|
) {
|
|
throw new Error('Retained member report identity mismatch');
|
|
}
|
|
const evidence = await this.verifySelectionEvidence(client, id, selection);
|
|
if (
|
|
!validationEqual(evidence.training, report.training) ||
|
|
!validationEqual(evidence.validation, report.validation) ||
|
|
!validationEqual(evidence.test, report.test)
|
|
) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Retained member report differs from its verified financial evidence'
|
|
);
|
|
}
|
|
return report;
|
|
}
|
|
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 insertExperimentTrial(client, {
|
|
runId,
|
|
backtestId: preview.input.backtestId,
|
|
runNumber: ++number,
|
|
request,
|
|
experimentId: id,
|
|
trialKey: candidate.trialKey,
|
|
trialIndex: candidate.index,
|
|
});
|
|
}
|
|
}
|
|
private async evidence(
|
|
client: PoolClient,
|
|
id: string,
|
|
phase: ValidationPhase,
|
|
sourceIndex?: number
|
|
): Promise<ValidationResultEvidence[]> {
|
|
const detail = await this.experiments.readParameterDetail(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;
|
|
}
|
|
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.readParameterDetail(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',
|
|
},
|
|
},
|
|
};
|
|
}
|
|
}
|