feat(research): add durable walk-forward validation workflows

This commit is contained in:
Boki 2026-10-24 12:34:39 -04:00
parent abd1c5b83d
commit 3ed7b98f7c
45 changed files with 5188 additions and 199 deletions

View file

@ -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(

View 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' });
}
});
});

File diff suppressed because it is too large Load diff

View 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);
});
});