feat(research): add durable walk-forward validation workflows
This commit is contained in:
parent
abd1c5b83d
commit
3ed7b98f7c
45 changed files with 5188 additions and 199 deletions
|
|
@ -126,48 +126,68 @@ export class ChronologicalValidationService {
|
|||
'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 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;
|
||||
}
|
||||
await this.insertRuns(client, id, train);
|
||||
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: 'operator' | 'service';
|
||||
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): Promise<ChronologicalValidationSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
|
|
@ -368,43 +388,10 @@ export class ChronologicalValidationService {
|
|||
) {
|
||||
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 [
|
||||
const { training, validation, test } = await this.verifySelectionEvidence(
|
||||
client,
|
||||
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
|
||||
selection
|
||||
);
|
||||
const manifest = {
|
||||
version: 'chronological-validation-report/v1' as const,
|
||||
|
|
@ -442,6 +429,97 @@ export class ChronologicalValidationService {
|
|||
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(
|
||||
|
|
@ -581,7 +659,7 @@ export class ChronologicalValidationService {
|
|||
}
|
||||
return evidence;
|
||||
}
|
||||
private async readDetail(client: PoolClient, id: string): Promise<ChronologicalValidationDetail> {
|
||||
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",
|
||||
|
|
|
|||
147
apps/stock/web-api/src/services/walk-forward-input.ts
Normal file
147
apps/stock/web-api/src/services/walk-forward-input.ts
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
import { z } from 'zod';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { assertStrategyJsonText } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
walkForwardFinalizationSchema,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
walkForwardSubmissionSchema,
|
||||
type WalkForwardInput,
|
||||
type WalkForwardPreview,
|
||||
type WalkForwardReport,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { retainedValidationPreview, validationEqual } from './validation-evidence';
|
||||
import { prepareChronologicalValidation } from './validation-preview';
|
||||
|
||||
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 walk-forward operation');
|
||||
}
|
||||
}
|
||||
export const parseWalkForwardInput = (raw: unknown): WalkForwardInput =>
|
||||
parse(walkForwardInputSchema, raw);
|
||||
export const parseWalkForwardSubmission = (raw: unknown) => parse(walkForwardSubmissionSchema, raw);
|
||||
export const parseWalkForwardFinalization = (raw: unknown) =>
|
||||
parse(walkForwardFinalizationSchema, raw);
|
||||
function countsAndChronology(input: WalkForwardInput, candidateCount: number) {
|
||||
for (let index = 1; index < input.windows.length; index++) {
|
||||
const previous = at(input.windows, index - 1),
|
||||
next = at(input.windows, index);
|
||||
if (
|
||||
next.train.tradeStart < previous.train.tradeStart ||
|
||||
next.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
previous.test.tradeEnd > next.validation.tradeStart
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
'Walk-forward training starts must not decrease, cutoffs must increase, and heldout windows cannot overlap'
|
||||
);
|
||||
}
|
||||
}
|
||||
const windows = input.windows.length,
|
||||
trainingRuns = windows * candidateCount,
|
||||
holdoutRuns = windows * 2,
|
||||
totalRuns = trainingRuns + holdoutRuns;
|
||||
if (totalRuns > MAX_WALK_FORWARD_RUNS) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
`Walk-forward may plan at most ${MAX_WALK_FORWARD_RUNS} runs, including all future holdouts`
|
||||
);
|
||||
}
|
||||
return { windows, trainingRuns, holdoutRuns, totalRuns, maxRuns: MAX_WALK_FORWARD_RUNS };
|
||||
}
|
||||
export function prepareWalkForward(
|
||||
raw: WalkForwardInput,
|
||||
sourcePreview: ExperimentPreview,
|
||||
sourceDataset: HistoricalDatasetV2
|
||||
) {
|
||||
const input = parseWalkForwardInput(raw),
|
||||
source = retainedExperimentPreview(sourcePreview);
|
||||
const { windows: recipes, ...sourceInput } = input;
|
||||
if (!validationEqual(source.input, sourceInput)) {
|
||||
throw new Error('Walk-forward source identity mismatch');
|
||||
}
|
||||
const counts = countsAndChronology(input, source.candidates.length);
|
||||
const prepared = recipes.map((recipe, index) => {
|
||||
const windowInput = { ...sourceInput, name: `${input.name} · window ${index + 1}` };
|
||||
const windowSource = buildExperimentPreview(windowInput, source.request, source.dataset);
|
||||
return prepareChronologicalValidation({ ...windowInput, recipe }, windowSource, sourceDataset);
|
||||
});
|
||||
const manifest = {
|
||||
version: 'walk-forward-preview/v1' as const,
|
||||
execution: 'preview-only' as const,
|
||||
input,
|
||||
source,
|
||||
policy: walkForwardPolicy,
|
||||
windows: prepared.map((window, index) => ({ index, preview: window.preview })),
|
||||
counts,
|
||||
};
|
||||
const preview: WalkForwardPreview = { ...manifest, previewHash: experimentHash(manifest) };
|
||||
return { preview, prepared };
|
||||
}
|
||||
export function retainedWalkForwardPreview(raw: unknown): WalkForwardPreview {
|
||||
const value = raw as WalkForwardPreview,
|
||||
{ previewHash, ...manifest } = value;
|
||||
if (
|
||||
value.version !== 'walk-forward-preview/v1' ||
|
||||
value.execution !== 'preview-only' ||
|
||||
experimentHash(manifest) !== previewHash
|
||||
) {
|
||||
throw new Error('Retained walk-forward preparation integrity failure');
|
||||
}
|
||||
const input = walkForwardInputSchema.parse(value.input),
|
||||
source = retainedExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = input;
|
||||
let counts;
|
||||
try {
|
||||
counts = countsAndChronology(input, source.candidates.length);
|
||||
} catch {
|
||||
throw new Error('Retained walk-forward chronology or budget integrity failure');
|
||||
}
|
||||
if (
|
||||
!validationEqual(sourceInput, source.input) ||
|
||||
!validationEqual(value.policy, walkForwardPolicy) ||
|
||||
!validationEqual(value.counts, counts) ||
|
||||
value.windows.length !== recipes.length
|
||||
) {
|
||||
throw new Error('Retained walk-forward source or budget mismatch');
|
||||
}
|
||||
for (const [index, window] of value.windows.entries()) {
|
||||
const child = retainedValidationPreview(window.preview),
|
||||
windowInput = { ...sourceInput, name: `${input.name} · window ${index + 1}` };
|
||||
if (
|
||||
window.index !== index ||
|
||||
!validationEqual(child.input, { ...windowInput, recipe: at(recipes, index) }) ||
|
||||
!validationEqual(
|
||||
child.source,
|
||||
buildExperimentPreview(windowInput, source.request, source.dataset)
|
||||
)
|
||||
) {
|
||||
throw new Error('Retained walk-forward window identity mismatch');
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export type StoredWalkForwardReport = WalkForwardReport & {
|
||||
_receipt: { key: string; hash: string };
|
||||
};
|
||||
export function publicWalkForwardReport(value: StoredWalkForwardReport): WalkForwardReport {
|
||||
const { _receipt, ...document } = value,
|
||||
{ reportHash, ...manifest } = document;
|
||||
if (!_receipt || experimentHash(manifest) !== reportHash) {
|
||||
throw new Error('Retained walk-forward report integrity failure');
|
||||
}
|
||||
return document;
|
||||
}
|
||||
398
apps/stock/web-api/src/services/walk-forward.service.ts
Normal file
398
apps/stock/web-api/src/services/walk-forward.service.ts
Normal file
|
|
@ -0,0 +1,398 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type {
|
||||
WalkForwardActionResult,
|
||||
WalkForwardDetail,
|
||||
WalkForwardReceipt,
|
||||
WalkForwardReport,
|
||||
WalkForwardSegment,
|
||||
WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import { ChronologicalValidationService } from './chronological-validation.service';
|
||||
import {
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentId,
|
||||
experimentReceipt,
|
||||
} from './experiment-input';
|
||||
import { ExperimentsService } from './experiments.service';
|
||||
import { validationEqual } from './validation-evidence';
|
||||
import {
|
||||
parseWalkForwardFinalization,
|
||||
parseWalkForwardInput,
|
||||
parseWalkForwardSubmission,
|
||||
prepareWalkForward,
|
||||
publicWalkForwardReport,
|
||||
retainedWalkForwardPreview,
|
||||
type StoredWalkForwardReport,
|
||||
} from './walk-forward-input';
|
||||
|
||||
type Actor = { principal: string; key: string };
|
||||
const summary = (row: QueryResultRow, reported: number): WalkForwardSummary => ({
|
||||
id: row.id,
|
||||
backtestId: row.backtest_id,
|
||||
name: row.name,
|
||||
previewHash: row.preview_hash,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
cancelRequested: row.cancel_requested,
|
||||
windowCount: row.preview.counts.windows,
|
||||
reportedWindowCount: reported,
|
||||
trainingRunCount: row.preview.counts.trainingRuns,
|
||||
plannedRunCount: row.preview.counts.totalRuns,
|
||||
stage: row.report ? 'reported' : 'windows',
|
||||
});
|
||||
function checkedHeader(row: QueryResultRow) {
|
||||
const preview = retainedWalkForwardPreview(row.preview);
|
||||
if (
|
||||
preview.previewHash !== row.preview_hash ||
|
||||
preview.input.backtestId !== row.backtest_id ||
|
||||
preview.input.name !== row.name ||
|
||||
!Array.isArray(row.member_ids) ||
|
||||
row.member_ids.length !== preview.windows.length ||
|
||||
new Set(row.member_ids).size !== row.member_ids.length
|
||||
) {
|
||||
throw new Error('Retained walk-forward header identity mismatch');
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
const receipt = (report: WalkForwardReport): WalkForwardReceipt => ({
|
||||
id: report.id,
|
||||
walkForwardId: report.walkForwardId,
|
||||
operation: 'finalize-walk-forward-report',
|
||||
previewHash: report.previewHash,
|
||||
reportHash: report.reportHash,
|
||||
createdAt: report.createdAt,
|
||||
principal: report.principal,
|
||||
});
|
||||
/** Grouped immutable validations; existing workers and per-window controls execute every run. */
|
||||
export class WalkForwardService {
|
||||
private readonly database;
|
||||
private readonly experiments;
|
||||
private readonly validations;
|
||||
constructor(container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.experiments = new ExperimentsService(container);
|
||||
this.validations = new ChronologicalValidationService(container);
|
||||
}
|
||||
async preview(raw: unknown) {
|
||||
const input = parseWalkForwardInput(raw);
|
||||
return this.database.transaction(async client => (await this.prepare(client, input)).preview);
|
||||
}
|
||||
private async prepare(client: PoolClient, input: ReturnType<typeof parseWalkForwardInput>) {
|
||||
const { windows: _windows, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
return prepareWalkForward(input, source, dataset);
|
||||
}
|
||||
async submit(raw: unknown, actor: Actor): Promise<WalkForwardDetail> {
|
||||
const submission = parseWalkForwardSubmission(raw),
|
||||
identity = experimentReceipt(actor),
|
||||
{ previewHash, ...input } = submission;
|
||||
const hash = experimentHash({ version: 1, operation: 'submit-walk-forward', submission });
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
'SELECT id,submission_hash FROM research_walk_forwards WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.submission_hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different walk-forward submission'
|
||||
);
|
||||
}
|
||||
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 prepared = await this.prepare(client, input);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Walk-forward preview is stale; preview the current inputs again'
|
||||
);
|
||||
}
|
||||
const id = randomUUID(),
|
||||
memberIds = prepared.prepared.map(() => randomUUID());
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO research_walk_forwards(id,backtest_id,name,preview,preview_hash,member_ids,submission_principal,submission_key,submission_hash)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT(submission_principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[
|
||||
id,
|
||||
input.backtestId,
|
||||
input.name,
|
||||
prepared.preview,
|
||||
previewHash,
|
||||
memberIds,
|
||||
identity.principal,
|
||||
identity.key,
|
||||
hash,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent walk-forward receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
for (const [index, member] of prepared.prepared.entries()) {
|
||||
const memberId = at(memberIds, index);
|
||||
const accepted = await this.validations.admitPrepared(client, member, {
|
||||
id: memberId,
|
||||
principal: identity.principal,
|
||||
key: `walk-forward-member:${id}:${index}`,
|
||||
hash: experimentHash({
|
||||
version: 1,
|
||||
walkForwardId: id,
|
||||
index,
|
||||
validationId: memberId,
|
||||
previewHash: member.preview.previewHash,
|
||||
}),
|
||||
membership: { id, index },
|
||||
});
|
||||
if (!accepted) {
|
||||
throw new Error('Walk-forward member receipt unexpectedly exists');
|
||||
}
|
||||
}
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<WalkForwardSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT w.*,(SELECT count(*)::int FROM research_experiments e WHERE e.walk_forward_id=w.id AND e.validation_report IS NOT NULL) AS reported
|
||||
FROM research_walk_forwards w ${backtestId === undefined ? '' : 'WHERE w.backtest_id=$1'} ORDER BY w.created_at DESC,w.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
);
|
||||
return rows.rows.map(row => {
|
||||
checkedHeader(row);
|
||||
return summary(row, Number(row.reported));
|
||||
});
|
||||
}
|
||||
async get(id: string): Promise<WalkForwardDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(client => this.readDetail(client, id));
|
||||
}
|
||||
async cancel(id: string): Promise<WalkForwardDetail> {
|
||||
experimentId(id);
|
||||
return this.database.transaction(async client => {
|
||||
await this.lockHeader(client, id);
|
||||
await client.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [
|
||||
id,
|
||||
]);
|
||||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async finalize(id: string, raw: unknown, actor: Actor): Promise<WalkForwardActionResult> {
|
||||
experimentId(id);
|
||||
const input = parseWalkForwardFinalization(raw),
|
||||
identity = experimentReceipt(actor);
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: 'finalize-walk-forward-report',
|
||||
walkForwardId: id,
|
||||
input,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const row = (
|
||||
await client.query(
|
||||
"SELECT id,report FROM research_walk_forwards WHERE report->>'principal'=$1 AND report#>>'{_receipt,key}'=$2",
|
||||
[identity.principal, identity.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (row.report._receipt.hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different walk-forward finalization'
|
||||
);
|
||||
}
|
||||
const report = publicWalkForwardReport(row.report);
|
||||
return { receipt: receipt(report), walkForward: await this.readDetail(client, row.id) };
|
||||
};
|
||||
const prior = await replay();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
const row = await this.lockHeader(client, id);
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (row.report) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Walk-forward report is already sealed under another receipt'
|
||||
);
|
||||
}
|
||||
const preview = checkedHeader(row);
|
||||
if (input.previewHash !== preview.previewHash) {
|
||||
throw new ExperimentError(409, 'Walk-forward preparation identity changed');
|
||||
}
|
||||
if (row.cancel_requested) {
|
||||
throw new ExperimentError(409, 'Walk-forward validation is cancelled');
|
||||
}
|
||||
const members = await this.members(client, row, 'UPDATE');
|
||||
const segments: WalkForwardSegment[] = [];
|
||||
for (const [index, memberId] of (row.member_ids as string[]).entries()) {
|
||||
const member = members.find(m => m.id === memberId && m.walk_forward_index === index);
|
||||
if (!member) {
|
||||
throw new ExperimentError(409, 'Expected walk-forward member is missing');
|
||||
}
|
||||
const report = await this.validations.verifiedSealedReport(client, memberId);
|
||||
segments.push({
|
||||
index,
|
||||
validationId: memberId,
|
||||
previewHash: at(preview.windows, index).preview.previewHash,
|
||||
selectionHash: report.selectionHash,
|
||||
reportId: report.id,
|
||||
reportHash: report.reportHash,
|
||||
validation: report.validation,
|
||||
test: report.test,
|
||||
});
|
||||
}
|
||||
const manifest = {
|
||||
version: 'walk-forward-report/v1' as const,
|
||||
id: randomUUID(),
|
||||
walkForwardId: id,
|
||||
previewHash: preview.previewHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: identity.principal,
|
||||
reset: 'initial-capital-empty-positions' as const,
|
||||
segments,
|
||||
limitations: [
|
||||
'Every window and phase starts with its declared initial capital and empty positions. These are independent reset segments, not a continuous portfolio.',
|
||||
'Training may include earlier historical holdouts; each frozen selection reads only its own training evidence. This does not certify globally unseen data.',
|
||||
'No compounded return, combined equity curve or averaged risk-adjusted metric is implied. Completed execution is not proof of profitability or statistical adequacy.',
|
||||
],
|
||||
};
|
||||
const report: WalkForwardReport = { ...manifest, reportHash: experimentHash(manifest) };
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [
|
||||
`walk-forward-finalize:${identity.principal}:${identity.key}`,
|
||||
]);
|
||||
const race = await replay();
|
||||
if (race) {
|
||||
return race;
|
||||
}
|
||||
const stored: StoredWalkForwardReport = { ...report, _receipt: { key: identity.key, hash } };
|
||||
await client.query('UPDATE research_walk_forwards SET report=$2 WHERE id=$1', [id, stored]);
|
||||
return { receipt: receipt(report), walkForward: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async lockHeader(client: PoolClient, id: string) {
|
||||
const parent = (
|
||||
await client.query(
|
||||
'SELECT id FROM backtests WHERE id=(SELECT backtest_id FROM research_walk_forwards WHERE id=$1) FOR UPDATE',
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Walk-forward validation not found');
|
||||
}
|
||||
const row = (
|
||||
await client.query('SELECT * FROM research_walk_forwards WHERE id=$1 FOR UPDATE', [id])
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Walk-forward validation not found');
|
||||
}
|
||||
return row;
|
||||
}
|
||||
private async members(client: PoolClient, row: QueryResultRow, lock: 'SHARE' | 'UPDATE') {
|
||||
const members = (
|
||||
await client.query(
|
||||
`SELECT * FROM research_experiments WHERE walk_forward_id=$1 ORDER BY walk_forward_index FOR ${lock}`,
|
||||
[row.id]
|
||||
)
|
||||
).rows;
|
||||
for (const member of members) {
|
||||
const expected = row.preview.windows[member.walk_forward_index];
|
||||
if (
|
||||
!expected ||
|
||||
member.id !== row.member_ids[member.walk_forward_index] ||
|
||||
member.backtest_id !== row.backtest_id ||
|
||||
member.validation_phase !== 'train' ||
|
||||
!validationEqual(member.validation_manifest, expected.preview)
|
||||
) {
|
||||
throw new Error('Retained walk-forward membership identity mismatch');
|
||||
}
|
||||
}
|
||||
return members;
|
||||
}
|
||||
private async readDetail(client: PoolClient, id: string): Promise<WalkForwardDetail> {
|
||||
const row = (
|
||||
await client.query('SELECT * FROM research_walk_forwards WHERE id=$1 FOR SHARE', [id])
|
||||
).rows[0];
|
||||
if (!row) {
|
||||
throw new ExperimentError(404, 'Walk-forward validation not found');
|
||||
}
|
||||
const preview = checkedHeader(row),
|
||||
members = await this.members(client, row, 'SHARE');
|
||||
const windows: WalkForwardDetail['windows'] = [];
|
||||
for (const [index, validationId] of (row.member_ids as string[]).entries()) {
|
||||
const member = members.find(m => m.id === validationId && m.walk_forward_index === index);
|
||||
windows.push({
|
||||
index,
|
||||
validationId,
|
||||
status: member ? 'admitted' : 'missing',
|
||||
validation: member ? await this.validations.readDetail(client, validationId) : null,
|
||||
});
|
||||
}
|
||||
const report = row.report ? publicWalkForwardReport(row.report) : null;
|
||||
const reported = windows.filter(w => w.validation?.report).length;
|
||||
const ready =
|
||||
!row.cancel_requested &&
|
||||
!report &&
|
||||
windows.every(
|
||||
w =>
|
||||
w.validation?.report &&
|
||||
!w.validation.cancelRequested &&
|
||||
w.validation.phases.every(
|
||||
p =>
|
||||
p.experiment &&
|
||||
!p.experiment.cancelRequested &&
|
||||
p.experiment.trials.every(
|
||||
t => t.status === 'completed' && t.comparable && !t.cancelRequested
|
||||
)
|
||||
)
|
||||
);
|
||||
return {
|
||||
...summary(row, reported),
|
||||
preview,
|
||||
windows,
|
||||
report,
|
||||
actions: {
|
||||
finalize: {
|
||||
available: ready,
|
||||
reason: ready
|
||||
? null
|
||||
: report
|
||||
? 'Walk-forward report is already saved'
|
||||
: row.cancel_requested
|
||||
? 'Walk-forward validation is cancelled'
|
||||
: 'Every window needs complete uncancelled verified evidence and a sealed report',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue