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
|
|
@ -36,6 +36,10 @@
|
|||
"./chronological-validation": {
|
||||
"types": "./dist/contracts/chronological-validation.d.ts",
|
||||
"default": "./dist/contracts/chronological-validation.js"
|
||||
},
|
||||
"./walk-forward": {
|
||||
"types": "./dist/contracts/walk-forward.d.ts",
|
||||
"default": "./dist/contracts/walk-forward.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
115
apps/stock/config/src/contracts/walk-forward.ts
Normal file
115
apps/stock/config/src/contracts/walk-forward.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/** A bounded collection of existing chronological validations, not a new execution engine. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationDetail,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationActionCapability,
|
||||
type ValidationResultEvidence,
|
||||
} from './chronological-validation';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentPreview,
|
||||
} from './experiments';
|
||||
|
||||
export const MAX_WALK_FORWARD_WINDOWS = 10;
|
||||
/** Includes training and both future holdouts for every window. */
|
||||
export const MAX_WALK_FORWARD_RUNS = MAX_EXPERIMENT_TRIALS;
|
||||
export const walkForwardInputSchema = experimentInputSchema.extend({
|
||||
windows: z
|
||||
.array(chronologicalValidationInputSchema.shape.recipe)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
});
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
export const walkForwardSubmissionSchema = walkForwardInputSchema.extend({ previewHash: hash });
|
||||
export const walkForwardFinalizationSchema = z.object({ previewHash: hash }).strict();
|
||||
export type WalkForwardInput = z.infer<typeof walkForwardInputSchema>;
|
||||
export type WalkForwardSubmission = z.infer<typeof walkForwardSubmissionSchema>;
|
||||
export type WalkForwardFinalizationInput = z.infer<typeof walkForwardFinalizationSchema>;
|
||||
|
||||
export const walkForwardPolicy = {
|
||||
selection: 'independent-training-winner-per-window',
|
||||
training: 'nondecreasing-start-strictly-increasing-cutoff',
|
||||
holdouts: 'previous-test-end-at-or-before-next-validation-start',
|
||||
reset: 'initial-capital-empty-positions',
|
||||
reporting: 'ordered-independent-reset-segments',
|
||||
} as const;
|
||||
export interface WalkForwardPreview {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreview;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreview }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
}
|
||||
export interface WalkForwardSegment {
|
||||
index: number;
|
||||
validationId: string;
|
||||
previewHash: string;
|
||||
selectionHash: string;
|
||||
reportId: string;
|
||||
reportHash: string;
|
||||
/** Copied diagnostic and test results, never a compounded portfolio. */
|
||||
validation: ValidationResultEvidence;
|
||||
test: ValidationResultEvidence;
|
||||
}
|
||||
export interface WalkForwardReport {
|
||||
version: 'walk-forward-report/v1';
|
||||
id: string;
|
||||
walkForwardId: string;
|
||||
previewHash: string;
|
||||
reportHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
reset: 'initial-capital-empty-positions';
|
||||
/** Every frozen window in ascending index; absent evidence cannot be omitted. */
|
||||
segments: WalkForwardSegment[];
|
||||
limitations: string[];
|
||||
}
|
||||
export interface WalkForwardSummary {
|
||||
id: string;
|
||||
backtestId: string;
|
||||
name: string;
|
||||
previewHash: string;
|
||||
createdAt: string;
|
||||
cancelRequested: boolean;
|
||||
windowCount: number;
|
||||
reportedWindowCount: number;
|
||||
trainingRunCount: number;
|
||||
plannedRunCount: number;
|
||||
stage: 'windows' | 'reported';
|
||||
}
|
||||
export interface WalkForwardDetail extends WalkForwardSummary {
|
||||
preview: WalkForwardPreview;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ChronologicalValidationDetail | null;
|
||||
}[];
|
||||
report: WalkForwardReport | null;
|
||||
actions: { finalize: ValidationActionCapability };
|
||||
}
|
||||
export interface WalkForwardReceipt {
|
||||
id: string;
|
||||
walkForwardId: string;
|
||||
operation: 'finalize-walk-forward-report';
|
||||
previewHash: string;
|
||||
reportHash: string;
|
||||
createdAt: string;
|
||||
principal: 'operator' | 'service';
|
||||
}
|
||||
export interface WalkForwardActionResult {
|
||||
receipt: WalkForwardReceipt;
|
||||
walkForward: WalkForwardDetail;
|
||||
}
|
||||
|
|
@ -64,7 +64,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '21-run-reproduction.sql' ||
|
||||
f === '22-experiments.sql' ||
|
||||
f === '23-experiment-retries.sql' ||
|
||||
f === '24-chronological-validation.sql')
|
||||
f === '24-chronological-validation.sql' ||
|
||||
f === '25-walk-forward.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -19,12 +19,19 @@ import {
|
|||
parseValidationSubmission,
|
||||
} from '../services/validation-evidence';
|
||||
import { parseChronologicalValidation } from '../services/validation-preview';
|
||||
import {
|
||||
parseWalkForwardFinalization,
|
||||
parseWalkForwardInput,
|
||||
parseWalkForwardSubmission,
|
||||
} from '../services/walk-forward-input';
|
||||
import { WalkForwardService } from '../services/walk-forward.service';
|
||||
|
||||
/** 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 walkForwards = new WalkForwardService(container);
|
||||
const logger = getLogger('experiments-api');
|
||||
const credentials: MiddlewareHandler = async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
|
|
@ -50,6 +57,54 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
throw new ExperimentError(400, 'Invalid JSON request');
|
||||
}
|
||||
};
|
||||
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
||||
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/walk-forward', async c => {
|
||||
const input = parseWalkForwardSubmission(await body(c.req.raw));
|
||||
const walkForward = await walkForwards.submit(
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
);
|
||||
c.header('Location', `/api/v2/experiments/walk-forward/${walkForward.id}`);
|
||||
return c.json({ walkForward }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments/walk-forward', async c =>
|
||||
c.json({ walkForwards: await walkForwards.list(c.req.query('backtestId')) })
|
||||
);
|
||||
app.get('/api/v2/experiments/walk-forward/:id', async c =>
|
||||
c.json({ walkForward: await walkForwards.get(experimentId(c.req.param('id'))) })
|
||||
);
|
||||
app.post('/api/v2/experiments/walk-forward/:id/finalize', async c => {
|
||||
const id = experimentId(c.req.param('id')),
|
||||
input = parseWalkForwardFinalization(await body(c.req.raw));
|
||||
return c.json(
|
||||
await walkForwards.finalize(
|
||||
id,
|
||||
input,
|
||||
experimentReceipt({
|
||||
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
|
||||
key: c.req.header('Idempotency-Key') ?? '',
|
||||
})
|
||||
),
|
||||
202
|
||||
);
|
||||
});
|
||||
app.post('/api/v2/experiments/walk-forward/: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({ walkForward: await walkForwards.cancel(id) });
|
||||
});
|
||||
app.post('/api/v2/experiments/validation/preview', async c => {
|
||||
const input = parseChronologicalValidation(await body(c.req.raw));
|
||||
return c.json({ preview: await service.previewValidation(input) });
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
ChronologicalValidationDetailPage,
|
||||
ExperimentDetailPage,
|
||||
ExperimentListPage,
|
||||
WalkForwardDetailPage,
|
||||
} from '@/features/experiments';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
|
|
@ -59,6 +60,7 @@ export function App() {
|
|||
path="validation/:validationId"
|
||||
element={<ChronologicalValidationDetailPage />}
|
||||
/>
|
||||
<Route path="walk-forward/:walkForwardId" element={<WalkForwardDetailPage />} />
|
||||
<Route path=":experimentId" element={<ExperimentDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Button } from '@/components/ui/Button';
|
|||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentEditor } from './components/ExperimentEditor';
|
||||
import { SavedChronologicalValidations } from './components/SavedChronologicalValidations';
|
||||
import { SavedWalkForwards } from './components/SavedWalkForwards';
|
||||
import { experimentApi } from './services/experimentApi';
|
||||
|
||||
export function ExperimentListPage() {
|
||||
|
|
@ -73,6 +74,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
</div>
|
||||
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
|
||||
<SavedChronologicalValidations backtestId={backtestId} />
|
||||
<SavedWalkForwards backtestId={backtestId} />
|
||||
<section aria-label="Saved experiments" className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved experiments</h2>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,383 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ValidationEvidence } from './components/ValidationEvidence';
|
||||
import {
|
||||
walkForwardApi,
|
||||
WalkForwardApiError,
|
||||
type WalkForwardDetailView,
|
||||
} from './services/walkForwardApi';
|
||||
|
||||
export function WalkForwardDetailPage() {
|
||||
const { walkForwardId = '' } = useParams<{ walkForwardId: string }>();
|
||||
return <WalkForwardDetail key={walkForwardId} walkForwardId={walkForwardId} />;
|
||||
}
|
||||
type Intent = { id: string; body: { previewHash: string }; key: string };
|
||||
function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
reading = useRef(true),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null),
|
||||
captured = useRef<Intent | null>(null);
|
||||
const [value, setValue] = useState<WalkForwardDetailView | null>(null),
|
||||
[intent, setIntent] = useState<Intent | null>(null),
|
||||
[receipt, setReceipt] = useState<WalkForwardReceipt | null>(null);
|
||||
const [loading, setLoading] = useState(true),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reload, setReload] = useState(0),
|
||||
[readError, setReadError] = useState(''),
|
||||
[actionError, setActionError] = useState(''),
|
||||
[ambiguous, setAmbiguous] = useState(false);
|
||||
useUnsavedWarning(Boolean(intent));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (pending.current) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
const revision = ++generation.current,
|
||||
controller = new AbortController();
|
||||
read.current = controller;
|
||||
reading.current = true;
|
||||
setLoading(true);
|
||||
setReadError('');
|
||||
void walkForwardApi
|
||||
.get(walkForwardId, controller.signal)
|
||||
.then(result => {
|
||||
if (current && revision === generation.current) {
|
||||
setValue(result);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current && revision === generation.current) {
|
||||
setReadError(
|
||||
cause instanceof Error ? cause.message : 'Could not load walk-forward validation'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current && revision === generation.current) {
|
||||
reading.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [walkForwardId, reload]);
|
||||
const begin = () => {
|
||||
if (pending.current || reading.current) {
|
||||
return false;
|
||||
}
|
||||
pending.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
return true;
|
||||
};
|
||||
const finish = () => {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const finalize = async () => {
|
||||
if (pending.current || reading.current || !value) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (!value.actions.finalize.available) {
|
||||
return;
|
||||
}
|
||||
captured.current = {
|
||||
id: walkForwardId,
|
||||
body: { previewHash: value.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
};
|
||||
setIntent(captured.current);
|
||||
setReceipt(null);
|
||||
}
|
||||
const original = captured.current;
|
||||
if (!begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await walkForwardApi.finalize(original.id, original.body, original.key);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setReceipt(result.receipt);
|
||||
setValue(result.walkForward);
|
||||
setAmbiguous(false);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
cause instanceof Error ? cause.message : 'Could not save walk-forward report'
|
||||
);
|
||||
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const cancel = async () => {
|
||||
if (!value || !begin()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await walkForwardApi.cancel(walkForwardId);
|
||||
if (alive.current) {
|
||||
setValue(result);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setActionError(
|
||||
`${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
pending.current ||
|
||||
!window.confirm(
|
||||
'Discard this report request? It may already have succeeded. Refresh the saved walk-forward validation before preparing another action.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setIntent(null);
|
||||
setActionError('');
|
||||
setAmbiguous(false);
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className="h-full overflow-auto p-1 space-y-4"
|
||||
onClickCapture={event => {
|
||||
if (
|
||||
(event.target as HTMLElement).closest('a') &&
|
||||
captured.current &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!window.confirm(
|
||||
'Leave this unconfirmed walk-forward report request? Its exact body and key will be discarded. You can inspect evidence in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Link to="/experiments" className="text-primary-500 text-sm">
|
||||
All experiments
|
||||
</Link>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 className="text-lg font-bold">{value?.name ?? 'Walk-forward validation'}</h1>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || busy}
|
||||
onClick={() => {
|
||||
if (!pending.current && !reading.current) {
|
||||
reading.current = true;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setReload(current => current + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Refresh walk-forward
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading walk-forward validation...</p>}
|
||||
{readError && (
|
||||
<p role="alert" className="text-error">
|
||||
{readError}
|
||||
{value && ' Showing the last loaded state.'}
|
||||
</p>
|
||||
)}
|
||||
{actionError && (
|
||||
<p role="alert" className="text-error">
|
||||
{actionError}
|
||||
</p>
|
||||
)}
|
||||
{intent && (
|
||||
<div className="space-y-2">
|
||||
<p role="status">
|
||||
{ambiguous ? 'Report acceptance is unconfirmed. ' : ''}This request retains its exact
|
||||
walk-forward identity, preview and key.
|
||||
</p>
|
||||
<Button disabled={busy || loading} onClick={() => void finalize()}>
|
||||
Retry walk-forward report request
|
||||
</Button>{' '}
|
||||
<Button variant="outline" disabled={busy} onClick={discard}>
|
||||
Discard walk-forward report request
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{receipt && (
|
||||
<p role="status">
|
||||
Walk-forward report accepted. Receipt {receipt.id} · {receipt.createdAt}
|
||||
</p>
|
||||
)}
|
||||
{value && (
|
||||
<>
|
||||
<p className="font-semibold">
|
||||
{value.report
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
: 'Window validations admitted · walk-forward report not yet saved'}
|
||||
</p>
|
||||
<p>
|
||||
{value.reportedWindowCount}/{value.windowCount} window reports saved ·{' '}
|
||||
{value.trainingRunCount} training runs · {value.plannedRunCount} total planned runs,
|
||||
including future holdouts.
|
||||
</p>
|
||||
<p>
|
||||
Each phase and window resets initial capital and positions. These are ordered
|
||||
independent reset segments, not a continuous portfolio equity curve. No returns are
|
||||
compounded and no window metrics are averaged.
|
||||
</p>
|
||||
{value.cancelRequested && (
|
||||
<p>
|
||||
Cancellation requested for all windows. Completed evidence remains retained; active
|
||||
work may still finish.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!intent && !value.report && (
|
||||
<Button
|
||||
disabled={loading || busy || !value.actions.finalize.available}
|
||||
onClick={() => void finalize()}
|
||||
>
|
||||
Save walk-forward report
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={loading || busy || value.cancelRequested}
|
||||
onClick={() => void cancel()}
|
||||
>
|
||||
Cancel remaining walk-forward work
|
||||
</Button>
|
||||
</div>
|
||||
{!value.report && value.actions.finalize.reason && <p>{value.actions.finalize.reason}</p>}
|
||||
<section aria-label="Walk-forward windows" className="space-y-3">
|
||||
<h2 className="font-semibold">Window progress and evidence</h2>
|
||||
{value.windows.map(member => (
|
||||
<article key={member.index} className="rounded border border-border p-3 space-y-2">
|
||||
<h3 className="font-medium">Window {member.index + 1}</h3>
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/experiments/validation/${encodeURIComponent(member.validationId)}`}
|
||||
>
|
||||
Open window {member.index + 1} validation
|
||||
</Link>
|
||||
{member.status === 'missing' ? (
|
||||
<p role="alert">
|
||||
Window {member.index + 1} validation is missing. Its outcome has not been
|
||||
omitted.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{member.validation?.report
|
||||
? 'Window report saved'
|
||||
: member.validation?.selection
|
||||
? 'Fixed winner selected · validation and test admitted'
|
||||
: 'Training candidates admitted · selection not yet frozen'}
|
||||
</p>
|
||||
{member.validation?.cancelRequested && (
|
||||
<p>Cancellation requested for this window.</p>
|
||||
)}
|
||||
{member.validation?.phases.map(phase => (
|
||||
<div key={phase.phase}>
|
||||
<p>
|
||||
{phase.phase}:{' '}
|
||||
{phase.status === 'not-admitted'
|
||||
? 'Not admitted'
|
||||
: phase.status === 'missing'
|
||||
? 'Experiment missing'
|
||||
: phase.experiment
|
||||
? `${phase.experiment.counts.completed} completed, ${phase.experiment.counts.failed} failed, ${phase.experiment.counts.cancelled} cancelled, ${phase.experiment.counts.pending} pending, ${phase.experiment.counts.running} running, ${phase.experiment.counts.paused} paused`
|
||||
: 'Unavailable'}
|
||||
</p>
|
||||
{phase.experiment &&
|
||||
phase.experiment.trials
|
||||
.filter(
|
||||
trial =>
|
||||
trial.status === 'missing' ||
|
||||
trial.error ||
|
||||
(trial.status === 'completed' && !trial.comparable)
|
||||
)
|
||||
.map(trial => (
|
||||
<p key={trial.index}>
|
||||
Candidate {trial.index + 1}: {trial.status};{' '}
|
||||
{trial.error ?? trial.diagnostic ?? 'Evidence unavailable'}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Frozen walk-forward inputs</summary>
|
||||
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(value.preview, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
{value.report && (
|
||||
<section aria-label="Saved walk-forward report" className="space-y-3">
|
||||
<h2 className="font-semibold">Saved walk-forward report</h2>
|
||||
<p className="break-all">
|
||||
Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}
|
||||
</p>
|
||||
{value.report.limitations.map((limitation, index) => (
|
||||
<p key={index}>{limitation}</p>
|
||||
))}
|
||||
{value.report.segments.map(segment => (
|
||||
<section key={segment.index} className="space-y-2">
|
||||
<h3 className="font-medium">Window {segment.index + 1} reset segment</h3>
|
||||
<p className="break-all">
|
||||
Window report {segment.reportId} · {segment.reportHash}
|
||||
</p>
|
||||
<p className="break-all">Selection {segment.selectionHash}</p>
|
||||
<ValidationEvidence
|
||||
title={`Window ${segment.index + 1} validation and test evidence`}
|
||||
items={[segment.validation, segment.test]}
|
||||
backtestId={value.backtestId}
|
||||
/>
|
||||
</section>
|
||||
))}
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained walk-forward report</summary>
|
||||
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(value.report, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -15,38 +15,15 @@ import {
|
|||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
} from '../services/chronologicalValidationDurableApi';
|
||||
import {
|
||||
emptyValidationWindows,
|
||||
parseValidationWindows,
|
||||
ValidationWindowFields,
|
||||
validationWindowsDirty,
|
||||
type ValidationWindows,
|
||||
} from './ValidationWindowFields';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
const labels = {
|
||||
warmupStart: 'warmup start',
|
||||
tradeStart: 'trading start',
|
||||
tradeEnd: 'trading end',
|
||||
};
|
||||
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
||||
type Windows = Record<ValidationPhase, Record<(typeof fields)[number], string>>;
|
||||
const empty = (): Windows => ({
|
||||
train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
});
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
function parseInstant(raw: string, label: string) {
|
||||
const text = raw.trim();
|
||||
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text);
|
||||
const value = Date.parse(text);
|
||||
if (
|
||||
!match ||
|
||||
!Number.isFinite(value) ||
|
||||
new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
|
|
@ -84,7 +61,7 @@ export function ChronologicalValidationPreflight({
|
|||
const [submittingTraining, setSubmittingTraining] = useState(false);
|
||||
const [trainingError, setTrainingError] = useState('');
|
||||
const [trainingAmbiguous, setTrainingAmbiguous] = useState(false);
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
const [windows, setWindows] = useState<ValidationWindows>(emptyValidationWindows);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
|
|
@ -100,8 +77,7 @@ export function ChronologicalValidationPreflight({
|
|||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty =
|
||||
hasTrainingIntent || phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
const dirty = hasTrainingIntent || validationWindowsDirty(windows);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
|
|
@ -121,7 +97,7 @@ export function ChronologicalValidationPreflight({
|
|||
setLoading(false);
|
||||
setError('');
|
||||
}, [identity]);
|
||||
const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
|
||||
const edit = (phase: ValidationPhase, field: keyof ValidationWindows['train'], value: string) => {
|
||||
if (disabled || trainingIntent.current) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -143,24 +119,11 @@ export function ChronologicalValidationPreflight({
|
|||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const bounds = (phase: ValidationPhase) =>
|
||||
Object.fromEntries(
|
||||
fields.map(field => [
|
||||
field,
|
||||
parseInstant(windows[phase][field], `${phaseLabels[phase]} ${labels[field]} (UTC)`),
|
||||
])
|
||||
);
|
||||
const input = chronologicalValidationInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
recipe: {
|
||||
version: 1,
|
||||
train: bounds('train'),
|
||||
validation: bounds('validation'),
|
||||
test: bounds('test'),
|
||||
labelHorizonMs: 0,
|
||||
},
|
||||
recipe: parseValidationWindows(windows),
|
||||
});
|
||||
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
||||
if (
|
||||
|
|
@ -264,33 +227,14 @@ export function ChronologicalValidationPreflight({
|
|||
instants ending in Z; no local-time conversion or automatic date split is applied. Trading
|
||||
windows exclude their end instant. Warmup may overlap earlier phases.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">{phaseLabels[phase]} window</legend>
|
||||
{fields.map(field => (
|
||||
<label key={field} className="block text-xs">
|
||||
{phaseLabels[phase]} {labels[field]} (UTC)
|
||||
<input
|
||||
className={fieldClass}
|
||||
type="text"
|
||||
value={windows[phase][field]}
|
||||
placeholder="2024-01-01T09:00:00Z"
|
||||
onChange={event => edit(phase, field, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
<ValidationWindowFields
|
||||
windows={windows}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
onChange={edit}
|
||||
/>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the ordinary sweep submission before preparing chronological
|
||||
inputs.
|
||||
Resolve or explicitly release the other submission before preparing chronological inputs.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
} from '../services/experimentApi';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import { WalkForwardPreflight } from './WalkForwardPreflight';
|
||||
|
||||
const fieldClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
||||
|
|
@ -49,15 +50,17 @@ export function ExperimentEditor({
|
|||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | null>(null);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner === 'chronological') {
|
||||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
|
|
@ -65,7 +68,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
|
|
@ -87,9 +90,11 @@ export function ExperimentEditor({
|
|||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [validationDirty, setValidationDirty] = useState(false);
|
||||
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
|
||||
const dirty =
|
||||
hasIntent ||
|
||||
validationDirty ||
|
||||
walkForwardDirty ||
|
||||
Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
|
|
@ -349,7 +354,7 @@ export function ExperimentEditor({
|
|||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={submitting || lockedBy === 'chronological'}
|
||||
disabled={submitting || (lockedBy !== null && lockedBy !== 'ordinary')}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
|
|
@ -369,12 +374,22 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy === 'ordinary'}
|
||||
disabled={lockedBy !== null && lockedBy !== 'chronological'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
<WalkForwardPreflight
|
||||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={lockedBy !== null && lockedBy !== 'walk-forward'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,83 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { WalkForwardSummary } from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { walkForwardApi } from '../services/walkForwardApi';
|
||||
|
||||
export function SavedWalkForwards({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<WalkForwardSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void walkForwardApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(
|
||||
cause instanceof Error ? cause.message : 'Could not load walk-forward validations'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<section aria-label="Saved walk-forward validations" className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved walk-forward validations</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh walk-forward validations
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading walk-forward validations...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No saved walk-forward validations.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-1">
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/walk-forward/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{item.stage === 'reported'
|
||||
? 'Execution complete · walk-forward report saved'
|
||||
: 'Window validations admitted'}{' '}
|
||||
· {item.reportedWindowCount}/{item.windowCount} window reports saved ·{' '}
|
||||
{item.trainingRunCount} training runs · {item.plannedRunCount} planned runs
|
||||
</p>
|
||||
{item.cancelRequested && <p className="text-sm">Cancellation requested</p>}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import type {
|
||||
ChronologicalValidationInput,
|
||||
ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
const labels = {
|
||||
warmupStart: 'warmup start',
|
||||
tradeStart: 'trading start',
|
||||
tradeEnd: 'trading end',
|
||||
};
|
||||
const phaseLabels = { train: 'Train', validation: 'Validation', test: 'Test' };
|
||||
export type ValidationWindows = Record<ValidationPhase, Record<(typeof fields)[number], string>>;
|
||||
export const emptyValidationWindows = (): ValidationWindows => ({
|
||||
train: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
validation: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
test: { warmupStart: '', tradeStart: '', tradeEnd: '' },
|
||||
});
|
||||
export const validationWindowsDirty = (windows: ValidationWindows) =>
|
||||
phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
function parseInstant(raw: string, label: string) {
|
||||
const text = raw.trim(),
|
||||
match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?Z$/.exec(text),
|
||||
value = Date.parse(text);
|
||||
if (
|
||||
!match ||
|
||||
!Number.isFinite(value) ||
|
||||
new Date(value).toISOString() !== `${match[1]}.${(match[2] ?? '').padEnd(3, '0')}Z`
|
||||
) {
|
||||
throw new Error(
|
||||
`${label} must be a real UTC instant ending in Z, for example 2024-01-01T09:00:00Z.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export function parseValidationWindows(
|
||||
windows: ValidationWindows,
|
||||
prefix = ''
|
||||
): ChronologicalValidationInput['recipe'] {
|
||||
const bounds = (phase: ValidationPhase) => ({
|
||||
warmupStart: parseInstant(
|
||||
windows[phase].warmupStart,
|
||||
`${prefix}${phaseLabels[phase]} warmup start (UTC)`
|
||||
),
|
||||
tradeStart: parseInstant(
|
||||
windows[phase].tradeStart,
|
||||
`${prefix}${phaseLabels[phase]} trading start (UTC)`
|
||||
),
|
||||
tradeEnd: parseInstant(
|
||||
windows[phase].tradeEnd,
|
||||
`${prefix}${phaseLabels[phase]} trading end (UTC)`
|
||||
),
|
||||
});
|
||||
return {
|
||||
version: 1,
|
||||
train: bounds('train'),
|
||||
validation: bounds('validation'),
|
||||
test: bounds('test'),
|
||||
labelHorizonMs: 0,
|
||||
};
|
||||
}
|
||||
export function ValidationWindowFields({
|
||||
windows,
|
||||
disabled,
|
||||
prefix = '',
|
||||
onChange,
|
||||
}: {
|
||||
windows: ValidationWindows;
|
||||
disabled: boolean;
|
||||
prefix?: string;
|
||||
onChange: (phase: ValidationPhase, field: (typeof fields)[number], value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">
|
||||
{prefix}
|
||||
{phaseLabels[phase]} window
|
||||
</legend>
|
||||
{fields.map(field => (
|
||||
<label key={field} className="block text-xs">
|
||||
{prefix}
|
||||
{phaseLabels[phase]} {labels[field]} (UTC)
|
||||
<input
|
||||
className="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60"
|
||||
type="text"
|
||||
value={windows[phase][field]}
|
||||
placeholder="2024-01-01T09:00:00Z"
|
||||
onChange={event => onChange(phase, field, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,349 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
type WalkForwardSubmission,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import {
|
||||
walkForwardApi,
|
||||
WalkForwardApiError,
|
||||
type WalkForwardPreviewView,
|
||||
} from '../services/walkForwardApi';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import {
|
||||
emptyValidationWindows,
|
||||
parseValidationWindows,
|
||||
ValidationWindowFields,
|
||||
validationWindowsDirty,
|
||||
type ValidationWindows,
|
||||
} from './ValidationWindowFields';
|
||||
|
||||
type Owner = 'ordinary' | 'chronological' | 'walk-forward';
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof z.ZodError
|
||||
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: 'Could not prepare walk-forward validation';
|
||||
export function WalkForwardPreflight({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (value: boolean) => void;
|
||||
claimSubmission: (owner: Owner) => boolean;
|
||||
releaseSubmission: (owner: Owner) => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const [windows, setWindows] = useState<ValidationWindows[]>(() => [
|
||||
emptyValidationWindows(),
|
||||
emptyValidationWindows(),
|
||||
]);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
preview: WalkForwardPreviewView;
|
||||
} | null>(null);
|
||||
const [hasIntent, setHasIntent] = useState(false),
|
||||
[loading, setLoading] = useState(false),
|
||||
[submitting, setSubmitting] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[ambiguous, setAmbiguous] = useState(false);
|
||||
const captured = useRef<{
|
||||
body: WalkForwardSubmission;
|
||||
key: string;
|
||||
preview: WalkForwardPreviewView;
|
||||
} | null>(null);
|
||||
const alive = useRef(false),
|
||||
pending = useRef(false),
|
||||
posting = useRef(false),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }),
|
||||
currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
captured.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty = hasIntent || windows.length !== 2 || windows.some(validationWindowsDirty);
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
pending.current = false;
|
||||
setPrepared(null);
|
||||
setLoading(false);
|
||||
if (!captured.current) {
|
||||
setError('');
|
||||
}
|
||||
}, [identity]);
|
||||
const edit = (change: (current: ValidationWindows[]) => ValidationWindows[]) => {
|
||||
if (disabled || captured.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
read.current?.abort();
|
||||
setWindows(change);
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !eligible || captured.current || pending.current) {
|
||||
return;
|
||||
}
|
||||
const revision = ++generation.current,
|
||||
original = identity,
|
||||
controller = new AbortController();
|
||||
read.current?.abort();
|
||||
read.current = controller;
|
||||
pending.current = true;
|
||||
setPrepared(null);
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const input = walkForwardInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
windows: windows.map((window, index) =>
|
||||
parseValidationWindows(window, `Window ${index + 1} `)
|
||||
),
|
||||
});
|
||||
const value = await walkForwardApi.preview(input, controller.signal);
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
setPrepared({ identity: original, preview: value });
|
||||
}
|
||||
} catch (cause) {
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
revision === generation.current &&
|
||||
original === currentIdentity.current
|
||||
) {
|
||||
pending.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (
|
||||
posting.current ||
|
||||
pending.current ||
|
||||
(!captured.current && (!preview || disabled || !eligible)) ||
|
||||
!claimSubmission('walk-forward')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!captured.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
captured.current = {
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
preview,
|
||||
};
|
||||
}
|
||||
const original = captured.current;
|
||||
posting.current = true;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await walkForwardApi.submit(original.body, original.key);
|
||||
if (alive.current) {
|
||||
captured.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('walk-forward');
|
||||
navigate(`/experiments/walk-forward/${encodeURIComponent(value.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
posting.current = false;
|
||||
if (alive.current) {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const discard = () => {
|
||||
if (
|
||||
posting.current ||
|
||||
!window.confirm(
|
||||
'Discard this walk-forward submission? It may already exist. Inspect saved walk-forward validations before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
captured.current = null;
|
||||
setHasIntent(false);
|
||||
setPrepared(null);
|
||||
setError('');
|
||||
setAmbiguous(false);
|
||||
releaseSubmission('walk-forward');
|
||||
};
|
||||
return (
|
||||
<details className="border-t border-border pt-4 text-sm">
|
||||
<summary className="cursor-pointer font-semibold">Walk-forward validation</summary>
|
||||
<section aria-label="Walk-forward setup" className="space-y-3 pt-3">
|
||||
<p>
|
||||
Uses the saved backtest, name and parameter grid above. Enter explicit UTC instants ending
|
||||
in Z. Preview saves nothing; submission freezes all windows and admits training together.
|
||||
Each window selects independently from training, with separate validation and test runs.
|
||||
</p>
|
||||
<p>
|
||||
Every phase resets initial capital and positions. Warmup may overlap earlier windows;
|
||||
held-out trading windows cannot overlap. Up to {MAX_WALK_FORWARD_WINDOWS} windows and{' '}
|
||||
{MAX_WALK_FORWARD_RUNS} total planned runs, including both future holdouts per window.
|
||||
</p>
|
||||
{windows.map((window, index) => (
|
||||
<section
|
||||
key={index}
|
||||
aria-label={`Walk-forward window ${index + 1}`}
|
||||
className="space-y-2"
|
||||
>
|
||||
<h4 className="font-medium">Window {index + 1}</h4>
|
||||
<ValidationWindowFields
|
||||
windows={window}
|
||||
prefix={`Window ${index + 1} `}
|
||||
disabled={disabled || hasIntent}
|
||||
onChange={(phase, field, value) =>
|
||||
edit(current =>
|
||||
current.map((item, i) =>
|
||||
i === index ? { ...item, [phase]: { ...item[phase], [field]: value } } : item
|
||||
)
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={disabled || hasIntent || windows.length <= 2}
|
||||
onClick={() => edit(current => current.filter((_, i) => i !== index))}
|
||||
>
|
||||
Remove window {index + 1}
|
||||
</Button>
|
||||
</section>
|
||||
))}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || hasIntent || windows.length >= MAX_WALK_FORWARD_WINDOWS}
|
||||
onClick={() => edit(current => [...current, emptyValidationWindows()])}
|
||||
>
|
||||
Add walk-forward window
|
||||
</Button>{' '}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || hasIntent || !eligible || !name.trim() || loading}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview walk-forward
|
||||
</Button>
|
||||
{disabled && (
|
||||
<p>
|
||||
Resolve or explicitly release the other submission before preparing walk-forward inputs.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Preparing walk-forward inputs...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{preview && (
|
||||
<section aria-label="Prepared walk-forward inputs" className="space-y-3">
|
||||
<p className="font-medium">
|
||||
{preview.counts.windows} windows · {preview.counts.trainingRuns} training runs ·{' '}
|
||||
{preview.counts.holdoutRuns} future holdout runs · {preview.counts.totalRuns} total
|
||||
planned runs
|
||||
</p>
|
||||
<ExperimentInputs preview={preview.source} />
|
||||
{preview.windows.map(item => (
|
||||
<details key={item.index}>
|
||||
<summary className="cursor-pointer">
|
||||
Window {item.index + 1} prepared inputs
|
||||
</summary>
|
||||
<p className="break-all">Preview {item.preview.previewHash}</p>
|
||||
{item.preview.partitions.map(part => (
|
||||
<div key={part.phase} className="py-2">
|
||||
<p>
|
||||
{part.phase}: {new Date(part.dataset.bounds.tradeStart).toISOString()} to{' '}
|
||||
{new Date(part.dataset.bounds.tradeEnd).toISOString()} (end excluded)
|
||||
</p>
|
||||
<p>
|
||||
Warmup starts {new Date(part.dataset.bounds.warmupStart).toISOString()};
|
||||
admitted warmup {part.counts.admittedWarmup}, required {part.requiredWarmup};
|
||||
evaluation observations {part.counts.availableEvaluation}; terminal-at-end
|
||||
observations {part.counts.terminalAtEnd}; completed observations unavailable
|
||||
at end {part.counts.unavailableAtEnd}.
|
||||
</p>
|
||||
<p className="break-all">Dataset {part.dataset.hash}</p>
|
||||
{part.warnings.map((warning, index) => (
|
||||
<p key={index}>{warning}</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(item.preview, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
))}
|
||||
<p className="break-all">Walk-forward preview {preview.previewHash}</p>
|
||||
</section>
|
||||
)}
|
||||
{hasIntent && (
|
||||
<p role="status">
|
||||
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission retains its exact
|
||||
windows, inputs and key. Retry to recover the same walk-forward validation.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting || (disabled && !hasIntent)} onClick={() => void submit()}>
|
||||
{hasIntent ? 'Retry walk-forward submission' : 'Submit walk-forward training'}
|
||||
</Button>
|
||||
{hasIntent && (
|
||||
<Button variant="outline" disabled={submitting} onClick={discard}>
|
||||
Discard walk-forward submission
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
|
||||
export { WalkForwardDetailPage } from './WalkForwardDetailPage';
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ const summary = z.object({
|
|||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
const evidence = z.object({
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
|
|
@ -87,7 +87,7 @@ const selection = z.object({
|
|||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
|
|
@ -100,9 +100,9 @@ const report = z.object({
|
|||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
validation: evidence,
|
||||
test: evidence,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
|
|
@ -134,7 +134,7 @@ const invalid = () =>
|
|||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
function parseDetail(raw: unknown): ValidationDetailView {
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
|
|
@ -198,7 +198,7 @@ function parseDetail(raw: unknown): ValidationDetailView {
|
|||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof evidence>,
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
|
|
@ -330,7 +330,7 @@ export const chronologicalValidationDurableApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -338,7 +338,7 @@ export const chronologicalValidationDurableApi = {
|
|||
}),
|
||||
submit: (input: ChronologicalValidationSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
|
|
@ -353,7 +353,7 @@ export const chronologicalValidationDurableApi = {
|
|||
) =>
|
||||
request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => {
|
||||
const accepted = receipt.parse(envelope(body, 'receipt'));
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
const record = operation === 'select' ? value.selection : value.report;
|
||||
if (
|
||||
accepted.validationId !== id ||
|
||||
|
|
@ -378,7 +378,7 @@ export const chronologicalValidationDurableApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const value = parseValidationDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,426 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
type WalkForwardDetail,
|
||||
type WalkForwardFinalizationInput,
|
||||
type WalkForwardInput,
|
||||
type WalkForwardSubmission,
|
||||
type WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
parseValidationDetail,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from './chronologicalValidationDurableApi';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type WalkForwardPreviewView = {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreviewView;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
};
|
||||
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
||||
preview: WalkForwardPreviewView;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ValidationDetailView | null;
|
||||
}[];
|
||||
};
|
||||
export class WalkForwardApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new WalkForwardApiError(
|
||||
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
const prepared = z.object({
|
||||
version: z.literal('walk-forward-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: hash,
|
||||
input: walkForwardInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
windows: z
|
||||
.array(z.object({ index: count, preview: z.unknown() }))
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
counts: z.object({
|
||||
windows: count,
|
||||
trainingRuns: count,
|
||||
holdoutRuns: count,
|
||||
totalRuns: count,
|
||||
maxRuns: count,
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardPreview(
|
||||
raw: unknown,
|
||||
expected?: WalkForwardInput
|
||||
): WalkForwardPreviewView {
|
||||
const value = prepared.parse(raw),
|
||||
source = parseExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = value.input;
|
||||
const size = recipes.length,
|
||||
candidates = source.candidates.length;
|
||||
if (
|
||||
(expected && !same(value.input, expected)) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, walkForwardPolicy) ||
|
||||
value.windows.length !== size ||
|
||||
!same(value.counts, {
|
||||
windows: size,
|
||||
trainingRuns: size * candidates,
|
||||
holdoutRuns: size * 2,
|
||||
totalRuns: size * (candidates + 2),
|
||||
maxRuns: MAX_WALK_FORWARD_RUNS,
|
||||
}) ||
|
||||
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
const recipe = recipes[index],
|
||||
previous = recipes[index - 1];
|
||||
if (
|
||||
!recipe ||
|
||||
item.index !== index ||
|
||||
(previous &&
|
||||
(recipe.train.tradeStart < previous.train.tradeStart ||
|
||||
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
recipe.validation.tradeStart < previous.test.tradeEnd))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const name = `${value.input.name} · window ${index + 1}`;
|
||||
const preview = parseChronologicalValidationPreview(
|
||||
{ preview: item.preview },
|
||||
{ ...sourceInput, name, recipe }
|
||||
);
|
||||
const { previewHash: _windowHash, ...childSource } = preview.source;
|
||||
const { previewHash: _sourceHash, ...originalSource } = source;
|
||||
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
||||
throw invalid();
|
||||
}
|
||||
return { index, preview };
|
||||
});
|
||||
return { ...value, source, windows, policy: walkForwardPolicy };
|
||||
}
|
||||
const summary = z
|
||||
.object({
|
||||
id: uuid,
|
||||
backtestId: uuid,
|
||||
name: z.string().min(1),
|
||||
previewHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
||||
reportedWindowCount: count,
|
||||
trainingRunCount: count,
|
||||
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
||||
stage: z.enum(['windows', 'reported']),
|
||||
})
|
||||
.superRefine((item, context) => {
|
||||
if (
|
||||
item.reportedWindowCount > item.windowCount ||
|
||||
item.trainingRunCount < item.windowCount ||
|
||||
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Inconsistent walk-forward counts',
|
||||
});
|
||||
}
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('walk-forward-report/v1'),
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: z.enum(['operator', 'service']),
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
segments: z
|
||||
.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportId: uuid,
|
||||
reportHash: hash,
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = z.object({
|
||||
preview: z.unknown(),
|
||||
windows: z.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
status: z.enum(['admitted', 'missing']),
|
||||
validation: z.unknown(),
|
||||
})
|
||||
),
|
||||
report: report.nullable(),
|
||||
actions: z.object({
|
||||
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
||||
const base = summary.parse(raw),
|
||||
value = detail.parse(raw),
|
||||
preview = parseWalkForwardPreview(value.preview);
|
||||
if (
|
||||
base.backtestId !== preview.input.backtestId ||
|
||||
base.name !== preview.input.name ||
|
||||
base.previewHash !== preview.previewHash ||
|
||||
base.windowCount !== preview.counts.windows ||
|
||||
base.trainingRunCount !== preview.counts.trainingRuns ||
|
||||
base.plannedRunCount !== preview.counts.totalRuns ||
|
||||
value.windows.length !== base.windowCount ||
|
||||
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
||||
(base.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
||||
if (
|
||||
validation &&
|
||||
(validation.id !== item.validationId ||
|
||||
validation.backtestId !== base.backtestId ||
|
||||
!same(validation.preview, preview.windows[index]?.preview))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...item, validation };
|
||||
});
|
||||
if (
|
||||
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
||||
(value.actions.finalize.available &&
|
||||
(base.cancelRequested ||
|
||||
value.report ||
|
||||
windows.some(
|
||||
item =>
|
||||
!item.validation?.report ||
|
||||
item.validation.cancelRequested ||
|
||||
item.validation.phases.some(
|
||||
phase =>
|
||||
phase.status !== 'admitted' ||
|
||||
!phase.experiment ||
|
||||
phase.experiment.cancelRequested ||
|
||||
phase.experiment.trials.some(
|
||||
trial =>
|
||||
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
||||
)
|
||||
)
|
||||
)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
saved.walkForwardId !== base.id ||
|
||||
saved.previewHash !== base.previewHash ||
|
||||
saved.segments.length !== base.windowCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const [index, segment] of saved.segments.entries()) {
|
||||
const member = windows[index],
|
||||
frozen = preview.windows[index]?.preview,
|
||||
child = member?.validation?.report;
|
||||
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
||||
if (
|
||||
!member ||
|
||||
!frozen ||
|
||||
!candidate ||
|
||||
segment.index !== index ||
|
||||
segment.validationId !== member.validationId ||
|
||||
segment.previewHash !== frozen.previewHash ||
|
||||
segment.validation.phase !== 'validation' ||
|
||||
segment.test.phase !== 'test' ||
|
||||
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
||||
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
||||
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
||||
[segment.validation, segment.test].some(
|
||||
item =>
|
||||
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
||||
) ||
|
||||
(member.validation &&
|
||||
(!child ||
|
||||
segment.reportId !== child.id ||
|
||||
segment.reportHash !== child.reportHash ||
|
||||
segment.selectionHash !== child.selectionHash ||
|
||||
!same(segment.validation, child.validation) ||
|
||||
!same(segment.test, child.test)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, ...value, preview, windows };
|
||||
}
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new WalkForwardApiError(
|
||||
'The walk-forward response was lost. Retry the same request to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new WalkForwardApiError(
|
||||
error.success ? error.data.error : `Walk-forward request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== status) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
const post = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
});
|
||||
export const walkForwardApi = {
|
||||
preview: (input: WalkForwardInput, signal?: AbortSignal) =>
|
||||
request('/preview', { ...post(input), signal }, 200, body =>
|
||||
parseWalkForwardPreview(envelope(body, 'preview'), input)
|
||||
),
|
||||
list: (backtestId?: string, signal?: AbortSignal) =>
|
||||
request(
|
||||
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
|
||||
{ signal },
|
||||
200,
|
||||
body => {
|
||||
const rows = z.array(summary).parse(envelope(body, 'walkForwards'));
|
||||
if (
|
||||
new Set(rows.map(item => item.id)).size !== rows.length ||
|
||||
(backtestId && rows.some(item => item.backtestId !== backtestId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return rows as WalkForwardSummary[];
|
||||
}
|
||||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
submit: (input: WalkForwardSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
finalize: (id: string, input: WalkForwardFinalizationInput, key: string) =>
|
||||
request(`/${encodeURIComponent(id)}/finalize`, post(input, key), 202, body => {
|
||||
const accepted = z
|
||||
.object({
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
operation: z.literal('finalize-walk-forward-report'),
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: z.enum(['operator', 'service']),
|
||||
})
|
||||
.parse(envelope(body, 'receipt'));
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward')),
|
||||
saved = value.report;
|
||||
if (
|
||||
value.id !== id ||
|
||||
accepted.walkForwardId !== id ||
|
||||
value.previewHash !== input.previewHash ||
|
||||
accepted.previewHash !== input.previewHash ||
|
||||
!saved ||
|
||||
accepted.id !== saved.id ||
|
||||
accepted.reportHash !== saved.reportHash ||
|
||||
accepted.createdAt !== saved.createdAt ||
|
||||
accepted.principal !== saved.principal
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { receipt: accepted, walkForward: value };
|
||||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
||||
const value = parseWalkForwardDetail(envelope(body, 'walkForward'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
};
|
||||
195
database/postgres/init/25-walk-forward.sql
Normal file
195
database/postgres/init/25-walk-forward.sql
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
-- A bounded series groups unchanged chronological validations, without another execution lifecycle.
|
||||
CREATE TABLE IF NOT EXISTS research_walk_forwards (
|
||||
id UUID PRIMARY KEY,
|
||||
backtest_id UUID NOT NULL REFERENCES backtests(id) ON DELETE RESTRICT,
|
||||
name TEXT NOT NULL CHECK(length(btrim(name))>0),
|
||||
preview JSONB NOT NULL,
|
||||
preview_hash TEXT NOT NULL CHECK(preview_hash ~ '^[a-f0-9]{64}$'),
|
||||
member_ids UUID[] NOT NULL,
|
||||
submission_principal TEXT NOT NULL CHECK(submission_principal IN ('operator','service')),
|
||||
submission_key TEXT NOT NULL CHECK(submission_key ~ '^[!-~]{1,200}$'),
|
||||
submission_hash TEXT NOT NULL CHECK(submission_hash ~ '^[a-f0-9]{64}$'),
|
||||
cancel_requested BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
report JSONB,
|
||||
UNIQUE(submission_principal,submission_key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS walk_forward_parent ON research_walk_forwards(backtest_id,created_at DESC);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS walk_forward_report_receipt ON research_walk_forwards((report->>'principal'),(report#>>'{_receipt,key}')) WHERE report IS NOT NULL;
|
||||
ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS walk_forward_id UUID REFERENCES research_walk_forwards(id) ON DELETE RESTRICT;
|
||||
ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS walk_forward_index INTEGER;
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='walk_forward_membership_shape' AND conrelid='research_experiments'::regclass) THEN
|
||||
ALTER TABLE research_experiments ADD CONSTRAINT walk_forward_membership_shape CHECK (((walk_forward_id IS NULL AND walk_forward_index IS NULL)
|
||||
OR (walk_forward_id IS NOT NULL AND walk_forward_index IS NOT NULL AND walk_forward_index>=0 AND validation_phase='train')) IS TRUE);
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS walk_forward_member_index ON research_experiments(walk_forward_id,walk_forward_index) WHERE walk_forward_id IS NOT NULL;
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_walk_forward_manifest() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE source_row research_experiments; source JSONB; segment_preview JSONB; recipe JSONB; previous JSONB; expected_source JSONB; expected_input JSONB;
|
||||
n INTEGER; candidates INTEGER; idx INTEGER:=0;
|
||||
BEGIN
|
||||
source:=NEW.preview->'source';
|
||||
IF (NOT NEW.cancel_requested AND NEW.report IS NULL AND NEW.preview->>'version'='walk-forward-preview/v1' AND NEW.preview->>'execution'='preview-only'
|
||||
AND NEW.preview->>'previewHash'=NEW.preview_hash AND NEW.preview#>>'{input,name}'=NEW.name AND NEW.preview#>>'{input,backtestId}'=NEW.backtest_id::text
|
||||
AND ((NEW.preview->'input')-'windows')=source->'input'
|
||||
AND NEW.preview->'policy'='{"selection":"independent-training-winner-per-window","training":"nondecreasing-start-strictly-increasing-cutoff","holdouts":"previous-test-end-at-or-before-next-validation-start","reset":"initial-capital-empty-positions","reporting":"ordered-independent-reset-segments"}'::jsonb
|
||||
AND jsonb_typeof(NEW.preview->'windows')='array' AND jsonb_typeof(NEW.preview#>'{input,windows}')='array'
|
||||
AND array_ndims(NEW.member_ids)=1 AND array_lower(NEW.member_ids,1)=1 AND array_position(NEW.member_ids,NULL) IS NULL) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Walk-forward requires a complete frozen header, receipt and explicit ordered windows' USING ERRCODE='23514';
|
||||
END IF;
|
||||
n:=jsonb_array_length(NEW.preview->'windows'); candidates:=jsonb_array_length(source->'candidates');
|
||||
IF (n BETWEEN 2 AND 10 AND candidates BETWEEN 1 AND 100 AND n*(candidates+2)<=100
|
||||
AND jsonb_array_length(NEW.preview#>'{input,windows}')=n AND cardinality(NEW.member_ids)=n
|
||||
AND (SELECT count(DISTINCT id) FROM unnest(NEW.member_ids) id)=n
|
||||
AND NEW.preview->'counts'=jsonb_build_object('windows',n,'trainingRuns',n*candidates,'holdoutRuns',n*2,'totalRuns',n*(candidates+2),'maxRuns',100)) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Walk-forward bounds include every training run and both future holdouts for every window' USING ERRCODE='23514';
|
||||
END IF;
|
||||
source_row.backtest_id:=NEW.backtest_id; source_row.name:=NEW.name; source_row.preview:=source; source_row.preview_hash:=source->>'previewHash'; source_row.cancel_requested:=FALSE;
|
||||
PERFORM validate_experiment_manifest(source_row);
|
||||
FOR segment_preview IN SELECT value FROM jsonb_array_elements(NEW.preview->'windows') LOOP
|
||||
recipe:=NEW.preview#>ARRAY['input','windows',idx::text];
|
||||
expected_input:=((NEW.preview->'input')-'windows')||jsonb_build_object('name',NEW.name||' · window '||(idx+1)::text);
|
||||
expected_source:=jsonb_set(source,'{input}',expected_input);
|
||||
IF ((segment_preview-'preview')=jsonb_build_object('index',idx)
|
||||
AND segment_preview#>'{preview,input}'=expected_input||jsonb_build_object('recipe',recipe)
|
||||
AND ((segment_preview#>'{preview,source}')-'previewHash')=(expected_source-'previewHash')
|
||||
AND segment_preview#>>'{preview,source,previewHash}' ~ '^[a-f0-9]{64}$'
|
||||
AND segment_preview#>>'{preview,version}'='chronological-validation-preview/v1' AND segment_preview#>>'{preview,execution}'='preview-only'
|
||||
AND segment_preview#>>'{preview,previewHash}' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Every walk-forward window must preserve its exact common source, grid and assigned recipe' USING ERRCODE='23514';
|
||||
END IF;
|
||||
IF previous IS NOT NULL THEN
|
||||
IF ((recipe#>>'{train,tradeStart}')::bigint>=(previous#>>'{train,tradeStart}')::bigint
|
||||
AND (recipe#>>'{train,tradeEnd}')::bigint>(previous#>>'{train,tradeEnd}')::bigint
|
||||
AND (previous#>>'{test,tradeEnd}')::bigint<=(recipe#>>'{validation,tradeStart}')::bigint) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Walk-forward training cutoffs must increase and heldout evaluation intervals cannot overlap' USING ERRCODE='23514';
|
||||
END IF;
|
||||
END IF;
|
||||
previous:=recipe; idx:=idx+1;
|
||||
END LOOP;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS walk_forward_manifest_admission ON research_walk_forwards;
|
||||
CREATE TRIGGER walk_forward_manifest_admission BEFORE INSERT ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION require_walk_forward_manifest();
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_walk_forward_member() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE header research_walk_forwards;
|
||||
BEGIN
|
||||
IF TG_OP='UPDATE' THEN
|
||||
IF NEW.walk_forward_id IS DISTINCT FROM OLD.walk_forward_id OR NEW.walk_forward_index IS DISTINCT FROM OLD.walk_forward_index THEN
|
||||
RAISE EXCEPTION 'Walk-forward membership is immutable' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.walk_forward_id IS NULL AND NEW.walk_forward_index IS NULL THEN RETURN NEW; END IF;
|
||||
PERFORM 1 FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
|
||||
SELECT * INTO header FROM research_walk_forwards WHERE id=NEW.walk_forward_id FOR UPDATE;
|
||||
IF (header.id IS NOT NULL AND NOT header.cancel_requested AND NEW.validation_phase='train' AND NEW.validation_parent_id IS NULL
|
||||
AND NEW.walk_forward_index>=0 AND NEW.walk_forward_index<cardinality(header.member_ids)
|
||||
AND header.member_ids[NEW.walk_forward_index+1]=NEW.id AND NEW.backtest_id=header.backtest_id
|
||||
AND NEW.validation_manifest=header.preview#>ARRAY['windows',NEW.walk_forward_index::text,'preview']
|
||||
AND NEW.submission_principal=header.submission_principal
|
||||
AND NEW.submission_key='walk-forward-member:'||header.id::text||':'||NEW.walk_forward_index::text) IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Walk-forward member must match its uncancelled header index, identity, receipt and complete frozen preview' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
-- Runs before SQL24's validation admission, preserving parent/header/original-family order.
|
||||
DROP TRIGGER IF EXISTS a_walk_forward_member_admission ON research_experiments;
|
||||
CREATE TRIGGER a_walk_forward_member_admission BEFORE INSERT OR UPDATE ON research_experiments FOR EACH ROW EXECUTE FUNCTION require_walk_forward_member();
|
||||
|
||||
CREATE OR REPLACE FUNCTION require_complete_walk_forward() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE header_id UUID; header research_walk_forwards; member research_experiments; idx INTEGER; member_id UUID;
|
||||
BEGIN
|
||||
IF TG_TABLE_NAME='research_walk_forwards' THEN header_id:=NEW.id; ELSE header_id:=NEW.walk_forward_id; END IF;
|
||||
IF header_id IS NULL THEN RETURN NULL; END IF;
|
||||
SELECT * INTO header FROM research_walk_forwards WHERE id=header_id;
|
||||
IF (SELECT count(*) FROM research_experiments WHERE walk_forward_id=header_id)<>cardinality(header.member_ids) THEN
|
||||
RAISE EXCEPTION 'Walk-forward header and all exact member roots must commit together' USING ERRCODE='23514';
|
||||
END IF;
|
||||
idx:=0;
|
||||
FOREACH member_id IN ARRAY header.member_ids LOOP
|
||||
SELECT * INTO member FROM research_experiments WHERE id=member_id AND walk_forward_id=header.id AND walk_forward_index=idx;
|
||||
IF member.id IS NULL OR member.validation_phase IS DISTINCT FROM 'train'
|
||||
OR member.validation_manifest IS DISTINCT FROM header.preview#>ARRAY['windows',idx::text,'preview']
|
||||
OR (SELECT count(*) FROM runs WHERE experiment_id=member.id)<>jsonb_array_length(member.preview->'candidates')
|
||||
OR EXISTS (SELECT 1 FROM runs r LEFT JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=member.id AND d.run_id IS NULL) THEN
|
||||
RAISE EXCEPTION 'Walk-forward admission requires every exact training root, run and durable outbox' USING ERRCODE='23514';
|
||||
END IF;
|
||||
idx:=idx+1;
|
||||
END LOOP;
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS walk_forward_admission_complete ON research_walk_forwards;
|
||||
CREATE CONSTRAINT TRIGGER walk_forward_admission_complete AFTER INSERT ON research_walk_forwards DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_walk_forward();
|
||||
DROP TRIGGER IF EXISTS walk_forward_member_complete ON research_experiments;
|
||||
CREATE CONSTRAINT TRIGGER walk_forward_member_complete AFTER INSERT ON research_experiments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_walk_forward();
|
||||
|
||||
CREATE OR REPLACE FUNCTION protect_walk_forward_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE document JSONB; member research_experiments; expected JSONB; item JSONB; segment JSONB; idx INTEGER:=0; training_index INTEGER;
|
||||
BEGIN
|
||||
IF NEW.id IS DISTINCT FROM OLD.id OR NEW.backtest_id IS DISTINCT FROM OLD.backtest_id OR NEW.name IS DISTINCT FROM OLD.name
|
||||
OR NEW.preview IS DISTINCT FROM OLD.preview OR NEW.preview_hash IS DISTINCT FROM OLD.preview_hash OR NEW.member_ids IS DISTINCT FROM OLD.member_ids
|
||||
OR NEW.submission_principal IS DISTINCT FROM OLD.submission_principal OR NEW.submission_key IS DISTINCT FROM OLD.submission_key
|
||||
OR NEW.submission_hash IS DISTINCT FROM OLD.submission_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at OR (OLD.cancel_requested AND NOT NEW.cancel_requested)
|
||||
OR (OLD.report IS NOT NULL AND NEW.report IS DISTINCT FROM OLD.report) THEN
|
||||
RAISE EXCEPTION 'Walk-forward inputs, receipt and report are immutable; cancellation is permanent' USING ERRCODE='23514';
|
||||
END IF;
|
||||
IF OLD.report IS NULL AND NEW.report IS NOT NULL THEN
|
||||
document:=NEW.report;
|
||||
IF (NOT NEW.cancel_requested AND document->>'version'='walk-forward-report/v1' AND document->>'walkForwardId'=NEW.id::text
|
||||
AND document->>'previewHash'=NEW.preview_hash AND document->>'reportHash' ~ '^[a-f0-9]{64}$'
|
||||
AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
|
||||
AND document->>'principal' IN ('operator','service') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
|
||||
AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->>'reset'='initial-capital-empty-positions'
|
||||
AND jsonb_typeof(document->'segments')='array' AND jsonb_array_length(document->'segments')=cardinality(NEW.member_ids)
|
||||
AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Walk-forward report requires all independent reset segments and a sealed receipt' USING ERRCODE='23514';
|
||||
END IF;
|
||||
FOR segment IN SELECT value FROM jsonb_array_elements(document->'segments') LOOP
|
||||
SELECT * INTO member FROM research_experiments WHERE id=NEW.member_ids[idx+1] AND walk_forward_id=NEW.id AND walk_forward_index=idx;
|
||||
IF (member.id IS NOT NULL AND NOT member.cancel_requested AND member.validation_report IS NOT NULL
|
||||
AND member.validation_manifest=NEW.preview#>ARRAY['windows',idx::text,'preview']
|
||||
AND member.validation_report->>'previewHash'=member.validation_manifest->>'previewHash'
|
||||
AND member.validation_report->>'selectionHash'=member.validation_selection->>'selectionHash'
|
||||
AND member.validation_report->'training'=member.validation_selection->'training') IS NOT TRUE THEN
|
||||
RAISE EXCEPTION 'Every walk-forward member must have uncancelled sealed evidence matching its exact preparation' USING ERRCODE='23514';
|
||||
END IF;
|
||||
training_index:=0;
|
||||
FOR item IN SELECT value FROM jsonb_array_elements(member.validation_report->'training') LOOP
|
||||
PERFORM assert_validation_evidence(item,member.id,'train',training_index); training_index:=training_index+1;
|
||||
END LOOP;
|
||||
IF training_index<>jsonb_array_length(member.preview->'candidates') THEN RAISE EXCEPTION 'All training evidence is required' USING ERRCODE='23514'; END IF;
|
||||
PERFORM assert_validation_evidence(member.validation_report->'validation',(member.validation_selection#>>'{holdoutExperimentIds,validation}')::uuid,'validation',(member.validation_selection#>>'{winner,index}')::integer);
|
||||
PERFORM assert_validation_evidence(member.validation_report->'test',(member.validation_selection#>>'{holdoutExperimentIds,test}')::uuid,'test',(member.validation_selection#>>'{winner,index}')::integer);
|
||||
expected:=jsonb_build_object('index',idx,'validationId',member.id::text,'previewHash',member.validation_manifest->'previewHash',
|
||||
'selectionHash',member.validation_report->'selectionHash','reportId',member.validation_report->'id','reportHash',member.validation_report->'reportHash',
|
||||
'validation',member.validation_report->'validation','test',member.validation_report->'test');
|
||||
IF segment IS DISTINCT FROM expected THEN RAISE EXCEPTION 'Walk-forward segments must copy exact ordered sealed member reports' USING ERRCODE='23514'; END IF;
|
||||
idx:=idx+1;
|
||||
END LOOP;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS walk_forward_evidence_identity ON research_walk_forwards;
|
||||
CREATE TRIGGER walk_forward_evidence_identity BEFORE UPDATE ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION protect_walk_forward_evidence();
|
||||
DROP TRIGGER IF EXISTS walk_forward_retained ON research_walk_forwards;
|
||||
CREATE TRIGGER walk_forward_retained BEFORE DELETE ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
DROP TRIGGER IF EXISTS walk_forward_no_truncate ON research_walk_forwards;
|
||||
CREATE TRIGGER walk_forward_no_truncate BEFORE TRUNCATE ON research_walk_forwards FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
||||
|
||||
CREATE OR REPLACE FUNCTION cascade_walk_forward_cancellation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE member_id UUID;
|
||||
BEGIN
|
||||
-- A direct UPDATE already owns the header; cascade downward, never acquire its parent.
|
||||
IF NEW.cancel_requested AND NOT OLD.cancel_requested THEN
|
||||
FOREACH member_id IN ARRAY NEW.member_ids LOOP
|
||||
UPDATE research_experiments SET cancel_requested=TRUE WHERE id=member_id AND walk_forward_id=NEW.id;
|
||||
END LOOP;
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
DROP TRIGGER IF EXISTS walk_forward_cancellation_cascade ON research_walk_forwards;
|
||||
CREATE TRIGGER walk_forward_cancellation_cascade AFTER UPDATE OF cancel_requested ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION cascade_walk_forward_cancellation();
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
**First twenty-nine waves committed; durable R08 chronological validation is validated and awaits commit.** Preflight is committed as `67ab30c`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The workbench now runs training, freezes its winner, evaluates validation/test and reopens immutable reports using existing durable experiments and Rust accounting. Full R08 remains partial for multi-window walk-forward and cost sensitivity; R05/R07 remain partial. Performance work stays paused.
|
||||
**First thirty waves committed; the walk-forward component is validated and awaiting commit.** Durable single-window validation is committed as `abd1c5b`; **35 of 45 scheduled tasks are fully committed (78% by count)**. Repeated windows now freeze and execute through the existing durable paths, with immutable reset-segment reports in the web workbench. Full R08 still needs bounded cost sensitivity; R05/R07 remain partial. Performance work stays paused.
|
||||
|
||||
Authorization update: the owner requested “commit and continue”. R08 preflight is accepted and committed as `67ab30c`; the next component implements a complete single chronological recipe through the existing engine and durable runner. No performance work, new-wave commits/pushes/PRs, candidate execution or trading/default activation are included.
|
||||
Authorization update: the owner requested “commit and continue”. The single chronological workflow is accepted and committed as `abd1c5b`; the walk-forward component is now independently reviewed and validated. No performance work, cost overrides, new-wave commits/pushes/PRs, candidate execution or trading/default activation are included.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -641,3 +641,18 @@ All gates passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 825 i
|
|||
The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; logs/worktrees and the exact 38-file archive remain under `/tmp/stock-bot-wave30.K6IDyj/`. Initial manual browser setup hit the fixture network guard because a local VITE override was present; the corrected same-origin build passed both focused and final suites. Existing bundle-size/Rust warnings remain; development data/services were untouched.
|
||||
|
||||
Next after acceptance/commit: finish R08 with repeated nonoverlapping walk-forward windows and bounded cost sensitivity, reusing these durable recipe/experiment paths. Keep independent reset-account reporting explicit; do not imply a continuous portfolio or untouched external holdout. R09 remains blocked; R05/R07 and AI/default/trading gates are unchanged. No performance work, candidate execution, new scheduler/simulator, new-wave commit, push or PR occurred.
|
||||
|
||||
## Thirty-first wave handoff — 2026-10-24
|
||||
|
||||
R08's bounded walk-forward component is independently accepted and `component_validated_uncommitted` on base `abd1c5b`. Full R08 remains `in_progress` for bounded cost sensitivity; R09 remains blocked. Forty-one source/test/config files and four existing planning files comprise this wave.
|
||||
|
||||
- **Frozen series:** A focused `research_walk_forwards` header owns 2–10 ordered recipes and immutable train-root memberships. Every source/grid/build/policy is frozen before training. Total promised work includes all candidates and both future holdouts, capped at 100 runs. Training cutoffs increase and heldout intervals cannot overlap.
|
||||
- **Reuse and integrity:** Existing chronological validations, per-window actions, durable runs/outbox and retries execute every member. SQL25 is additive; SQL22–24 are unchanged. All training roots/slices/runs/outbox admit in one transaction, including a pool-size-one proof. Exact membership, write-once reports and receipts resist direct SQL mutation. Series cancellation reaches all remaining member work; member cancellation stays local and completed evidence is preserved.
|
||||
- **Research evidence:** Series finalization re-verifies all canonical native results behind every member report, then copies ordered validation/test evidence. Archival or current build eligibility cannot invalidate historical sealing/replay. Separate reset accounts are labelled honestly: no continuous equity, compounding or new statistical formula. Changing only later test prices leaves earlier training scores/winners unchanged.
|
||||
- **Web workflow:** Explicit windows, preview, durable submission, saved series, member links and report save/reopen use the existing APIs. Shared editor ownership prevents ordinary/single-window/series submissions from competing. Ambiguous requests retain exact intent/key and late responses cannot replace another route. The real browser executes both windows, freezes inputs before template changes, seals after archival and reopens exact native evidence.
|
||||
|
||||
Validation: 93 tooling, 43 utility, 44 calculation, **882 integration** and **150 Rust** tests passed; **215 PostgreSQL/Redis tests /1881 assertions**, **14 Chromium workflows /412 assertions**, strict authored-test types and lint passed. The full check initially failed only missing-brace lint rules; final source lint/types passed after reviewed formatting-only fixes. Broad lint of old touched test fixtures still reports eight preexisting curly violations outside the added migration-list lines. Existing four ignored Rust cases and build warnings remain. No performance measurements ran.
|
||||
|
||||
Independent backend/frontend reviews accepted the exact eight/eleven-file overlays; root composition and browser coverage were independently reviewed. Source archive, 41 file hashes, native identities, commands and local logs: `manifest.json` → `thirty_first_wave_validation`, under `/tmp/stock-bot-wave31.QqUT6Z/`. Release addon was restored for final database/browser tests. Both disposable fixture containers were removed after validation; development services were untouched. No new-wave commit, push, PR or trading operation occurred.
|
||||
|
||||
Next: bounded fee/slippage sensitivity with an explicit immutable financial-policy admission contract, reusing the authoritative Rust engine. Do not encode costs as strategy parameters or mutate saved templates. Keep cost scenarios separate from frozen walk-forward selection unless an explicit later study requires their combination. Performance, candidate/AI execution and multi-asset/default/paper/live activation remain gated.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First twenty-nine waves committed; durable R08 chronological validation is validated and awaits commit.** Preflight is committed as `67ab30c`; **35 of 45 scheduled tasks are fully committed (78% by count)**. The workbench now runs training, freezes its winner, evaluates validation/test and reopens immutable reports using existing durable experiments and Rust accounting. Full R08 remains partial for multi-window walk-forward and cost sensitivity; R05/R07 remain partial. Performance work stays paused.
|
||||
**First thirty waves committed; the walk-forward component is validated and awaiting commit.** Durable single-window validation is committed as `abd1c5b`; **35 of 45 scheduled tasks are fully committed (78% by count)**. Repeated windows now freeze and execute through the existing durable paths, with immutable reset-segment reports in the web workbench. Full R08 still needs bounded cost sensitivity; R05/R07 remain partial. Performance work stays paused.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -79,7 +79,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M |
|
||||
| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M |
|
||||
| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (component) | R06 component API pinned; release after integration, ADR-006 | W04 | Full-stack research product / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / in_progress (durable recipe validated) | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / in_progress (walk-forward) | R06, ADR-006 | — | Quantitative research integrity / M |
|
||||
| [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M |
|
||||
| [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M |
|
||||
| [R11 Select and reuse frozen datasets in the workbench](tasks/R11.md) | P1 / done | D01, O01, ADR-003, ADR-006 | W04 | Full-stack market data/research / M |
|
||||
|
|
@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
R06 is complete and committed as `b373410`; R08 preflight is committed as `67ab30c`. The durable single-recipe R08 component is independently reviewed and fully validated, awaiting commit. Full R08 still needs repeated walk-forward windows and cost sensitivity. R05/R07 remain partial; R09 and AI/default/trading activation retain their gates. Provider preparation is independent of experiments over retained data, and performance work remains paused.
|
||||
R06 is complete and committed as `b373410`; the durable single-recipe R08 component is committed as `abd1c5b`. Repeated walk-forward windows are in progress; bounded cost sensitivity remains a separate next slice. R05/R07 remain partial; R09 and AI/default/trading activation retain their gates. Provider preparation is independent of experiments over retained data, and performance work remains paused.
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-24.64",
|
||||
"plan_revision": "2026-10-24.66",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "thirtieth_wave_validated_awaiting_commit",
|
||||
"plan_status": "thirty_first_wave_validated_awaiting_commit",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: commit and continue; accepted chronological preflight committed 67ab30cb7a578591262cb0218fa9f6a135924c7f",
|
||||
"authorized_by": "User: commit and continue; accepted durable chronological workflow committed abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"tasks": ["R08"],
|
||||
"permissions": [
|
||||
"R08 durable single chronological recipe: immutable source and phase datasets, ordinary training experiment and fixed-winner holdout children, write-once selection/report, explicit web workflow and full regression gates"
|
||||
"R08 bounded walk-forward series: freeze all ordered recipes/common inputs, atomically admit existing training windows, reuse per-window actions and save an immutable reset-segment report with integrated web workflow"
|
||||
],
|
||||
"excluded": [
|
||||
"performance_profiling_or_optimization",
|
||||
|
|
@ -24,8 +24,8 @@
|
|||
"AI_execution_or_credentials",
|
||||
"historical_binary_provisioning",
|
||||
"cross_experiment_ranking",
|
||||
"multi_window_walk_forward_and_cost_sensitivity_execution",
|
||||
"strategy_performance_conclusions"
|
||||
"strategy_performance_conclusions",
|
||||
"cost_sensitivity_execution"
|
||||
],
|
||||
"pending_policy_decisions": [
|
||||
"ADR-007",
|
||||
|
|
@ -1444,34 +1444,33 @@
|
|||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"integration_state": "component_validated_uncommitted",
|
||||
"integration_base": "67ab30cb7a578591262cb0218fa9f6a135924c7f",
|
||||
"integration_base": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"worktree": "/home/boki/repos/stock-bot",
|
||||
"execution_component": "Durable single train/fixed-winner validation/test recipe with immutable report",
|
||||
"execution_component": "Bounded repeated walk-forward windows and immutable independent reset-segment reports",
|
||||
"component_exclusions": [
|
||||
"multi-window walk-forward/reset-series aggregation",
|
||||
"cost-sensitivity execution",
|
||||
"bounded cost-sensitivity execution",
|
||||
"findings/regime evidence integration"
|
||||
],
|
||||
"reviewed_by": "/root/r04_review",
|
||||
"verification_reference": "ROADMAP.md#thirtieth-wave-handoff--2026-10-24",
|
||||
"review_notes": "Single durable chronological recipe independently accepted and all integrated gates passed. Full R08 stays in progress for multi-window walk-forward/reset-series aggregation and cost sensitivity; R09 remains blocked.",
|
||||
"verification_reference": "ROADMAP.md#thirty-first-wave-handoff--2026-10-24",
|
||||
"review_notes": "Independent backend/frontend/root integration reviews accepted exact snapshots. Native all-window admission, immutable reports, no future suffix leakage, cancellation and receipt races, existing flow preservation and complete browser lifecycle pass. Full R08 remains partial for bounded cost sensitivity.",
|
||||
"implementation_slices": [
|
||||
{
|
||||
"owner": "/root/r12_backend",
|
||||
"worktree": "/tmp/stock-bot-wave30.K6IDyj/backend",
|
||||
"scope": "SQL24, validation service/routes, ordinary experiment compatibility, new pure/API/PostgreSQL regressions"
|
||||
"worktree": "/tmp/stock-bot-wave31.QqUT6Z/backend",
|
||||
"scope": "SQL25 header/membership guards, walk-forward service/preparation/routes, narrow transaction-scoped chronological admission/report reuse, new pure/API/PostgreSQL tests"
|
||||
},
|
||||
{
|
||||
"owner": "/root/r12_frontend",
|
||||
"worktree": "/tmp/stock-bot-wave30.K6IDyj/frontend",
|
||||
"scope": "Explicit training/selection/report UI, saved validations and focused interaction tests; symmetric submission ownership"
|
||||
"worktree": "/tmp/stock-bot-wave31.QqUT6Z/frontend",
|
||||
"scope": "Explicit window editor with shared submission ownership, series detail/list/report UI and focused regressions"
|
||||
},
|
||||
{
|
||||
"owner": "/root",
|
||||
"scope": "Shared DTO, migration registry and old fixture chains, web route composition, native/browser workflow, full gates and planning"
|
||||
"scope": "Shared DTO/export and fixture, migration registry/old fixture chains, App/index composition, actual native browser lifecycle, final gates and planning"
|
||||
}
|
||||
],
|
||||
"partial_commit": "67ab30cb7a578591262cb0218fa9f6a135924c7f"
|
||||
"partial_commit": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e"
|
||||
},
|
||||
{
|
||||
"id": "R09",
|
||||
|
|
@ -3340,7 +3339,7 @@
|
|||
"files": 1153,
|
||||
"scope": "Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded."
|
||||
},
|
||||
"workload": "1k/10k total bars;1asset/1owner or10assets/2owners;2fresh processes \u00d72fresh native sessions, second reverses callback evaluation. Alternating unit targets,1% fee,initialcapital1000000,600bars/session with retained gaps. No randomness, storage, queue, indicators or parallel simulation.",
|
||||
"workload": "1k/10k total bars;1asset/1owner or10assets/2owners;2fresh processes ×2fresh native sessions, second reverses callback evaluation. Alternating unit targets,1% fee,initialcapital1000000,600bars/session with retained gaps. No randomness, storage, queue, indicators or parallel simulation.",
|
||||
"equality": "Exact complete normalized result hashes match every repeat and debug/release profile. Independent integer-cent cash/equity/remaining basis/owner fees/fill count oracle passes. Economically different results invalidate measurement.",
|
||||
"timing": "Report separates imports, detached D01 verify, once-per-child prepared-JS mapping, fresh native load, actual advance/submit/decision/finalize and validation/hash. Native call timers include JS encoding/schema/immutable projection plus Rust work/serialization, not pure crossing cost. Trial wall includes load+replay+finalization+oracle/hash, excludes one-time preparation/import and parent aggregation. No explicit warmup or OS-cache flush; means only, not latency distributions. Shared host; release focused checks briefly overlapped initial measurement, so not an isolated performance SLA.",
|
||||
"workloads": [
|
||||
|
|
@ -5227,7 +5226,7 @@
|
|||
"Two separate processes per mode, two fresh timed sessions each, counterbalanced mode order. Second SMA session reverses owner callback order and must preserve financial and diagnostic hashes. This checks fresh whole-attempt recomputation, not native checkpoint resume.",
|
||||
"Shared host, no timing assertion, confidence interval, cold-start SLA, or cross-artifact performance attribution. Root must freeze source and use the matching release addon before execution."
|
||||
],
|
||||
"interpretation": "Verified aggregate host/strategy/state overhead, not per-function attribution. Long-window decision phase is about51\u201362%of total owner-dense wall. Profiles in P08 must distinguish schema parsing, copying/freezing, trailing calculations and allocation before optimization. No cross-shape scaling or S02 speedup claim."
|
||||
"interpretation": "Verified aggregate host/strategy/state overhead, not per-function attribution. Long-window decision phase is about51–62%of total owner-dense wall. Profiles in P08 must distinguish schema parsing, copying/freezing, trailing calculations and allocation before optimization. No cross-shape scaling or S02 speedup claim."
|
||||
},
|
||||
"cleanup": {
|
||||
"stopped_exact_containers": [
|
||||
|
|
@ -6901,7 +6900,7 @@
|
|||
"R08 remains partial for multiple walk-forward windows and cost sensitivity. R09 and performance/default/trading/AI gates unchanged."
|
||||
],
|
||||
"thirtieth_wave_validation": {
|
||||
"state": "component_validated_uncommitted",
|
||||
"state": "component_committed",
|
||||
"scope": "R08 durable single train/fixed-winner validation/test recipe and immutable report; full R08 remains in_progress and R09 blocked",
|
||||
"integration_base": "67ab30cb7a578591262cb0218fa9f6a135924c7f",
|
||||
"log_directory": "/tmp/stock-bot-wave30.K6IDyj",
|
||||
|
|
@ -7017,6 +7016,132 @@
|
|||
"An initial manually built browser fixture used the local VITE API override; its network guard rejected login. Rebuilding with explicit same-origin VITE_API_BASE_URL fixed the setup; both focused and final complete browser suites passed. No application change or test retry hid a source failure."
|
||||
],
|
||||
"cleanup": "Both exact disposable PostgreSQL/Redis containers stopped successfully after all suites completed. 38 source/test files archived and hashed; worktrees/logs retained. Development/production services and data untouched.",
|
||||
"next": "Accept/commit this durable single-recipe component, then finish R08 with explicit repeated nonoverlapping walk-forward windows and bounded cost sensitivity through the existing recipe/experiment paths. Preserve immutable per-window winners and separate reset-account reports; avoid a general workflow scheduler. Keep performance, candidate/AI execution and default/trading activation gated."
|
||||
"next": "Accept/commit this durable single-recipe component, then finish R08 with explicit repeated nonoverlapping walk-forward windows and bounded cost sensitivity through the existing recipe/experiment paths. Preserve immutable per-window winners and separate reset-account reports; avoid a general workflow scheduler. Keep performance, candidate/AI execution and default/trading activation gated.",
|
||||
"completed_commit": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e"
|
||||
},
|
||||
"thirty_first_wave": ["R08"],
|
||||
"thirty_first_wave_base": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"thirty_first_wave_notes": [
|
||||
"Walk-forward only: cost scenarios change financial-policy admission and stay a separate next slice. No template mutation or cost-as-strategy-parameter workaround.",
|
||||
"Focused research_walk_forwards header plus train-root membership columns; every member remains an existing standalone chronological validation. Avoid overloading first-window cancellation.",
|
||||
"Freeze 2–10 recipes/common source/grid/build/policies before any execution; total promised training plus future holdouts<=100. Nondecreasing training starts, strictly increasing train cutoffs and previous test.end<=next validation.start.",
|
||||
"Atomic all-training admission with exact deferred membership/run/outbox guards. Existing member select/finalize/retry paths reused; no scheduler or automatic advancement.",
|
||||
"Historical series finalization verifies full canonical evidence and every sealed member report, copying ordered validation/test reset segments without compounding or new analytics. Accepted receipts replay before current eligibility.",
|
||||
"Whole-series cancellation propagates downward to every member; local member cancellation remains local and blocks series completion. SQL22–24 files remain unchanged.",
|
||||
"Performance remains paused. Full R08 stays partial for cost sensitivity; R09 and candidate/AI/multi-asset/default/trading activation gates unchanged."
|
||||
],
|
||||
"thirty_first_wave_validation": {
|
||||
"state": "component_validated_uncommitted",
|
||||
"scope": "R08 bounded repeated walk-forward windows and immutable independent reset-segment reports; full R08 remains in_progress for cost sensitivity and R09 blocked",
|
||||
"integration_base": "abd1c5b83d55ad49b562408cb3a87a1c7b7f952e",
|
||||
"log_directory": "/tmp/stock-bot-wave31.QqUT6Z",
|
||||
"source_archive": "/tmp/stock-bot-wave31.QqUT6Z/validated-source.tar.gz",
|
||||
"source_archive_sha256": "ff10c4fe33033d5a4e33c68cfb1d8f6633ce885ccc7d95bf5a4e2ff408c55818",
|
||||
"source_files": {
|
||||
"apps/stock/config/package.json": "802bc6005690386786d536758c3d49f9a5929e193bb14760dd2b7e0880f25bea",
|
||||
"apps/stock/config/src/contracts/walk-forward.ts": "823632db7935aaa729a8b9aba925e74db117553b1ca9eaea027a0637ab96fe92",
|
||||
"apps/stock/web-api/src/migrations/migration-runner.ts": "819e13509f052ff81ea8021ab0eb2e975bd699fd87b42efba9ecc5c2eabe0879",
|
||||
"apps/stock/web-api/src/routes/experiments.routes.ts": "d959a1dbedf158c6dbb1eb39e28354fe8d31bc13bbceaaafc0c474deff60a2ad",
|
||||
"apps/stock/web-api/src/services/chronological-validation.service.ts": "51ac51167351d496c67fd9154c696ce7eb33be4b4af14c7fdce429a5224db349",
|
||||
"apps/stock/web-api/src/services/walk-forward-input.ts": "7f4dc96c449bb09d075b027b5c4e2f26f38b6bc0a1498a8338d830d96647bdde",
|
||||
"apps/stock/web-api/src/services/walk-forward.service.ts": "357a2a3e29f9e78329003186835669d74096c5f3f5ae93a859af4570b5b77596",
|
||||
"apps/stock/web-app/src/app/App.tsx": "0a882a55c98f53d0fe2f246f1f3536b27990c9ad3bd35a2bdcbca4e8463f187d",
|
||||
"apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx": "8afe33d1fd4836e4209ebd62bbb05e168c938cd7cc89bc8da9fb43d3b2f2d03a",
|
||||
"apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx": "671dd0aff2d42f83cc776bc101b65fcf2dccfb3be44d24e6a6eea530127a34d2",
|
||||
"apps/stock/web-app/src/features/experiments/components/ChronologicalValidationPreflight.tsx": "8f135323ddac45fc38294a488afd0cf8216aae4c3df59dd2c38ce0aaf97cdaff",
|
||||
"apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx": "77a4586120a60550d58e331227fca0b85a7801dda5f76bd7c9eedc6c8b7586d2",
|
||||
"apps/stock/web-app/src/features/experiments/components/SavedWalkForwards.tsx": "10ee1ff4340c2c24a31b09f3653ae4b314b03353be19f1b3ab7345b1d24e3015",
|
||||
"apps/stock/web-app/src/features/experiments/components/ValidationWindowFields.tsx": "a7bf21462f58e277ae3939355cd1a56cdb6eefd3cced654b1182dd159887400c",
|
||||
"apps/stock/web-app/src/features/experiments/components/WalkForwardPreflight.tsx": "7550d4027b8df56c24568de74b56b71f3814c8bc4a837ffce145acf91d8ac729",
|
||||
"apps/stock/web-app/src/features/experiments/index.ts": "65cec87cea6e4b5b30df231bfbcc4b52caccd340d5dd9a68b72e0d1596411308",
|
||||
"apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi.ts": "ed90d1c5211fec8850507984ada72216c83c17be4077196a37ad436a3980463a",
|
||||
"apps/stock/web-app/src/features/experiments/services/walkForwardApi.ts": "2fe8c8e23e7e108fd117db3eb4cc35fe9ebd3d0c9a76733b685156bb4f65495d",
|
||||
"database/postgres/init/25-walk-forward.sql": "bc30037f303c67cd431e904fd251671fa88210b888dcee75799b0cc4a55e64df",
|
||||
"test/e2e/fixture.ts": "10b19b3723a8c24a08af1d9dbacf9a639e1e733a119f02a09017dba2d071e3a6",
|
||||
"test/e2e/workbench.test.ts": "24253213d7efdb4c7750990338fc7be1b3468dc40655f44b4c542ad03c17c8f6",
|
||||
"test/fixtures/walk-forward.ts": "e0ec22545c3aa74c703808fcc4785f475feb13395ac3904323f52dd16072963f",
|
||||
"test/integration/chronological-validation-ui.test.tsx": "f59c5cf66a1e46c8ddd0a5c3ebc623a57c7d7b111e99988c59580dc452fcebdf",
|
||||
"test/integration/walk-forward-api.test.ts": "bd6fc7fe02e6c89150b467191912d9a6251660cd16582a5ae3fd55d8538b89d1",
|
||||
"test/integration/walk-forward-ui.test.tsx": "eaaa96110baae8bf6065222da1acb8cc89d9ea416692cdcd71e1d7834242f08d",
|
||||
"test/integration/walk-forward.test.ts": "f4864edb4bd69944407eff49ece4ba1e1c554872caacc33d15c8c221d475dafb",
|
||||
"test/postgres/canonical-durable-backtest.test.ts": "252e30fea1e3e86b1278c6b0f60b0f632714407a6fa141915b16c70774648a8f",
|
||||
"test/postgres/canonical-research.test.ts": "d03b7b8a2876f3662d85c009ddea0e5a9812c2b6a11b3475185fd6d3606c9325",
|
||||
"test/postgres/catalog-backtest-drafts.test.ts": "a8af8e65f1899303513e0e0efb817e59a192ffb92bab8d925d09b390cdff5be6",
|
||||
"test/postgres/chronological-validation-durable.test.ts": "13976744faaca453a8e151777a12d36321b235a4978384f2220083375c25c855",
|
||||
"test/postgres/chronological-validation.test.ts": "1a181f21bc399f3aae924d2a62f61f1e6e1b166c498445ee8e6711fe3153610f",
|
||||
"test/postgres/dataset-catalog.test.ts": "003666a7fe9ba460c5c6b9869d353a43a9356529e880a4c255d73c10fe4f6ec1",
|
||||
"test/postgres/durable-backtest.test.ts": "b7afc78dc689349c9d832c0bb348fb0c7ff9fe9e7f0278e6f8bf71e673e3fb7c",
|
||||
"test/postgres/experiment-retries.test.ts": "f6a73e6a6d409bd52ba5abcc937052b4bb090be73323f9857bf3d4c531197405",
|
||||
"test/postgres/experiments.test.ts": "1f3fbfda8f164dcda1832d6cff7d3909fad8c0e63de7414fd431a74f3b66d2d1",
|
||||
"test/postgres/migration-runner.test.ts": "c2865ad88c2def8d19f6fd2e4cbb8893657311813d19d0887bb09c4dbc455d7a",
|
||||
"test/postgres/research-retention.test.ts": "98ec033a93ddf4129160654dc3fa85687c34a912d47d54c17e6ce0c8d3df49a2",
|
||||
"test/postgres/research-runtime-isolation.test.ts": "359a887febbbab359ce2a04f1cb67ea4ae5b82eeabf8f35e76126c6e465e109a",
|
||||
"test/postgres/research-workspace.test.ts": "8cc154401e69a7b3d8c0e4c303644a350ad79d08cf166dac024c4730713a69e5",
|
||||
"test/postgres/run-reproduction.test.ts": "d3a76cbcd072e3e1edda11f9b8e468afc953f8195a307873aa61434e5a9235ea",
|
||||
"test/postgres/walk-forward.test.ts": "cd11f3f5d64301a4ac64b536a07ee5af7e4b72c8dad9002e61b6342bd2695676"
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "integration-check-final.log",
|
||||
"exit_code": 1,
|
||||
"result": "Secret audit, build, types, contracts, 93 tooling, 43 utility, 44 calculation, 882 integration and 150 Rust tests passed; only one remaining route curly lint error failed. Corrected with braces only; final repository lint and source types passed separately below. Four existing Rust cases remain ignored."
|
||||
},
|
||||
{
|
||||
"command": "bun run lint:check; bun run typecheck",
|
||||
"logs": ["integration-lint-final.log", "integration-types-final.log"],
|
||||
"result": "Both passed after final reviewed brace/format fixes; no application behavior changed."
|
||||
},
|
||||
{
|
||||
"command": "bun test test/integration/walk-forward.test.ts test/integration/walk-forward-api.test.ts",
|
||||
"log": "integration-backend-focused-final.log",
|
||||
"result": "7 passed, 83 assertions; final brace-only test overlay also passed owner rerun backend-focused-final.log."
|
||||
},
|
||||
{
|
||||
"command": "bun run test:postgres",
|
||||
"log": "integration-postgres-final.log",
|
||||
"result": "215 passed, 1881 assertions, zero failures; disposable PostgreSQL and Redis DB15."
|
||||
},
|
||||
{
|
||||
"command": "bun run test:e2e",
|
||||
"log": "integration-browser-final.log",
|
||||
"result": "14 passed, 412 assertions, zero failures; same-origin production rebuild and real Chromium/native runner."
|
||||
},
|
||||
{
|
||||
"command": "Strict authored test TypeScript; explicit authored test ESLint",
|
||||
"logs": ["root-tests-types-final.log", "authored-tests-lint-final.log"],
|
||||
"result": "Passed. Broad lint of all touched old test fixtures found eight preexisting curly violations in durable-backtest.test.ts and research-runtime-isolation.test.ts; only their migration lists changed. New authored tests are clean."
|
||||
},
|
||||
{
|
||||
"command": "Prettier changed TS/TSX/JSON; git diff --check; task references/dependency DAG",
|
||||
"result": "Passed; 55 unique IDs, valid references and acyclic implementation dependencies."
|
||||
}
|
||||
],
|
||||
"review": {
|
||||
"independent_reviewer": "/root/r04_review",
|
||||
"backend": "Accepted final eight-file v2 snapshot; only three tests changed for braces after initial acceptance, no semantics changed. Own pure/API 7/83 and reviewed PG 10/108.",
|
||||
"backend_archive": "/tmp/stock-bot-wave31.QqUT6Z/backend-final-v2.tar",
|
||||
"backend_archive_sha256": "f8ed5599fc27be0c8cbe660a41e623803f31e2fc9ca15eca12e216cac21499dc",
|
||||
"frontend": "Accepted final 11-file snapshot; independent focused UI 50/154 and owner combined UI 285/1305.",
|
||||
"frontend_archive": "/tmp/stock-bot-wave31.QqUT6Z/frontend-final.tar.gz",
|
||||
"frontend_archive_sha256": "8bfd0d8d9296f3903697906683a481a7727cbbc675a0c9b0ee8f58e88336f45b",
|
||||
"root_composition": "Read-only independent reviews of shared DTO/fixture, App/index, old migration chains and real native browser flow accepted."
|
||||
},
|
||||
"engine": {
|
||||
"debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff",
|
||||
"release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103",
|
||||
"note": "Unchanged financial engine. Release restored before final PostgreSQL and browser suites."
|
||||
},
|
||||
"limits": [
|
||||
"2–10 explicit windows; at most 100 planned runs including both future holdouts per window.",
|
||||
"Deterministic registered built-ins and zero label horizon only; no trained models, candidate execution or AI authorization.",
|
||||
"Training may overlap earlier historical holdouts; frozen recipes and own-training-only selection do not certify globally unseen data.",
|
||||
"Separate reset-account validation/test segments, not compounded equity or averaged Sharpe/CAGR; execution completeness is not statistical adequacy.",
|
||||
"Per-window existing actions remain explicit; no scheduler or automatic advancement. Ambiguous browser intent remains component-lifetime state.",
|
||||
"Bounded cost sensitivity remains the next R08 slice; no cost-as-strategy-parameter workaround or template mutation.",
|
||||
"Performance work, R09 evidence integration and candidate/AI/multi-asset/default/paper/live activation gates remain unchanged."
|
||||
],
|
||||
"fixture_cleanup": "Removed both exact disposable PostgreSQL/Redis containers after all final gates; development services untouched. Worktrees and local evidence retained.",
|
||||
"commits": "Previous wave committed as abd1c5b. This validated component remains uncommitted; no push or PR."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ Scheduling source of truth: [manifest entry R08](../manifest.json). No task is a
|
|||
|
||||
## Intended behavior and implementation scope
|
||||
|
||||
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Aggregate segment returns as a labelled reset-segment research series, never claim one continuous tradable equity curve. Cost/parameter sensitivity reuses grid expansion. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
|
||||
First implement bounded chronological parameter selection and nonoverlapping walk-forward recipes for deterministic registered strategies. Explicit warmup and evaluation windows; each validation segment starts from its declared initial capital and empty positions with warmed indicators, not carried money/state. Aggregate segment returns as a labelled reset-segment research series, never claim one continuous tradable equity curve. Parameter sensitivity reuses the existing bounded grid. Cost sensitivity needs a separate explicit immutable financial-policy admission contract; costs are not strategy parameters and must not mutate saved templates. Reject trainable/overlapping-label models until their fit-artifact and declared horizon/embargo contracts are supplied; do not invent general ML infrastructure for SMA.
|
||||
|
||||
Persist the immutable validation manifest/report as experiment-owned JSON on the R06 experiment (or a focused child row if immutability requires it), keyed by experiment/report version and containing every contributing run ID, selection rule and segment policy. This is not R03 research-findings storage. Reopening an experiment must recover the same report; new inputs require a new experiment/report identity.
|
||||
|
||||
|
|
@ -79,7 +79,7 @@ This component is explicitly **prepared input, not durable experiment evidence**
|
|||
|
||||
### Validated preflight handoff
|
||||
|
||||
The first component is independently reviewed and `component_validated_uncommitted`; full R08 remains `in_progress`. Exact bars and legacy conversion provenance survive slicing; immediate source lineage stays in the outer preview. Warmup diagnostics respect actual availability and retained strategy ordering, including observations at/after the evaluation end. Existing account-clock calculation is reused for each phase without changing financial policy.
|
||||
The first component is independently reviewed and committed as `67ab30c`; full R08 remains `in_progress`. Exact bars and legacy conversion provenance survive slicing; immediate source lineage stays in the outer preview. Warmup diagnostics respect actual availability and retained strategy ordering, including observations at/after the evaluation end. Existing account-clock calculation is reused for each phase without changing financial policy.
|
||||
|
||||
Full repository checks passed (786 integration /150 Rust tests), PostgreSQL (194 tests /1655 assertions), Chromium (12 workflows /306 assertions), strict test types, lint and formatting. Native regressions prove independent initial cash/positions/state, no warmup orders/fills and earlier-phase invariance to a changed test suffix. Browser/database tests prove preview makes no retained-data/job/template writes. Hashes and logs: `manifest.json` → `twenty_ninth_wave_validation`.
|
||||
|
||||
|
|
@ -95,6 +95,22 @@ The web supports saved validations, training admission, selection, heldout progr
|
|||
|
||||
### Validated durable handoff
|
||||
|
||||
The single-recipe component is independently accepted and `component_validated_uncommitted`. Shared Rust economics, ordinary runs/outbox, SQL22/23 retry semantics and original evidence are preserved. All repository gates pass (825 integration /150 Rust tests), PostgreSQL/Redis 205 tests /1773 assertions, Chromium 13 workflows /357 assertions, strict test types and lint. Exact source hashes and review evidence: `manifest.json` → `thirtieth_wave_validation`.
|
||||
The single-recipe component is independently accepted and committed as `abd1c5b`. Shared Rust economics, ordinary runs/outbox, SQL22/23 retry semantics and original evidence are preserved. All repository gates pass (825 integration /150 Rust tests), PostgreSQL/Redis 205 tests /1773 assertions, Chromium 13 workflows /357 assertions, strict test types and lint. Exact source hashes and review evidence: `manifest.json` → `thirtieth_wave_validation`.
|
||||
|
||||
The UI supports the complete staged lifecycle and immutable report reopening. Native regressions prove unchanged training scores/winner after modifying only future test prices; malformed or missing candidate evidence cannot seal selection. Atomicity, SQL tamper, receipt/cancel races, migration preservation and phase retries pass. Full R08 remains incomplete for repeated walk-forward windows/reset-series aggregation and bounded cost sensitivity. R09 remains blocked. No performance or trading/default/AI activation occurred.
|
||||
|
||||
## Authorized repeated-window component — 2026-10-24
|
||||
|
||||
The durable single-window workflow is accepted and committed as `abd1c5b`. Implement bounded walk-forward series now; cost sensitivity remains separate because it needs an explicit financial-policy admission branch. Freeze 2–10 ordered recipes and common source/build/grid/policies before any member runs. Count every planned training candidate and both future holdouts against the 100-run bound. Training starts cannot decrease, training cutoffs strictly increase, and each test end must be no later than the next validation start. Existing per-window boundary/warmup checks remain authoritative.
|
||||
|
||||
A focused series header and immutable train-root memberships preserve existing single-window semantics; SQL22–24 files remain unchanged. Admission of all member roots/slices/runs/outbox is atomic. Reuse per-window actions and ordinary retries; no bulk-select scheduler or general workflow framework. Whole-series cancellation reaches all windows, while local member cancellation only blocks series completion. Historical finalization verifies every sealed report and its canonical result facts, copying ordered validation/test reset segments without new financial or statistical formulas. Receipt replay precedes mutable eligibility.
|
||||
|
||||
The web provides explicit windows, preview, submission, member links, report save/reopen and honest missing/failed/cancelled states. Required proofs include total budget/chronology, later-suffix independence, partial-admission rollback, exact immutable membership, receipt/cancel races, old evidence preservation, pool1 transactions and the full two-window native browser lifecycle. Full R08 remains partial for bounded cost scenarios after this component.
|
||||
|
||||
### Validated walk-forward handoff
|
||||
|
||||
The repeated-window component is independently accepted and `component_validated_uncommitted`. Forty-one source/test/config files preserve the existing Rust financial engine, worker/run/outbox model and SQL22–24 behavior. New SQL25 headers and exact train-root membership guards keep all-window admission atomic; full native evidence is checked again before sealing an immutable ordered reset-segment report. Member cancellation stays local; series cancellation prevents new member actions without changing completed evidence.
|
||||
|
||||
The web supports explicit 2–10-window recipes, full promised-run counts, synchronous shared submission ownership, member actions through existing pages, and saved report reopen. Native tests prove future-suffix independence, unchanged old migrations/receipts/leases, partial-admission rollback, actual lock contention, finalization receipt races and rejection of corrupted financial/analytics evidence. Repository test gates pass (882 integration /150 Rust), PostgreSQL/Redis 215 tests /1881 assertions, Chromium 14 workflows /412 assertions; final source and authored-test lint/types pass. Exact commands, formatting-only corrections and old fixture lint limitations are recorded in `manifest.json` → `thirty_first_wave_validation`.
|
||||
|
||||
Full R08 remains partial for bounded cost sensitivity; R09 remains blocked. Next scope should define supported fee/slippage scenarios as immutable execution-policy inputs and reuse canonical runs/results, without template mutation, strategy-parameter hacks, a second simulator or a window×cost scheduler. No regime/finding integration, performance work or AI/default/trading activation is included.
|
||||
|
|
|
|||
|
|
@ -296,6 +296,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import type {
|
|||
ChronologicalValidationActionResult,
|
||||
ChronologicalValidationDetail,
|
||||
ChronologicalValidationPreview,
|
||||
ChronologicalValidationReport,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
|
|
@ -16,10 +17,16 @@ import type {
|
|||
ExperimentRetryResult,
|
||||
ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import type {
|
||||
WalkForwardActionResult,
|
||||
WalkForwardDetail,
|
||||
WalkForwardPreview,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
import {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
|
|
@ -42,6 +49,224 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_report_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const { dataset, windows } = walkForwardDataset();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed bounded walk-forward native browser fixture',
|
||||
});
|
||||
const definition = {
|
||||
name: 'Walk-forward native template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: dataset.manifest.series[0]!.interval,
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
};
|
||||
const backtest = await f.request('/api/v2/backtests', 'POST', {
|
||||
...definition,
|
||||
autoStart: false,
|
||||
});
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
|
||||
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Frozen rolling windows');
|
||||
await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
|
||||
await f.page.getByText('Walk-forward validation', { exact: true }).click();
|
||||
for (const [index, recipe] of windows.entries()) {
|
||||
for (const phase of ['Train', 'Validation', 'Test'] as const) {
|
||||
const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test'];
|
||||
for (const [label, value] of [
|
||||
['warmup start', window.warmupStart],
|
||||
['trading start', window.tradeStart],
|
||||
['trading end', window.tradeEnd],
|
||||
] as const) {
|
||||
await f.page
|
||||
.getByLabel(`Window ${index + 1} ${phase} ${label} (UTC)`, { exact: true })
|
||||
.fill(new Date(value).toISOString());
|
||||
}
|
||||
}
|
||||
}
|
||||
const preparing = f.page.waitForResponse(r =>
|
||||
r.url().endsWith('/api/v2/experiments/walk-forward/preview')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Preview walk-forward', exact: true }).click();
|
||||
const prepared = await preparing;
|
||||
expect(prepared.status()).toBe(200);
|
||||
const { preview } = (await prepared.json()) as { preview: WalkForwardPreview };
|
||||
expect(preview.input.windows).toEqual(windows);
|
||||
expect(preview.counts).toEqual({
|
||||
windows: 2,
|
||||
trainingRuns: 4,
|
||||
holdoutRuns: 4,
|
||||
totalRuns: 8,
|
||||
maxRuns: 100,
|
||||
});
|
||||
expect((await f.pool.query('SELECT * FROM research_walk_forwards')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
const submitting = f.page.waitForResponse(
|
||||
r => r.request().method() === 'POST' && r.url().endsWith('/api/v2/experiments/walk-forward')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Submit walk-forward training', exact: true }).click();
|
||||
const accepted = await submitting;
|
||||
expect(accepted.status()).toBe(202);
|
||||
const { walkForward: initial } = (await accepted.json()) as { walkForward: WalkForwardDetail };
|
||||
const endpoint = `/api/v2/experiments/walk-forward/${initial.id}`;
|
||||
const route = `${f.origin}/experiments/walk-forward/${initial.id}`;
|
||||
expect(accepted.headers().location).toBe(endpoint);
|
||||
expect(initial.preview).toEqual(preview);
|
||||
expect(initial.windows.map(w => w.index)).toEqual([0, 1]);
|
||||
expect(
|
||||
initial.windows.every(w => w.status === 'admitted' && w.validation?.selection === null)
|
||||
).toBe(true);
|
||||
expect(initial.actions.finalize.available).toBe(false);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(4);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(4);
|
||||
await f.page.waitForURL(route);
|
||||
// Every member already owns its frozen source before any native training starts.
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Edited after frozen series',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
|
||||
'4',
|
||||
'all training windows complete'
|
||||
);
|
||||
const childReports: ChronologicalValidationReport[] = [];
|
||||
for (const member of initial.windows) {
|
||||
await f.page.getByRole('button', { name: 'Refresh walk-forward', exact: true }).click();
|
||||
await f.page
|
||||
.getByRole('link', { name: `Open window ${member.index + 1} validation`, exact: true })
|
||||
.click();
|
||||
await f.page.waitForURL(`${f.origin}/experiments/validation/${member.validationId}`);
|
||||
const selecting = f.page.waitForResponse(r =>
|
||||
r.url().endsWith(`/validation/${member.validationId}/select`)
|
||||
);
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Freeze selection and run holdouts', exact: true })
|
||||
.click();
|
||||
const selectionResponse = await selecting;
|
||||
expect(selectionResponse.status()).toBe(202);
|
||||
const selected = (await selectionResponse.json()) as ChronologicalValidationActionResult;
|
||||
const holdoutIds = selected.validation.phases
|
||||
.slice(1)
|
||||
.map(p => p.experiment!.trials[0]!.runId!);
|
||||
await until(
|
||||
async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*) FROM runs WHERE id=ANY($1::uuid[]) AND status='completed'",
|
||||
[holdoutIds]
|
||||
)
|
||||
).rows[0].count === '2',
|
||||
'member holdouts complete'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
|
||||
const finalizing = f.page.waitForResponse(r =>
|
||||
r.url().endsWith(`/validation/${member.validationId}/finalize`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save validation report', exact: true }).click();
|
||||
const memberResponse = await finalizing;
|
||||
expect(memberResponse.status()).toBe(202);
|
||||
const memberResult = (await memberResponse.json()) as ChronologicalValidationActionResult;
|
||||
childReports.push(memberResult.validation.report!);
|
||||
await visible(f.page, 'Execution complete · report saved');
|
||||
await f.page.goto(route);
|
||||
await visible(f.page, 'Frozen rolling windows');
|
||||
const state = (await f.request(endpoint)).walkForward as WalkForwardDetail;
|
||||
expect(state.reportedWindowCount).toBe(member.index + 1);
|
||||
if (member.index === 0) {
|
||||
expect(state.actions.finalize.available).toBe(false);
|
||||
expect(
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Save walk-forward report', exact: true })
|
||||
.isDisabled()
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [backtest.id]);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
|
||||
await f.page.getByRole('button', { name: 'Refresh walk-forward', exact: true }).click();
|
||||
const finalizing = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/finalize`));
|
||||
await f.page.getByRole('button', { name: 'Save walk-forward report', exact: true }).click();
|
||||
const response = await finalizing;
|
||||
expect(response.status()).toBe(202);
|
||||
const completed = (await response.json()) as WalkForwardActionResult;
|
||||
const report = completed.walkForward.report!;
|
||||
expect(completed.receipt.id).toBe(report.id);
|
||||
expect(completed.receipt.reportHash).toBe(report.reportHash);
|
||||
expect(report.reset).toBe('initial-capital-empty-positions');
|
||||
expect(report.segments).toHaveLength(2);
|
||||
for (const [index, segment] of report.segments.entries()) {
|
||||
const child = childReports[index]!;
|
||||
expect(segment.index).toBe(index);
|
||||
expect(segment.validationId).toBe(initial.windows[index]!.validationId);
|
||||
expect(segment.reportId).toBe(child.id);
|
||||
expect(segment.reportHash).toBe(child.reportHash);
|
||||
expect(segment.selectionHash).toBe(child.selectionHash);
|
||||
expect(segment.validation).toEqual(child.validation);
|
||||
expect(segment.test).toEqual(child.test);
|
||||
const result = (await f.request(
|
||||
`/api/v2/runs/${segment.test.runId}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(segment.test.metrics).toEqual(result.analytics.metrics);
|
||||
expect(segment.test.unavailable).toEqual(result.analytics.unavailable);
|
||||
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'10000.00000000'
|
||||
);
|
||||
}
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(6);
|
||||
await visible(f.page, 'Execution complete · walk-forward report saved');
|
||||
const replay = (await f.request(
|
||||
`${endpoint}/finalize`,
|
||||
'POST',
|
||||
response.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': response.request().headers()['idempotency-key']! }
|
||||
)) as WalkForwardActionResult;
|
||||
expect(replay.receipt).toEqual(completed.receipt);
|
||||
expect(replay.walkForward.report).toEqual(report);
|
||||
const submitReplay = await f.request(
|
||||
'/api/v2/experiments/walk-forward',
|
||||
'POST',
|
||||
accepted.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': accepted.request().headers()['idempotency-key']! }
|
||||
);
|
||||
expect(submitReplay.walkForward.id).toBe(initial.id);
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Execution complete · walk-forward report saved');
|
||||
expect((await f.request(endpoint)).walkForward.report).toEqual(report);
|
||||
await f.page.goto(`${f.origin}/experiments`);
|
||||
await visible(f.page, 'Saved walk-forward validations');
|
||||
await f.page.locator(`a[href="/experiments/walk-forward/${initial.id}"]`).click();
|
||||
await visible(f.page, 'Execution complete · walk-forward report saved');
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('chronological_preflight_checks_explicit_windows_without_admitting_or_saving_work_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
|
|
|
|||
50
test/fixtures/walk-forward.ts
vendored
Normal file
50
test/fixtures/walk-forward.ts
vendored
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import type { WalkForwardInput } from '@stock-bot/stock-config/walk-forward';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { nativeReplayFixture } from './native-replay';
|
||||
|
||||
/** Two explicit rolling windows; only the later test suffix changes in isolation regressions. */
|
||||
export function walkForwardDataset(laterTestPrice?: number) {
|
||||
const fixture = nativeReplayFixture(72);
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
fixture.dataset.manifest;
|
||||
const closes = [3, 2, 1, 4, 5, 1, 1, 3, 6, 2, 1, 4];
|
||||
const dataset = createDatasetV2({
|
||||
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
||||
bars: fixture.dataset.bars.map((bar, index) => {
|
||||
const close =
|
||||
index >= 64 && laterTestPrice !== undefined
|
||||
? laterTestPrice + index
|
||||
: closes[index % closes.length]!;
|
||||
const open = index === 0 ? 3 : closes[(index - 1) % closes.length]!;
|
||||
return {
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart,
|
||||
availableAt: bar.availableAt,
|
||||
sourceSequence: bar.sourceSequence,
|
||||
open,
|
||||
close,
|
||||
high: Math.max(open, close),
|
||||
low: Math.min(open, close),
|
||||
volume: 1000,
|
||||
};
|
||||
}),
|
||||
});
|
||||
const at = (step: number) => fixture.start + step * fixture.minute;
|
||||
const windows: WalkForwardInput['windows'] = [
|
||||
{
|
||||
version: 1,
|
||||
labelHorizonMs: 0,
|
||||
train: { warmupStart: at(0), tradeStart: at(6), tradeEnd: at(12) },
|
||||
validation: { warmupStart: at(10), tradeStart: at(16), tradeEnd: at(24) },
|
||||
test: { warmupStart: at(22), tradeStart: at(28), tradeEnd: at(36) },
|
||||
},
|
||||
{
|
||||
version: 1,
|
||||
labelHorizonMs: 0,
|
||||
train: { warmupStart: at(24), tradeStart: at(30), tradeEnd: at(48) },
|
||||
validation: { warmupStart: at(46), tradeStart: at(52), tradeEnd: at(60) },
|
||||
test: { warmupStart: at(58), tradeStart: at(64), tradeEnd: at(72) },
|
||||
},
|
||||
];
|
||||
return { ...fixture, dataset, windows };
|
||||
}
|
||||
|
|
@ -582,9 +582,7 @@ describe('chronological validation preflight', () => {
|
|||
expect(button('Preview chronological validation').disabled).toBe(true);
|
||||
expect(field('Train warmup start (UTC)').closest('fieldset')!.disabled).toBe(true);
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
expect(host.textContent).toContain(
|
||||
'Resolve or explicitly release the ordinary sweep submission'
|
||||
);
|
||||
expect(host.textContent).toContain('Resolve or explicitly release the other submission');
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(button('Preview chronological validation').disabled).toBe(false);
|
||||
expect(field('Train warmup start (UTC)').value).toBe(
|
||||
|
|
|
|||
125
test/integration/walk-forward-api.test.ts
Normal file
125
test/integration/walk-forward-api.test.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
const tokens = {
|
||||
operator: 'validation-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'validation-service-fixture-not-a-real-secret-1234',
|
||||
read: 'validation-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const input = {
|
||||
backtestId: randomUUID(),
|
||||
name: 'Validation preview',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
windows: walkForwardDataset().windows,
|
||||
};
|
||||
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
||||
function fixture(
|
||||
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => ({ rows: [] })
|
||||
) {
|
||||
const client = { query: mock(query) };
|
||||
const database = {
|
||||
...client,
|
||||
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
|
||||
};
|
||||
const app = new Hono();
|
||||
if (mode !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: mode === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
|
||||
return {
|
||||
database,
|
||||
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
|
||||
return app.request('/api/v2/experiments/walk-forward' + path, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
...(key ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const id = randomUUID(),
|
||||
previewHash = 'a'.repeat(64);
|
||||
|
||||
const actions = [
|
||||
['/preview', JSON.stringify(input)],
|
||||
['', JSON.stringify({ ...input, previewHash })],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash })],
|
||||
[`/${id}/cancel`, '{}'],
|
||||
];
|
||||
describe('walk-forward HTTP gates', () => {
|
||||
test('writes need real operator/service proof, readers may inspect only', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
|
||||
}
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, 'read', 'key')).status).toBe(403);
|
||||
}
|
||||
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
|
||||
expect((await f.request(`/${id}`, 'GET', undefined, 'read')).status).toBe(404);
|
||||
expect((await f.request()).status).toBe(401);
|
||||
});
|
||||
test('strict malformed, reserved, missing-key and mixed-operation inputs fail before storage', async () => {
|
||||
const cases: [string, string, string | undefined][] = [
|
||||
['/preview', '{', 'key'],
|
||||
['/preview', JSON.stringify({ ...input, winner: 0 }), 'key'],
|
||||
['/preview', JSON.stringify(input).replace('"fastPeriod":[1,2]', '"__proto__":[1]'), 'key'],
|
||||
['', JSON.stringify({ ...input, previewHash }), undefined],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash }), undefined],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash, selectionHash: 'a'.repeat(64) }), 'key'],
|
||||
[`/${id}/cancel`, '{"restart":true}', undefined],
|
||||
['/bad/finalize', JSON.stringify({ previewHash }), 'key'],
|
||||
];
|
||||
for (const [path, body, key] of cases) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('valid routes return missing404 and unexpected storage/schema failure is sanitized500', async () => {
|
||||
for (const role of ['operator', 'service'] as const) {
|
||||
const f = fixture();
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, role, 'key')).status).toBe(404);
|
||||
}
|
||||
}
|
||||
for (const error of [new Error('private storage failure'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await f.request(
|
||||
`/${id}/finalize`,
|
||||
'POST',
|
||||
JSON.stringify({ previewHash }),
|
||||
'operator',
|
||||
'key'
|
||||
);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
1161
test/integration/walk-forward-ui.test.tsx
Normal file
1161
test/integration/walk-forward-ui.test.tsx
Normal file
File diff suppressed because it is too large
Load diff
175
test/integration/walk-forward.test.ts
Normal file
175
test/integration/walk-forward.test.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { WalkForwardInput } from '@stock-bot/stock-config/walk-forward';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import {
|
||||
parseWalkForwardInput,
|
||||
prepareWalkForward,
|
||||
retainedWalkForwardPreview,
|
||||
} from '../../apps/stock/web-api/src/services/walk-forward-input';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
const backtestId = '10000000-0000-4000-8000-000000000001';
|
||||
const versionId = '20000000-0000-4000-8000-000000000001';
|
||||
const owner = `strategy:${versionId}`;
|
||||
const input = (): WalkForwardInput => ({
|
||||
backtestId,
|
||||
name: 'Rolling research',
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
||||
windows: walkForwardDataset().windows,
|
||||
});
|
||||
function source(dataset: HistoricalDatasetV2, raw = input()) {
|
||||
const { windows: _windows, ...experiment } = raw;
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
|
||||
const clock = canonicalRiskSessionClock(dataset);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
policy.matching.risk.ledger.riskSession = clock.riskSession;
|
||||
policy.risk_boundaries = clock.riskBoundaries;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: '30000000-0000-4000-8000-000000000001',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '40000000-0000-4000-8000-000000000001',
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
selection: {
|
||||
strategyId: descriptor.program.strategyId,
|
||||
strategyVersion: descriptor.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 42,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '40',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
});
|
||||
return buildExperimentPreview(experiment, request, dataset.manifest);
|
||||
}
|
||||
|
||||
describe('walk-forward deterministic preparation', () => {
|
||||
test('prepares ordered immutable windows from one exact common source and counts future holdouts', () => {
|
||||
const data = walkForwardDataset().dataset,
|
||||
raw = input(),
|
||||
original = source(data, raw),
|
||||
before = structuredClone({ data, raw, original });
|
||||
const prepared = prepareWalkForward(raw, original, data);
|
||||
expect(prepareWalkForward(raw, original, data)).toEqual(prepared);
|
||||
expect({ data, raw, original }).toEqual(before);
|
||||
expect(retainedWalkForwardPreview(prepared.preview)).toEqual(prepared.preview);
|
||||
expect(prepared.preview.counts).toEqual({
|
||||
windows: 2,
|
||||
trainingRuns: 4,
|
||||
holdoutRuns: 4,
|
||||
totalRuns: 8,
|
||||
maxRuns: 100,
|
||||
});
|
||||
for (const [index, member] of prepared.prepared.entries()) {
|
||||
expect(member.preview.input.name).toBe(`${raw.name} · window ${index + 1}`);
|
||||
expect(member.preview.source.request).toEqual(original.request);
|
||||
expect(member.preview.source.candidates).toEqual(original.candidates);
|
||||
expect(member.preview.input.recipe).toEqual(raw.windows[index]!);
|
||||
}
|
||||
});
|
||||
test('rejects reordered/duplicated/decreasing/overlapping windows and promised-run overflow', () => {
|
||||
const data = walkForwardDataset().dataset;
|
||||
for (const mutate of [
|
||||
(i: WalkForwardInput) => i.windows.reverse(),
|
||||
(i: WalkForwardInput) => (i.windows[1] = structuredClone(i.windows[0]!)),
|
||||
(i: WalkForwardInput) =>
|
||||
(i.windows[1]!.train.tradeStart = i.windows[0]!.train.tradeStart - 1),
|
||||
(i: WalkForwardInput) =>
|
||||
(i.windows[1]!.validation.tradeStart = i.windows[0]!.test.tradeEnd - 1),
|
||||
]) {
|
||||
const raw = input();
|
||||
mutate(raw);
|
||||
expect(() => prepareWalkForward(raw, source(data, raw), data)).toThrow(ExperimentError);
|
||||
}
|
||||
const raw = input();
|
||||
raw.grid = { fastPeriod: Array.from({ length: 49 }, (_, i) => i + 1), slowPeriod: [60] };
|
||||
expect(() => prepareWalkForward(raw, source(data, raw), data)).toThrow(
|
||||
'including all future holdouts'
|
||||
);
|
||||
expect(() => parseWalkForwardInput({ ...input(), windows: [input().windows[0]] })).toThrow();
|
||||
expect(() =>
|
||||
parseWalkForwardInput({
|
||||
...input(),
|
||||
windows: Array.from({ length: 11 }, () => input().windows[0]),
|
||||
})
|
||||
).toThrow();
|
||||
});
|
||||
test('later test suffix changes no preceding training dataset or strategy policy', () => {
|
||||
const raw = input(),
|
||||
a = walkForwardDataset().dataset,
|
||||
b = walkForwardDataset(90).dataset;
|
||||
const first = prepareWalkForward(raw, source(a, raw), a),
|
||||
second = prepareWalkForward(raw, source(b, raw), b);
|
||||
for (const index of [0, 1]) {
|
||||
expect(second.prepared[index]!.datasets.train).toEqual(first.prepared[index]!.datasets.train);
|
||||
}
|
||||
expect(second.prepared[0]!.datasets.test).toEqual(first.prepared[0]!.datasets.test);
|
||||
expect(second.prepared[1]!.datasets.test.manifest.hash).not.toBe(
|
||||
first.prepared[1]!.datasets.test.manifest.hash
|
||||
);
|
||||
});
|
||||
test('retained chronology corruption is a server integrity error, never input400', () => {
|
||||
const data = walkForwardDataset().dataset,
|
||||
raw = input(),
|
||||
preview = prepareWalkForward(raw, source(data, raw), data).preview;
|
||||
const corrupt = structuredClone(preview);
|
||||
corrupt.input.windows.reverse();
|
||||
const { previewHash: _hash, ...manifest } = corrupt;
|
||||
corrupt.previewHash = experimentHash(manifest);
|
||||
let failure: unknown;
|
||||
try {
|
||||
retainedWalkForwardPreview(corrupt);
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
expect(failure).toBeInstanceOf(Error);
|
||||
expect(failure).not.toBeInstanceOf(ExperimentError);
|
||||
});
|
||||
});
|
||||
|
|
@ -66,6 +66,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -104,6 +104,7 @@ async function fixture() {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ async function fixture(poolMax = 1, withValidation = true) {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
...(withValidation ? ['24-chronological-validation.sql'] : []),
|
||||
...(withValidation ? ['24-chronological-validation.sql', '25-walk-forward.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -506,6 +506,13 @@ describe.skipIf(!url)('durable validation adversarial boundaries', () => {
|
|||
await f.pool.query(migration);
|
||||
expect(await f.snapshot()).toEqual(first);
|
||||
expect((await f.experiments.list())[0]!.id).toBe(ordinary.id);
|
||||
// Current chronological admission can link roots to a walk-forward series.
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/25-walk-forward.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const current = await submit(f);
|
||||
expect(current.validation.stage).toBe('training');
|
||||
expect(
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ async function fixture() {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -77,6 +77,7 @@ async function fixture() {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -88,6 +88,7 @@ async function fixture() {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -69,7 +69,9 @@ async function fixture(poolMax = 4, withRetries = true) {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
...(withRetries ? ['23-experiment-retries.sql', '24-chronological-validation.sql'] : []),
|
||||
...(withRetries
|
||||
? ['23-experiment-retries.sql', '24-chronological-validation.sql', '25-walk-forward.sql']
|
||||
: []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -65,7 +65,12 @@ async function fixture(poolMax = 4, withExperiments = true) {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
...(withExperiments
|
||||
? ['22-experiments.sql', '23-experiment-retries.sql', '24-chronological-validation.sql']
|
||||
? [
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]
|
||||
: []),
|
||||
]) {
|
||||
await pool.query(
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ const migrations = [
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -31,7 +31,9 @@ const retention =
|
|||
'\n' +
|
||||
sql('23-experiment-retries.sql') +
|
||||
'\n' +
|
||||
sql('24-chronological-validation.sql');
|
||||
sql('24-chronological-validation.sql') +
|
||||
'\n' +
|
||||
sql('25-walk-forward.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ async function fixture() {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ async function fixture(poolMax = 4, withReproduction = true) {
|
|||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
]
|
||||
: []),
|
||||
]) {
|
||||
|
|
|
|||
771
test/postgres/walk-forward.test.ts
Normal file
771
test/postgres/walk-forward.test.ts
Normal file
|
|
@ -0,0 +1,771 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { WalkForwardInput } from '@stock-bot/stock-config/walk-forward';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
|
||||
import { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { WalkForwardService } from '../../apps/stock/web-api/src/services/walk-forward.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { walkForwardDataset } from '../fixtures/walk-forward';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('chronological-validation');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
const tokens = {
|
||||
operator: 'chronological-operator-fixture-not-a-real-secret-1234',
|
||||
service: 'chronological-service-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 1, withWalkForward = true) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
// A single connection detects accidental nested pool reads while the admission lock is held.
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
max: poolMax,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const name of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
...(withWalkForward ? ['25-walk-forward.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const container = { postgres, logger },
|
||||
api = new BacktestServiceV2(container),
|
||||
experiments = new ExperimentsService(container),
|
||||
catalog = new StrategyCatalogService(container);
|
||||
const version = await catalog.seedBuiltin(
|
||||
'Validation SMA',
|
||||
(await (packages ??= packageBuiltinStrategies()))[0]!,
|
||||
'seed'
|
||||
);
|
||||
const data = walkForwardDataset(),
|
||||
dataset = data.dataset;
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const draft = await api.createBacktest(
|
||||
{
|
||||
name: 'Validation template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: dataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const input: WalkForwardInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Two rolling windows',
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
||||
windows: data.windows,
|
||||
};
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
}).mount(app);
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') =>
|
||||
app.request('/api/v2/experiments/walk-forward/preview', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` },
|
||||
body: JSON.stringify(raw),
|
||||
});
|
||||
const review = async (decision: 'approve' | 'revoke' = 'approve') => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision, reason: 'Disposable validation proof' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const snapshot = async () => {
|
||||
const tables = (
|
||||
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [
|
||||
schema,
|
||||
])
|
||||
).rows;
|
||||
const rows: Record<string, unknown> = {};
|
||||
for (const { tablename } of tables) {
|
||||
const quoted = '"' + String(tablename).replaceAll('"', '""') + '"';
|
||||
rows[String(tablename)] = (
|
||||
await pool.query(
|
||||
`SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t`
|
||||
)
|
||||
).rows[0].rows;
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
const validations = new ChronologicalValidationService(container);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('No provider reads allowed');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
cloneTemplate: async (sourceDataset = dataset) =>
|
||||
api.createBacktest(
|
||||
{
|
||||
name: 'Other validation template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: ['X0.US'],
|
||||
startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
initialCapital: 10000,
|
||||
config: {
|
||||
datasetHash: sourceDataset.manifest.hash,
|
||||
dataFrequency: '1m',
|
||||
canonical: canonicalSettings,
|
||||
},
|
||||
},
|
||||
{ autoStart: false }
|
||||
),
|
||||
validations,
|
||||
walks: new WalkForwardService(container),
|
||||
repository,
|
||||
execute,
|
||||
api,
|
||||
pool,
|
||||
postgres,
|
||||
experiments,
|
||||
catalog,
|
||||
version,
|
||||
draft,
|
||||
dataset,
|
||||
input,
|
||||
request,
|
||||
review,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
||||
async function submit(f: Fixture, input = f.input, identity = actor()) {
|
||||
await f.review();
|
||||
const preview = await f.walks.preview(input),
|
||||
body = { ...input, previewHash: preview.previewHash };
|
||||
return { preview, body, identity, walk: await f.walks.submit(body, identity) };
|
||||
}
|
||||
async function finishWindow(f: Fixture, id: string) {
|
||||
const initial = await f.validations.get(id);
|
||||
for (const trial of initial.phases[0]!.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const selected = await f.validations.select(id, { previewHash: initial.previewHash }, actor());
|
||||
for (const phase of selected.validation.phases.slice(1)) {
|
||||
for (const trial of phase.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
}
|
||||
return f.validations.finalize(
|
||||
id,
|
||||
{
|
||||
previewHash: initial.previewHash,
|
||||
selectionHash: selected.validation.selection!.selectionHash,
|
||||
},
|
||||
actor()
|
||||
);
|
||||
}
|
||||
describe.skipIf(!url)('bounded walk-forward validation', () => {
|
||||
test('pool1 native windows admit atomically, retain independent reports and finalize historically', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f);
|
||||
expect(start.walk.windows).toHaveLength(2);
|
||||
expect(start.walk.trainingRunCount).toBe(4);
|
||||
expect(start.walk.plannedRunCount).toBe(8);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
||||
4
|
||||
);
|
||||
expect(await f.walks.submit(start.body, start.identity)).toEqual(start.walk);
|
||||
await expect(
|
||||
f.walks.finalize(start.walk.id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow();
|
||||
for (const member of start.walk.windows) {
|
||||
await finishWindow(f, member.validationId);
|
||||
}
|
||||
expect((await f.walks.get(start.walk.id)).actions.finalize.available).toBe(true);
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
const identity = actor(),
|
||||
body = { previewHash: start.preview.previewHash };
|
||||
const [final, duplicate] = await Promise.all([
|
||||
f.walks.finalize(start.walk.id, body, identity),
|
||||
f.walks.finalize(start.walk.id, body, identity),
|
||||
]);
|
||||
expect(duplicate.receipt).toEqual(final.receipt);
|
||||
await expect(f.walks.finalize(randomUUID(), body, identity)).rejects.toThrow('different');
|
||||
expect(final.walkForward.report!.segments.map(s => s.index)).toEqual([0, 1]);
|
||||
expect(final.walkForward.report!.segments.map(s => s.validationId)).toEqual(
|
||||
start.walk.windows.map(w => w.validationId)
|
||||
);
|
||||
expect(final.walkForward.report!.reset).toBe('initial-capital-empty-positions');
|
||||
expect(final.walkForward.reportedWindowCount).toBe(2);
|
||||
expect((await f.walks.list())[0]!.stage).toBe('reported');
|
||||
expect(await f.walks.finalize(start.walk.id, body, identity)).toEqual(final);
|
||||
expect((await f.walks.get(start.walk.id)).report).toEqual(final.walkForward.report);
|
||||
await f.walks.cancel(start.walk.id);
|
||||
expect((await f.walks.finalize(start.walk.id, body, identity)).receipt).toEqual(final.receipt);
|
||||
expect((await f.walks.submit(start.body, start.identity)).id).toBe(start.walk.id);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
async function trainWindow(f: Fixture, id: string) {
|
||||
const detail = await f.validations.get(id);
|
||||
for (const trial of detail.phases[0]!.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
return f.validations.select(id, { previewHash: detail.previewHash }, actor());
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('walk-forward adversarial boundaries', () => {
|
||||
test('first and idempotent SQL25 preserve ordinary evidence, receipts, active lease and SQL22–24 bodies', async () => {
|
||||
const f = await fixture(1, false);
|
||||
await f.review();
|
||||
const input = { backtestId: f.draft.id, name: 'Preserved sweep', grid: { fastPeriod: [1, 2] } };
|
||||
const preview = await f.experiments.preview(input),
|
||||
ordinary = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
await f.execute(ordinary.trials[0]!.runId!);
|
||||
const pending = ordinary.trials[1]!.runId!,
|
||||
request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.repository.startCanonical(request);
|
||||
const before = await f.snapshot(),
|
||||
functions = async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname'
|
||||
)
|
||||
).rows;
|
||||
const priorFunctions = await functions();
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/25-walk-forward.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(migration);
|
||||
const after = await f.snapshot();
|
||||
delete after.research_walk_forwards;
|
||||
after.research_experiments = (after.research_experiments as Record<string, unknown>[]).map(
|
||||
({ walk_forward_id: _id, walk_forward_index: _index, ...row }) => row
|
||||
);
|
||||
expect(after).toEqual(before);
|
||||
expect(
|
||||
(await functions()).filter(row => priorFunctions.some(p => p.proname === row.proname))
|
||||
).toEqual(priorFunctions);
|
||||
const upgraded = await f.snapshot();
|
||||
await f.pool.query(migration);
|
||||
expect(await f.snapshot()).toEqual(upgraded);
|
||||
expect(
|
||||
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0]
|
||||
).toMatchObject({ status: 'running', attempt_number: 1 });
|
||||
expect((await submit(f)).walk.windows).toHaveLength(2);
|
||||
}, 60000);
|
||||
test('failure on second root, retained slice, run, outbox or header rolls back every row and receipt', async () => {
|
||||
const f = await fixture();
|
||||
await f.review();
|
||||
const preview = await f.walks.preview(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash };
|
||||
const secondHash = preview.windows[1]!.preview.partitions[0].dataset.hash;
|
||||
for (const [table, condition] of [
|
||||
['research_experiments', 'NEW.walk_forward_index=1'],
|
||||
['backtest_datasets', `NEW.hash='${secondHash}'`],
|
||||
[
|
||||
'runs',
|
||||
'EXISTS(SELECT 1 FROM research_experiments e WHERE e.id=NEW.experiment_id AND e.walk_forward_index=1)',
|
||||
],
|
||||
[
|
||||
'backtest_dispatch',
|
||||
'EXISTS(SELECT 1 FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE r.id=NEW.run_id AND e.walk_forward_index=1)',
|
||||
],
|
||||
['research_walk_forwards', 'TRUE'],
|
||||
]) {
|
||||
await f.pool.query(
|
||||
`CREATE OR REPLACE FUNCTION injected_walk_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected walk failure'; END IF; RETURN NEW; END $$`
|
||||
);
|
||||
await f.pool.query(
|
||||
`CREATE TRIGGER injected_walk_failure BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION injected_walk_failure()`
|
||||
);
|
||||
const before = await f.snapshot();
|
||||
await expect(f.walks.submit(body, actor())).rejects.toThrow('Injected');
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await f.pool.query(`DROP TRIGGER injected_walk_failure ON ${table}`);
|
||||
}
|
||||
expect((await f.walks.submit(body, actor())).windows).toHaveLength(2);
|
||||
}, 60000);
|
||||
test('same and cross-parent submission receipts have one owner and replay before changed eligibility', async () => {
|
||||
const f = await fixture(5);
|
||||
await f.review();
|
||||
const preview = await f.walks.preview(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash },
|
||||
identity = actor();
|
||||
const [first, replay] = await Promise.all([
|
||||
f.walks.submit(body, identity),
|
||||
f.walks.submit(body, identity),
|
||||
]);
|
||||
expect(first.id).toBe(replay.id);
|
||||
const other = await f.cloneTemplate(),
|
||||
otherInput = { ...f.input, backtestId: other.id },
|
||||
otherPreview = await f.walks.preview(otherInput),
|
||||
otherBody = { ...otherInput, previewHash: otherPreview.previewHash },
|
||||
raceActor = actor();
|
||||
const race = await Promise.allSettled([
|
||||
f.walks.submit(body, raceActor),
|
||||
f.walks.submit(otherBody, raceActor),
|
||||
]);
|
||||
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int n FROM research_walk_forwards')).rows[0].n
|
||||
).toBe(2);
|
||||
expect((await f.pool.query('SELECT count(*)::int n FROM runs')).rows[0].n).toBe(8);
|
||||
await f.review('revoke');
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
expect((await f.walks.submit(body, identity)).id).toBe(first.id);
|
||||
await expect(f.walks.submit({ ...body, name: 'Changed' }, identity)).rejects.toThrow(
|
||||
'different'
|
||||
);
|
||||
await expect(f.walks.submit(body, actor())).rejects.toThrow();
|
||||
}, 60000);
|
||||
test('SQL rejects mixed membership, changed header/source/order, extra or missing roots and report replacement', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
header = (
|
||||
await f.pool.query('SELECT * FROM research_walk_forwards WHERE id=$1', [start.walk.id])
|
||||
).rows[0];
|
||||
const cloneHeader = async (patch: Record<string, unknown> = {}) => {
|
||||
const row = {
|
||||
...header,
|
||||
id: randomUUID(),
|
||||
member_ids: [randomUUID(), randomUUID()],
|
||||
submission_key: randomUUID(),
|
||||
...patch,
|
||||
};
|
||||
return f.pool.query(
|
||||
'INSERT INTO research_walk_forwards SELECT * FROM jsonb_populate_record(NULL::research_walk_forwards,$1)',
|
||||
[row]
|
||||
);
|
||||
};
|
||||
await expect(cloneHeader()).rejects.toThrow('must commit together');
|
||||
for (const patch of [
|
||||
{ member_ids: [header.member_ids[0], header.member_ids[0]] },
|
||||
{ preview: { ...header.preview, counts: { ...header.preview.counts, totalRuns: 4 } } },
|
||||
{
|
||||
preview: {
|
||||
...header.preview,
|
||||
source: {
|
||||
...header.preview.source,
|
||||
input: { ...header.preview.source.input, name: 'Other source' },
|
||||
},
|
||||
},
|
||||
},
|
||||
{ preview: { ...header.preview, windows: [...header.preview.windows].reverse() } },
|
||||
{ preview: { ...header.preview, policy: null } },
|
||||
]) {
|
||||
await expect(cloneHeader(patch)).rejects.toThrow();
|
||||
}
|
||||
for (const sql of [
|
||||
"UPDATE research_walk_forwards SET name='changed' WHERE id=$1",
|
||||
'UPDATE research_walk_forwards SET member_ids=ARRAY[]::uuid[] WHERE id=$1',
|
||||
"UPDATE research_walk_forwards SET report='{}' WHERE id=$1",
|
||||
'DELETE FROM research_walk_forwards WHERE id=$1',
|
||||
]) {
|
||||
await expect(f.pool.query(sql, [start.walk.id])).rejects.toThrow();
|
||||
}
|
||||
await expect(f.pool.query('TRUNCATE research_walk_forwards CASCADE')).rejects.toThrow();
|
||||
const member = (
|
||||
await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [header.member_ids[0]])
|
||||
).rows[0];
|
||||
for (const patch of [
|
||||
{ walk_forward_index: null },
|
||||
{ walk_forward_index: 2 },
|
||||
{ walk_forward_id: null },
|
||||
{ validation_phase: 'validation' },
|
||||
{
|
||||
validation_manifest: {
|
||||
...member.validation_manifest,
|
||||
input: { ...member.validation_manifest.input, name: 'Other' },
|
||||
},
|
||||
},
|
||||
]) {
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)',
|
||||
[{ ...member, id: randomUUID(), submission_key: randomUUID(), ...patch }]
|
||||
)
|
||||
).rejects.toThrow();
|
||||
}
|
||||
await expect(
|
||||
f.pool.query(
|
||||
'UPDATE research_experiments SET walk_forward_id=NULL,walk_forward_index=NULL WHERE id=$1',
|
||||
[member.id]
|
||||
)
|
||||
).rejects.toThrow('immutable');
|
||||
expect((await f.walks.get(start.walk.id)).windows).toHaveLength(2);
|
||||
}, 60000);
|
||||
test('member cancellation stays local; direct series cancellation races select and retry without orphan work', async () => {
|
||||
const f = await fixture(5),
|
||||
local = await submit(f);
|
||||
await f.validations.cancel(local.walk.windows[0]!.validationId);
|
||||
const localDetail = await f.walks.get(local.walk.id);
|
||||
expect(localDetail.cancelRequested).toBe(false);
|
||||
expect(localDetail.windows[0]!.validation!.cancelRequested).toBe(true);
|
||||
expect(localDetail.windows[1]!.validation!.cancelRequested).toBe(false);
|
||||
await expect(
|
||||
f.walks.finalize(local.walk.id, { previewHash: local.preview.previewHash }, actor())
|
||||
).rejects.toThrow();
|
||||
const start = await submit(f),
|
||||
first = start.walk.windows[0]!.validation!,
|
||||
second = start.walk.windows[1]!.validation!;
|
||||
for (const trial of first.phases[0]!.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const failed = second.phases[0]!.experiment!.trials[0]!.runId!;
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Preclaim failure',completed_at=NOW() WHERE id=$1",
|
||||
[failed]
|
||||
);
|
||||
const race = await Promise.allSettled([
|
||||
f.validations.select(first.id, { previewHash: first.previewHash }, actor()),
|
||||
f.experiments.retryTrial(
|
||||
second.id,
|
||||
failed,
|
||||
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
|
||||
actor()
|
||||
),
|
||||
f.pool.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [
|
||||
start.walk.id,
|
||||
]),
|
||||
]);
|
||||
expect(race[2]!.status).toBe('fulfilled');
|
||||
for (const outcome of race.slice(0, 2)) {
|
||||
if (outcome.status === 'rejected') {
|
||||
expect(outcome.reason).toBeInstanceOf(ExperimentError);
|
||||
expect(outcome.reason.status).toBe(409);
|
||||
}
|
||||
}
|
||||
const detail = await f.walks.get(start.walk.id);
|
||||
expect(detail.cancelRequested).toBe(true);
|
||||
expect(detail.windows.every(w => w.validation!.cancelRequested)).toBe(true);
|
||||
const rows = (
|
||||
await f.pool.query(
|
||||
'SELECT r.status,r.cancel_requested FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.walk_forward_id=$1 OR e.validation_parent_id=ANY($2::uuid[])',
|
||||
[start.walk.id, start.walk.windows.map(w => w.validationId)]
|
||||
)
|
||||
).rows;
|
||||
expect(rows.filter(r => r.status === 'cancelled').every(r => r.cancel_requested)).toBe(true);
|
||||
expect(rows.filter(r => r.status === 'completed')).toHaveLength(2);
|
||||
expect(rows.some(r => r.status === 'pending' || r.status === 'running')).toBe(false);
|
||||
expect((await f.walks.cancel(start.walk.id)).cancelRequested).toBe(true);
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_walk_forwards SET cancel_requested=FALSE WHERE id=$1', [
|
||||
start.walk.id,
|
||||
])
|
||||
).rejects.toThrow('permanent');
|
||||
}, 60000);
|
||||
test('only later test-price changes leave both native training scores and winners unchanged', async () => {
|
||||
const f = await fixture(),
|
||||
first = await submit(f),
|
||||
before = [];
|
||||
for (const member of first.walk.windows) {
|
||||
before.push((await trainWindow(f, member.validationId)).validation.selection!);
|
||||
}
|
||||
const dataset = walkForwardDataset(900).dataset;
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const other = await f.cloneTemplate(dataset);
|
||||
const raw = { ...f.input, backtestId: other.id },
|
||||
preview = await f.walks.preview(raw),
|
||||
second = await f.walks.submit({ ...raw, previewHash: preview.previewHash }, actor());
|
||||
for (const [index, member] of second.windows.entries()) {
|
||||
const selected = (await trainWindow(f, member.validationId)).validation.selection!;
|
||||
expect(selected.winner).toEqual(before[index]!.winner);
|
||||
expect(selected.training.map(t => t.metrics)).toEqual(
|
||||
before[index]!.training.map(t => t.metrics)
|
||||
);
|
||||
expect(preview.windows[index]!.preview.partitions[0].dataset.hash).toBe(
|
||||
first.preview.windows[index]!.preview.partitions[0].dataset.hash
|
||||
);
|
||||
}
|
||||
expect(preview.windows[1]!.preview.partitions[2].dataset.hash).not.toBe(
|
||||
first.preview.windows[1]!.preview.partitions[2].dataset.hash
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.validation_phase IN ('validation','test') AND r.status<>'pending'"
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(0);
|
||||
}, 60000);
|
||||
test('all members and full retained canonical results are required even after member reports were sealed', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f);
|
||||
for (const member of start.walk.windows) {
|
||||
await finishWindow(f, member.validationId);
|
||||
}
|
||||
const body = { previewHash: start.preview.previewHash },
|
||||
last = start.walk.windows[1]!.validationId;
|
||||
const root = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [last]))
|
||||
.rows[0];
|
||||
await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
'UPDATE research_experiments SET walk_forward_id=NULL,walk_forward_index=NULL WHERE id=$1',
|
||||
[last]
|
||||
);
|
||||
expect((await f.walks.get(start.walk.id)).windows[1]!.status).toBe('missing');
|
||||
await expect(f.walks.finalize(start.walk.id, body, actor())).rejects.toThrow('missing');
|
||||
await f.pool.query(
|
||||
'UPDATE research_experiments SET walk_forward_id=$2,walk_forward_index=$3 WHERE id=$1',
|
||||
[last, root.walk_forward_id, root.walk_forward_index]
|
||||
);
|
||||
await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
|
||||
const runId = root.validation_report.test.runId;
|
||||
const result = (
|
||||
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [runId])
|
||||
).rows[0].canonical_result;
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
for (const [path, value] of [
|
||||
['{analytics,metrics,totalReturn}', '900'],
|
||||
['{financial,view,equity}', '"900.00000000"'],
|
||||
]) {
|
||||
await f.pool.query(
|
||||
'UPDATE backtest_results SET canonical_result=jsonb_set($2::jsonb,$3::text[],$4::jsonb) WHERE run_id=$1',
|
||||
[runId, result, path, value]
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [
|
||||
runId,
|
||||
])
|
||||
).rows[0].canonical_result
|
||||
).not.toEqual(result);
|
||||
await expect(f.walks.finalize(start.walk.id, body, actor())).rejects.toThrow();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT report FROM research_walk_forwards WHERE id=$1', [
|
||||
start.walk.id,
|
||||
])
|
||||
).rows[0].report
|
||||
).toBeNull();
|
||||
}
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [
|
||||
runId,
|
||||
result,
|
||||
]);
|
||||
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
||||
const final = await f.walks.finalize(start.walk.id, body, actor());
|
||||
expect(final.walkForward.report!.segments).toHaveLength(2);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE research_walk_forwards SET report=jsonb_set(report,'{segments}','[]') WHERE id=$1",
|
||||
[start.walk.id]
|
||||
)
|
||||
).rejects.toThrow('immutable');
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
describe.skipIf(!url)('walk-forward concurrent controls', () => {
|
||||
test('direct cancellation passes downward while select and retry are demonstrably waiting on parent lock', async () => {
|
||||
const f = await fixture(6),
|
||||
start = await submit(f),
|
||||
first = start.walk.windows[0]!.validation!,
|
||||
second = start.walk.windows[1]!.validation!;
|
||||
for (const trial of first.phases[0]!.experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
const completed = async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT to_jsonb(r) AS row FROM runs r WHERE experiment_id=$1 ORDER BY trial_index',
|
||||
[first.id]
|
||||
)
|
||||
).rows;
|
||||
const preserved = await completed(),
|
||||
failed = second.phases[0]!.experiment!.trials[0]!.runId!;
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Preclaim',completed_at=NOW() WHERE id=$1",
|
||||
[failed]
|
||||
);
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]);
|
||||
const pending = Promise.allSettled([
|
||||
f.validations.select(first.id, { previewHash: first.previewHash }, actor()),
|
||||
f.experiments.retryTrial(
|
||||
second.id,
|
||||
failed,
|
||||
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
|
||||
actor()
|
||||
),
|
||||
]);
|
||||
try {
|
||||
let waiting = 0;
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
waiting = Number(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'"
|
||||
)
|
||||
).rows[0].n
|
||||
);
|
||||
if (waiting >= 2) {
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(waiting).toBeGreaterThanOrEqual(2);
|
||||
await f.pool.query('UPDATE research_walk_forwards SET cancel_requested=TRUE WHERE id=$1', [
|
||||
start.walk.id,
|
||||
]);
|
||||
await blocker.query('COMMIT');
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
}
|
||||
const outcomes = await pending;
|
||||
for (const outcome of outcomes) {
|
||||
expect(outcome.status).toBe('rejected');
|
||||
if (outcome.status === 'rejected') {
|
||||
expect(outcome.reason).toBeInstanceOf(ExperimentError);
|
||||
expect(outcome.reason.status).toBe(409);
|
||||
}
|
||||
}
|
||||
expect(await completed()).toEqual(preserved);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int n FROM runs r JOIN research_experiments e ON e.id=r.experiment_id WHERE e.walk_forward_id=$1 AND r.status IN ('pending','running','paused')",
|
||||
[start.walk.id]
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(0);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT count(*)::int n FROM experiment_trial_retries WHERE experiment_id=$1',
|
||||
[second.id]
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(0);
|
||||
}, 60000);
|
||||
test('same and cross-parent finalization receipts serialize exactly once without sealing the losing series', async () => {
|
||||
const f = await fixture(5),
|
||||
first = await submit(f),
|
||||
other = await f.cloneTemplate();
|
||||
const raw = { ...f.input, backtestId: other.id },
|
||||
preview = await f.walks.preview(raw),
|
||||
second = await f.walks.submit({ ...raw, previewHash: preview.previewHash }, actor());
|
||||
for (const member of [...first.walk.windows, ...second.windows]) {
|
||||
await finishWindow(f, member.validationId);
|
||||
}
|
||||
const identity = actor(),
|
||||
race = await Promise.allSettled([
|
||||
f.walks.finalize(first.walk.id, { previewHash: first.preview.previewHash }, identity),
|
||||
f.walks.finalize(second.id, { previewHash: preview.previewHash }, identity),
|
||||
]);
|
||||
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
const winnerIndex = race[0]!.status === 'fulfilled' ? 0 : 1,
|
||||
winner = winnerIndex === 0 ? first.walk : second,
|
||||
loser = winnerIndex === 0 ? second : first.walk;
|
||||
const rejected = race[1 - winnerIndex]!;
|
||||
if (rejected.status === 'rejected') {
|
||||
expect(rejected.reason).toBeInstanceOf(ExperimentError);
|
||||
expect(rejected.reason.status).toBe(409);
|
||||
}
|
||||
expect((await f.walks.get(loser.id)).report).toBeNull();
|
||||
const body = { previewHash: winner.previewHash },
|
||||
[one, two] = await Promise.all([
|
||||
f.walks.finalize(winner.id, body, identity),
|
||||
f.walks.finalize(winner.id, body, identity),
|
||||
]);
|
||||
expect(one.receipt).toEqual(two.receipt);
|
||||
await expect(f.walks.finalize(winner.id, body, actor())).rejects.toMatchObject({ status: 409 });
|
||||
const secondIdentity = actor(),
|
||||
[three, four] = await Promise.all([
|
||||
f.walks.finalize(loser.id, { previewHash: loser.previewHash }, secondIdentity),
|
||||
f.walks.finalize(loser.id, { previewHash: loser.previewHash }, secondIdentity),
|
||||
]);
|
||||
expect(three.receipt).toEqual(four.receipt);
|
||||
}, 60000);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue