342 lines
13 KiB
TypeScript
342 lines
13 KiB
TypeScript
import type { QueryResultRow } from 'pg';
|
|
import { at } from '@stock-bot/invariants';
|
|
import {
|
|
isCanonicalRunResult,
|
|
type CanonicalRunResult,
|
|
type ResearchRunResult,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import type {
|
|
ChronologicalValidationReport,
|
|
ChronologicalValidationSelection,
|
|
ValidationPhase,
|
|
} from '@stock-bot/stock-config/chronological-validation';
|
|
import type { WorkbenchExperimentPreview } from '@stock-bot/stock-config/cost-sensitivity';
|
|
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
|
|
import type { WalkForwardSegment } from '@stock-bot/stock-config/walk-forward';
|
|
import { isResearchActor } from '@stock-bot/types';
|
|
import type { ResearchEvidenceReference, ResearchFindingSource } from '@stock-bot/types';
|
|
import type { BacktestResultQuery } from './backtest-v2.service';
|
|
import { retainedWorkbenchPreview, workbenchTrialRequest } from './cost-sensitivity-input';
|
|
import { ResearchError } from './research-errors';
|
|
import {
|
|
publicValidationDocument,
|
|
retainedValidationPreview,
|
|
selectValidationWinner,
|
|
validationEqual,
|
|
validationEvidence,
|
|
validationPhasePreview,
|
|
} from './validation-evidence';
|
|
import { publicWalkForwardReport, retainedWalkForwardPreview } from './walk-forward-input';
|
|
|
|
function retained(condition: unknown, message: string): asserts condition {
|
|
if (!condition) {
|
|
throw new Error(`Retained finding source ${message}`);
|
|
}
|
|
}
|
|
function requested(condition: unknown, message: string): asserts condition {
|
|
if (!condition) {
|
|
throw new ResearchError(422, message);
|
|
}
|
|
}
|
|
function documentMetadata(value: Record<string, unknown>, report: boolean): void {
|
|
const receipt = value._receipt as { key?: unknown; hash?: unknown } | undefined;
|
|
retained(
|
|
typeof value.id === 'string' &&
|
|
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.id) &&
|
|
typeof value.createdAt === 'string' &&
|
|
Number.isFinite(Date.parse(value.createdAt)) &&
|
|
isResearchActor(value.principal) &&
|
|
typeof receipt?.key === 'string' &&
|
|
/^[!-~]{1,200}$/.test(receipt.key) &&
|
|
typeof receipt.hash === 'string' &&
|
|
/^[a-f0-9]{64}$/.test(receipt.hash) &&
|
|
(!report ||
|
|
(Array.isArray(value.limitations) &&
|
|
value.limitations.every(item => typeof item === 'string'))),
|
|
'document metadata is invalid'
|
|
);
|
|
}
|
|
type ResultReader = (
|
|
id: string,
|
|
database: BacktestResultQuery
|
|
) => Promise<ResearchRunResult | null>;
|
|
|
|
/** Historical provenance only. The existing canonical reader owns all financial validation. */
|
|
export async function verifyResearchSource(
|
|
source: ResearchFindingSource,
|
|
references: ResearchEvidenceReference[],
|
|
database: BacktestResultQuery,
|
|
readResult: ResultReader
|
|
): Promise<Map<string, CanonicalRunResult>> {
|
|
requested(
|
|
references.length > 0 && references.every(r => r.metricsVersion === 'canonical-analytics/v1'),
|
|
'A finding source requires at least one canonical metric reference'
|
|
);
|
|
const results = new Map<string, CanonicalRunResult>();
|
|
const experiment = async (id: string) =>
|
|
(await database.query('SELECT * FROM research_experiments WHERE id=$1', [id])).rows[0];
|
|
const previewOf = (row: QueryResultRow): WorkbenchExperimentPreview => {
|
|
const preview = retainedWorkbenchPreview(row.preview);
|
|
retained(
|
|
preview.previewHash === row.preview_hash &&
|
|
preview.input.backtestId === row.backtest_id &&
|
|
preview.input.name === row.name,
|
|
'experiment identity mismatch'
|
|
);
|
|
return preview;
|
|
};
|
|
const resultOf = async (
|
|
row: QueryResultRow,
|
|
preview: WorkbenchExperimentPreview,
|
|
candidate: ExperimentCandidate
|
|
) => {
|
|
retained(
|
|
row.status === 'completed' &&
|
|
row.backtest_id === preview.input.backtestId &&
|
|
row.trial_key === candidate.trialKey &&
|
|
row.trial_index === candidate.index,
|
|
'completed trial identity mismatch'
|
|
);
|
|
const request = workbenchTrialRequest(preview, candidate, row.id);
|
|
retained(
|
|
validationEqual(row.request_snapshot, request) && row.dataset_hash === request.datasetHash,
|
|
'trial request mismatch'
|
|
);
|
|
let result = results.get(row.id);
|
|
if (!result) {
|
|
const saved = await readResult(row.id, database);
|
|
retained(
|
|
saved &&
|
|
isCanonicalRunResult(saved) &&
|
|
saved.runId === row.id &&
|
|
saved.backtestId === row.backtest_id &&
|
|
saved.status === 'completed',
|
|
'canonical result unavailable'
|
|
);
|
|
result = saved;
|
|
results.set(row.id, result);
|
|
}
|
|
retained(validationEqual(result.request, request), 'result request mismatch');
|
|
return result;
|
|
};
|
|
const phaseEvidence = async (
|
|
row: QueryResultRow,
|
|
phase: ValidationPhase,
|
|
sourceIndex?: number
|
|
) => {
|
|
const preview = previewOf(row);
|
|
retained(
|
|
preview.version === 'research-experiment-preview/v1' && row.validation_phase === phase,
|
|
'phase kind mismatch'
|
|
);
|
|
const runs = (
|
|
await database.query('SELECT * FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [
|
|
row.id,
|
|
])
|
|
).rows;
|
|
retained(runs.length === preview.candidates.length, 'phase run count mismatch');
|
|
const evidence = [];
|
|
for (const [index, candidate] of preview.candidates.entries()) {
|
|
const run = at(runs, index);
|
|
const result = await resultOf(run, preview, candidate);
|
|
evidence.push(
|
|
validationEvidence(phase, row.id, candidate, sourceIndex ?? candidate.index, result)
|
|
);
|
|
}
|
|
return evidence;
|
|
};
|
|
const chronological = async (root: QueryResultRow): Promise<ChronologicalValidationReport> => {
|
|
retained(
|
|
root.validation_phase === 'train' &&
|
|
root.validation_parent_id === null &&
|
|
root.validation_selection &&
|
|
root.validation_report,
|
|
'sealed chronological report unavailable'
|
|
);
|
|
documentMetadata(root.validation_selection, false);
|
|
documentMetadata(root.validation_report, true);
|
|
const preview = retainedValidationPreview(root.validation_manifest);
|
|
const selection = publicValidationDocument<ChronologicalValidationSelection>(
|
|
root.validation_selection,
|
|
'selectionHash'
|
|
);
|
|
const report = publicValidationDocument<ChronologicalValidationReport>(
|
|
root.validation_report,
|
|
'reportHash'
|
|
);
|
|
retained(
|
|
preview.input.backtestId === root.backtest_id &&
|
|
validationEqual(previewOf(root), validationPhasePreview(preview, 'train')),
|
|
'training preview mismatch'
|
|
);
|
|
retained(
|
|
selection.version === 'chronological-validation-selection/v1' &&
|
|
selection.validationId === root.id &&
|
|
selection.previewHash === preview.previewHash &&
|
|
report.version === 'chronological-validation-report/v1' &&
|
|
report.validationId === root.id &&
|
|
report.previewHash === preview.previewHash &&
|
|
report.selectionHash === selection.selectionHash &&
|
|
report.reset === 'initial-capital-empty-positions',
|
|
'chronological report identity mismatch'
|
|
);
|
|
const training = await phaseEvidence(root, 'train');
|
|
const winner = selectValidationWinner(previewOf(root).candidates, training);
|
|
retained(
|
|
validationEqual(selection.training, training) &&
|
|
validationEqual(report.training, training) &&
|
|
validationEqual(selection.winner, winner),
|
|
'training selection or report mismatch'
|
|
);
|
|
const children = (
|
|
await database.query(
|
|
'SELECT * FROM research_experiments WHERE validation_parent_id=$1 ORDER BY validation_phase',
|
|
[root.id]
|
|
)
|
|
).rows;
|
|
retained(children.length === 2, 'holdout membership mismatch');
|
|
for (const phase of ['validation', 'test'] as const) {
|
|
const child = children.find(
|
|
item => item.id === selection.holdoutExperimentIds[phase] && item.validation_phase === phase
|
|
);
|
|
retained(
|
|
child &&
|
|
child.backtest_id === root.backtest_id &&
|
|
validationEqual(
|
|
previewOf(child),
|
|
validationPhasePreview(preview, phase, winner, selection.reviewId)
|
|
),
|
|
'holdout preview or membership mismatch'
|
|
);
|
|
const evidence = await phaseEvidence(child, phase, winner.index);
|
|
retained(
|
|
evidence.length === 1 && validationEqual(report[phase], at(evidence, 0)),
|
|
'holdout report mismatch'
|
|
);
|
|
}
|
|
return report;
|
|
};
|
|
try {
|
|
let members: Set<string>;
|
|
if (source.kind === 'experiment/v1') {
|
|
const row = await experiment(source.experimentId);
|
|
requested(
|
|
row && row.validation_phase === null,
|
|
'Source must be a retained standalone experiment'
|
|
);
|
|
const preview = previewOf(row);
|
|
requested(
|
|
preview.previewHash === source.previewHash,
|
|
'Source experiment preview does not match'
|
|
);
|
|
members = new Set();
|
|
for (const reference of references) {
|
|
const run = (
|
|
await database.query('SELECT * FROM runs WHERE id=$1 AND experiment_id=$2', [
|
|
reference.runId,
|
|
row.id,
|
|
])
|
|
).rows[0];
|
|
requested(
|
|
run && run.status === 'completed',
|
|
'Evidence must be a completed source experiment trial'
|
|
);
|
|
const candidate = preview.candidates[run.trial_index];
|
|
retained(candidate, 'trial candidate unavailable');
|
|
await resultOf(run, preview, candidate);
|
|
members.add(run.id);
|
|
}
|
|
} else if (source.kind === 'chronological-report/v1') {
|
|
const row = await experiment(source.validationId);
|
|
requested(
|
|
row && row.validation_phase === 'train' && row.validation_report,
|
|
'Source requires a sealed chronological report'
|
|
);
|
|
const report = await chronological(row);
|
|
requested(
|
|
report.id === source.reportId &&
|
|
report.reportHash === source.reportHash &&
|
|
report.previewHash === source.previewHash,
|
|
'Source chronological report does not match'
|
|
);
|
|
members = new Set(
|
|
[...report.training, report.validation, report.test].map(item => item.runId)
|
|
);
|
|
} else {
|
|
const header = (
|
|
await database.query('SELECT * FROM research_walk_forwards WHERE id=$1', [
|
|
source.walkForwardId,
|
|
])
|
|
).rows[0];
|
|
requested(header && header.report, 'Source requires a sealed walk-forward report');
|
|
documentMetadata(header.report, true);
|
|
const preview = retainedWalkForwardPreview(header.preview),
|
|
report = publicWalkForwardReport(header.report);
|
|
retained(
|
|
header.preview_hash === preview.previewHash &&
|
|
header.backtest_id === preview.input.backtestId &&
|
|
header.name === preview.input.name &&
|
|
Array.isArray(header.member_ids) &&
|
|
header.member_ids.length === preview.windows.length &&
|
|
new Set(header.member_ids).size === header.member_ids.length,
|
|
'walk-forward header identity mismatch'
|
|
);
|
|
retained(
|
|
report.version === 'walk-forward-report/v1' &&
|
|
report.walkForwardId === header.id &&
|
|
report.previewHash === preview.previewHash &&
|
|
report.reset === 'initial-capital-empty-positions',
|
|
'walk-forward report identity mismatch'
|
|
);
|
|
requested(
|
|
report.id === source.reportId &&
|
|
report.reportHash === source.reportHash &&
|
|
report.previewHash === source.previewHash,
|
|
'Source walk-forward report does not match'
|
|
);
|
|
const rows = (
|
|
await database.query(
|
|
'SELECT * FROM research_experiments WHERE walk_forward_id=$1 ORDER BY walk_forward_index',
|
|
[header.id]
|
|
)
|
|
).rows;
|
|
retained(rows.length === header.member_ids.length, 'walk-forward member count mismatch');
|
|
const segments: WalkForwardSegment[] = [];
|
|
for (const [index, row] of rows.entries()) {
|
|
const window = at(preview.windows, index);
|
|
retained(
|
|
row.id === header.member_ids[index] &&
|
|
row.walk_forward_index === index &&
|
|
row.backtest_id === header.backtest_id &&
|
|
validationEqual(row.validation_manifest, window.preview),
|
|
'walk-forward member identity mismatch'
|
|
);
|
|
const member = await chronological(row);
|
|
segments.push({
|
|
index,
|
|
validationId: row.id,
|
|
previewHash: member.previewHash,
|
|
selectionHash: member.selectionHash,
|
|
reportId: member.id,
|
|
reportHash: member.reportHash,
|
|
validation: member.validation,
|
|
test: member.test,
|
|
});
|
|
}
|
|
retained(validationEqual(report.segments, segments), 'walk-forward segment report mismatch');
|
|
members = new Set(
|
|
segments.flatMap(segment => [segment.validation.runId, segment.test.runId])
|
|
);
|
|
}
|
|
requested(
|
|
references.every(reference => members.has(reference.runId)),
|
|
'Evidence run does not belong to the selected source'
|
|
);
|
|
return results;
|
|
} catch (cause) {
|
|
if (cause instanceof ResearchError) {
|
|
throw cause;
|
|
}
|
|
throw new Error('Retained research source could not be verified', { cause });
|
|
}
|
|
}
|