stock-bot/apps/stock/web-api/src/services/walk-forward.service.ts

428 lines
16 KiB
TypeScript

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 type { ChronologicalValidationService } from './chronological-validation.service';
import {
ExperimentError,
experimentHash,
experimentId,
experimentReceipt,
} from './experiment-input';
import type { ExperimentsService } from './experiments.service';
import { lockResearchAgent } from './research-agent-budget';
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,
collaborators: {
experiments: Pick<ExperimentsService, 'lockedPreview'>;
validations: Pick<
ChronologicalValidationService,
'admitPrepared' | 'verifiedSealedReport' | 'readDetail'
>;
}
) {
this.database = requireServices(container, 'postgres').postgres;
this.experiments = collaborators.experiments;
this.validations = collaborators.validations;
}
async preview(raw: unknown, principal = 'operator') {
const input = parseWalkForwardInput(raw);
return this.database.transaction(async client => {
await lockResearchAgent(client, principal);
return (await this.prepare(client, input, principal)).preview;
});
}
private async prepare(
client: PoolClient,
input: ReturnType<typeof parseWalkForwardInput>,
principal = 'operator'
) {
const { windows: _windows, ...sourceInput } = input;
const source = await this.experiments.lockedPreview(client, sourceInput, principal);
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 => {
await lockResearchAgent(client, identity.principal);
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, identity.principal);
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, agentId?: string): Promise<WalkForwardSummary[]> {
if (backtestId !== undefined) {
experimentId(backtestId);
}
const conditions: string[] = [];
const values: unknown[] = [];
if (backtestId !== undefined) {
values.push(backtestId);
conditions.push(`w.backtest_id=$${values.length}`);
}
if (agentId !== undefined) {
values.push(agentId);
conditions.push(`w.submission_principal=$${values.length}`);
}
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
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 ${where} ORDER BY w.created_at DESC,w.id DESC`,
values
);
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 => {
await lockResearchAgent(client, identity.principal);
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',
},
},
};
}
}