feat(research): run durable chronological validation and retain reports
This commit is contained in:
parent
67ab30cb7a
commit
abd1c5b83d
42 changed files with 5345 additions and 74 deletions
|
|
@ -295,6 +295,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -5,7 +5,11 @@ import {
|
|||
canonicalResearchSettingsSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ChronologicalValidationPreview } from '@stock-bot/stock-config/chronological-validation';
|
||||
import type {
|
||||
ChronologicalValidationActionResult,
|
||||
ChronologicalValidationDetail,
|
||||
ChronologicalValidationPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
|
|
@ -127,7 +131,7 @@ test('chronological_preflight_checks_explicit_windows_without_admitting_or_savin
|
|||
.getByText('Exact chronological preview inputs and policies', { exact: true })
|
||||
.click();
|
||||
expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash);
|
||||
await visible(f.page, /No datasets, experiments or runs are saved/);
|
||||
await visible(f.page, /Previewing does not save datasets, experiments or runs/);
|
||||
for (const partition of preview.partitions) {
|
||||
await visible(f.page, partition.dataset.hash);
|
||||
expect(partition.requiredWarmup).toBe(4);
|
||||
|
|
@ -166,6 +170,203 @@ test('chronological_preflight_checks_explicit_windows_without_admitting_or_savin
|
|||
}
|
||||
});
|
||||
|
||||
test('durable_chronological_training_fixed_holdouts_report_and_reopen_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
const { dataset, recipe } = chronologicalDataset();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const version = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
const approve = () =>
|
||||
f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed chronological durable browser fixture',
|
||||
});
|
||||
await approve();
|
||||
const definition = {
|
||||
name: 'Chronological durable 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 chronological research');
|
||||
await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
|
||||
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(`${phase} ${label} (UTC)`, { exact: true })
|
||||
.fill(new Date(value).toISOString());
|
||||
}
|
||||
}
|
||||
const previewing = f.page.waitForResponse(r =>
|
||||
r.url().endsWith('/api/v2/experiments/validation/preview')
|
||||
);
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Preview chronological validation', exact: true })
|
||||
.click();
|
||||
const { preview } = (await (await previewing).json()) as {
|
||||
preview: ChronologicalValidationPreview;
|
||||
};
|
||||
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/validation')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Submit training runs', exact: true }).click();
|
||||
const accepted = await submitting;
|
||||
expect(accepted.status()).toBe(202);
|
||||
const { validation: admitted } = (await accepted.json()) as {
|
||||
validation: ChronologicalValidationDetail;
|
||||
};
|
||||
const endpoint = `/api/v2/experiments/validation/${admitted.id}`;
|
||||
expect(accepted.headers().location).toBe(endpoint);
|
||||
expect(admitted.preview).toEqual(preview);
|
||||
expect(admitted.selection).toBeNull();
|
||||
expect(admitted.report).toBeNull();
|
||||
expect(admitted.phases.map(p => p.status)).toEqual([
|
||||
'admitted',
|
||||
'not-admitted',
|
||||
'not-admitted',
|
||||
]);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(1);
|
||||
await f.page.waitForURL(`${f.origin}/experiments/validation/${admitted.id}`);
|
||||
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
// Holdouts must retain the original recipe despite subsequent template edits and approval changes.
|
||||
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
|
||||
...definition,
|
||||
name: 'Changed template',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
});
|
||||
await approve();
|
||||
f.dispatcher.start();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
|
||||
'2',
|
||||
'training finishes through native durable runner'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
|
||||
const selecting = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/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;
|
||||
expect(selected.receipt.operation).toBe('select-and-admit-holdouts');
|
||||
expect(selected.receipt.id).toBe(selected.validation.selection!.id);
|
||||
expect(selected.validation.selection!.training).toHaveLength(2);
|
||||
expect(selected.validation.phases.map(p => p.status)).toEqual([
|
||||
'admitted',
|
||||
'admitted',
|
||||
'admitted',
|
||||
]);
|
||||
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(3);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(4);
|
||||
const winner = [...selected.validation.selection!.training].sort(
|
||||
(a, b) =>
|
||||
b.metrics.totalReturn! - a.metrics.totalReturn! ||
|
||||
a.sourceCandidateIndex - b.sourceCandidateIndex
|
||||
)[0]!;
|
||||
expect(selected.validation.selection!.winner.index).toBe(winner.sourceCandidateIndex);
|
||||
await until(
|
||||
async () =>
|
||||
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
|
||||
'4',
|
||||
'both same-winner heldouts finish through native runner'
|
||||
);
|
||||
// Finalization saves historical evidence and does not require permission to start new work.
|
||||
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 validation', exact: true }).click();
|
||||
const finalizing = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/finalize`));
|
||||
await f.page.getByRole('button', { name: 'Save validation report', exact: true }).click();
|
||||
const reportResponse = await finalizing;
|
||||
expect(reportResponse.status()).toBe(202);
|
||||
const completed = (await reportResponse.json()) as ChronologicalValidationActionResult;
|
||||
expect(completed.receipt.operation).toBe('finalize-report');
|
||||
expect(completed.receipt.id).toBe(completed.validation.report!.id);
|
||||
expect(completed.validation.stage).toBe('reported');
|
||||
const report = completed.validation.report!;
|
||||
expect(report.training).toEqual(selected.validation.selection!.training);
|
||||
expect(report.reset).toBe('initial-capital-empty-positions');
|
||||
expect(report.validation.parameters).toEqual(selected.validation.selection!.winner.parameters);
|
||||
expect(report.test.parameters).toEqual(report.validation.parameters);
|
||||
expect(report.validation.sourceCandidateIndex).toBe(winner.sourceCandidateIndex);
|
||||
expect(report.test.sourceCandidateIndex).toBe(winner.sourceCandidateIndex);
|
||||
for (const evidence of [...report.training, report.validation, report.test]) {
|
||||
const result = (await f.request(
|
||||
`/api/v2/runs/${evidence.runId}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(evidence.metrics).toEqual(result.analytics.metrics);
|
||||
expect(evidence.unavailable).toEqual(result.analytics.unavailable);
|
||||
expect(evidence.datasetHash).toBe(result.request.datasetHash);
|
||||
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'10000.00000000'
|
||||
);
|
||||
}
|
||||
await visible(f.page, 'Execution complete · report saved');
|
||||
const read = (await f.request(endpoint)) as { validation: ChronologicalValidationDetail };
|
||||
expect(read.validation.report).toEqual(report);
|
||||
const originalRuns = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
// Retrying the accepted selection after archival returns its same receipt, never finalizes again.
|
||||
const replay = (await f.request(
|
||||
`${endpoint}/select`,
|
||||
'POST',
|
||||
selectionResponse.request().postDataJSON(),
|
||||
{ 'Idempotency-Key': selectionResponse.request().headers()['idempotency-key']! }
|
||||
)) as ChronologicalValidationActionResult;
|
||||
expect(replay.receipt).toEqual(selected.receipt);
|
||||
expect(replay.validation.report).toEqual(report);
|
||||
expect((await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows).toEqual(
|
||||
originalRuns
|
||||
);
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Execution complete · report saved');
|
||||
expect((await f.request(endpoint)).validation.report).toEqual(report);
|
||||
await f.page.getByRole('link', { name: 'Open test experiment', exact: true }).click();
|
||||
await f.page.waitForURL(
|
||||
`${f.origin}/experiments/${selected.validation.selection!.holdoutExperimentIds.test}`
|
||||
);
|
||||
await visible(f.page, /completed: 1/);
|
||||
await f.page.goto(`${f.origin}/experiments`);
|
||||
await visible(f.page, 'Saved chronological validations');
|
||||
await f.page.locator(`a[href="/experiments/validation/${admitted.id}"]`).click();
|
||||
await visible(f.page, 'Execution complete · report saved');
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('failed_experiment_trial_retry_preserves_history_and_reopens_native_result_browser', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue