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