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());
|
||||
|
|
|
|||
133
test/integration/chronological-validation-durable-api.test.ts
Normal file
133
test/integration/chronological-validation-durable-api.test.ts
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
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 { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
|
||||
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] },
|
||||
recipe: chronologicalDataset().recipe,
|
||||
};
|
||||
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/validation' + 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),
|
||||
selectionHash = 'b'.repeat(64);
|
||||
const actions = [
|
||||
['', JSON.stringify({ ...input, previewHash })],
|
||||
[`/${id}/select`, JSON.stringify({ previewHash })],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash, selectionHash })],
|
||||
[`/${id}/cancel`, '{}'],
|
||||
];
|
||||
describe('durable validation HTTP gates', () => {
|
||||
test('all writes require real operator/service proof including disabled development auth; readers only inspect', 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 bodies, unknown winners/actions, raw reserved grids and missing receipts reject before any transaction', async () => {
|
||||
for (const [path, body, key] of [
|
||||
['', '{', 'key'],
|
||||
['', JSON.stringify({ ...input, previewHash, winner: 1 }), 'key'],
|
||||
[
|
||||
'',
|
||||
JSON.stringify({ ...input, previewHash }).replace('"fastPeriod":[1,2]', '"__proto__":[1]'),
|
||||
'key',
|
||||
],
|
||||
[`/${id}/select`, JSON.stringify({ previewHash, winner: 0 }), 'key'],
|
||||
[`/${id}/select`, JSON.stringify({ previewHash }), undefined],
|
||||
[`/${id}/finalize`, JSON.stringify({ previewHash }), 'key'],
|
||||
[
|
||||
`/${id}/finalize`,
|
||||
JSON.stringify({ previewHash, selectionHash, operation: 'select' }),
|
||||
'key',
|
||||
],
|
||||
[`/${id}/cancel`, '{"restart":true}', undefined],
|
||||
['/bad/select', JSON.stringify({ previewHash }), 'key'],
|
||||
]) {
|
||||
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('correct operation routes return missing404 and sanitize unexpected database/schema errors500', 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}/select`,
|
||||
'POST',
|
||||
JSON.stringify({ previewHash }),
|
||||
'operator',
|
||||
'key'
|
||||
);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
1029
test/integration/chronological-validation-durable-ui.test.tsx
Normal file
1029
test/integration/chronological-validation-durable-ui.test.tsx
Normal file
File diff suppressed because it is too large
Load diff
101
test/integration/chronological-validation-durable.test.ts
Normal file
101
test/integration/chronological-validation-durable.test.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
|
||||
import {
|
||||
parseValidationFinalization,
|
||||
parseValidationSelection,
|
||||
selectValidationWinner,
|
||||
} from '../../apps/stock/web-api/src/services/validation-evidence';
|
||||
|
||||
function fixture(scores: (number | null)[]) {
|
||||
const candidates: ExperimentCandidate[] = scores.map((_, index) => ({
|
||||
index,
|
||||
trialKey: String(index).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 1, slowPeriod: 5 },
|
||||
}));
|
||||
const evidence: ValidationResultEvidence[] = scores.map((totalReturn, index) => ({
|
||||
phase: 'train',
|
||||
experimentId: 'training',
|
||||
runId: String(index),
|
||||
sourceCandidateIndex: index,
|
||||
trialKey: candidates[index]!.trialKey,
|
||||
parameters: candidates[index]!.parameters,
|
||||
datasetHash: 'a'.repeat(64),
|
||||
requestHash: 'b'.repeat(64),
|
||||
economicHash: 'c'.repeat(64),
|
||||
metrics: {
|
||||
totalReturn,
|
||||
cagr: null,
|
||||
maxDrawdown: null,
|
||||
exposureTime: null,
|
||||
volatility: null,
|
||||
downsideDeviation: null,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
var95: null,
|
||||
cvar95: null,
|
||||
var99: null,
|
||||
alpha: null,
|
||||
beta: null,
|
||||
informationRatio: null,
|
||||
roundTripCount: null,
|
||||
winRate: null,
|
||||
profitFactor: null,
|
||||
avgWin: null,
|
||||
avgLoss: null,
|
||||
},
|
||||
unavailable: {},
|
||||
completePeriodCount: 0,
|
||||
periodicSampleCount: 0,
|
||||
fillCount: 0,
|
||||
limitations: [],
|
||||
}));
|
||||
return { candidates, evidence };
|
||||
}
|
||||
describe('sealed chronological selection contract', () => {
|
||||
test('maximizes finite zero/negative training scores, ties choose original index without reordering evidence', () => {
|
||||
for (const [scores, expected] of [
|
||||
[[-0.2, -0.1, -0.1], 1],
|
||||
[[0, -0.1, 0], 0],
|
||||
[[0.2, 0.4, 0.3], 1],
|
||||
] as const) {
|
||||
const { candidates, evidence } = fixture([...scores]),
|
||||
before = structuredClone(evidence);
|
||||
expect(selectValidationWinner(candidates, evidence)).toEqual(candidates[expected]!);
|
||||
expect(evidence).toEqual(before);
|
||||
}
|
||||
});
|
||||
test('missing/null/nonfinite/reordered or holdout evidence can never silently disappear from ranking', () => {
|
||||
for (const scores of [[1, null], [1, Infinity], [1, NaN], []]) {
|
||||
const f = fixture(scores);
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow();
|
||||
}
|
||||
const f = fixture([0, 1]);
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence.slice(1))).toThrow();
|
||||
expect(() => selectValidationWinner(f.candidates, [...f.evidence].reverse())).toThrow();
|
||||
f.evidence[0]!.phase = 'test';
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow();
|
||||
f.evidence[0]!.phase = 'train';
|
||||
f.evidence[0]!.parameters = { fastPeriod: 99 };
|
||||
expect(() => selectValidationWinner(f.candidates, f.evidence)).toThrow();
|
||||
});
|
||||
test('selection/finalization bodies cannot supply winners, scores, changed recipes or a different action', () => {
|
||||
const previewHash = 'a'.repeat(64),
|
||||
selectionHash = 'b'.repeat(64);
|
||||
expect(parseValidationSelection({ previewHash })).toEqual({ previewHash });
|
||||
expect(parseValidationFinalization({ previewHash, selectionHash })).toEqual({
|
||||
previewHash,
|
||||
selectionHash,
|
||||
});
|
||||
for (const extra of [
|
||||
{ winner: 1 },
|
||||
{ metrics: { totalReturn: 2 } },
|
||||
{ recipe: {} },
|
||||
{ operation: 'finalize-report' },
|
||||
]) {
|
||||
expect(() => parseValidationSelection({ previewHash, ...extra })).toThrow();
|
||||
expect(() => parseValidationFinalization({ previewHash, selectionHash, ...extra })).toThrow();
|
||||
}
|
||||
expect(() => parseValidationFinalization({ previewHash })).toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -362,9 +362,7 @@ describe('chronological validation preflight', () => {
|
|||
test('explicit UTC preparation sends only read-only preview and displays all phase assumptions and counts', async () => {
|
||||
const value = await fill();
|
||||
expect(host.textContent).toContain('No chronological preview prepared');
|
||||
expect(host.textContent).toContain(
|
||||
'Preview only. No datasets, experiments or runs are saved. Staged execution and immutable reports are not available yet.'
|
||||
);
|
||||
expect(host.textContent).toContain('Previewing does not save datasets, experiments or runs.');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Preview chronological validation').click();
|
||||
|
|
@ -393,7 +391,7 @@ describe('chronological validation preflight', () => {
|
|||
host
|
||||
.querySelector('[aria-label="Chronological validation preflight"]')!
|
||||
.querySelectorAll('button')
|
||||
).toHaveLength(1);
|
||||
).toHaveLength(2);
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'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')
|
||||
|
|
|
|||
|
|
@ -103,6 +103,7 @@ async function fixture() {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
917
test/postgres/chronological-validation-durable.test.ts
Normal file
917
test/postgres/chronological-validation-durable.test.ts
Normal file
|
|
@ -0,0 +1,917 @@
|
|||
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 { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ChronologicalValidationInput,
|
||||
ChronologicalValidationPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
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 { experimentHash } 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 {
|
||||
selectValidationWinner,
|
||||
validationEqual,
|
||||
validationEvidence,
|
||||
validationPhasePreview,
|
||||
} from '../../apps/stock/web-api/src/services/validation-evidence';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
|
||||
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, withValidation = 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',
|
||||
...(withValidation ? ['24-chronological-validation.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 = chronologicalDataset(),
|
||||
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: ChronologicalValidationInput = {
|
||||
backtestId: draft.id,
|
||||
name: 'Three explicit windows',
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
||||
recipe: data.recipe,
|
||||
};
|
||||
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/validation/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,
|
||||
repository,
|
||||
execute,
|
||||
api,
|
||||
pool,
|
||||
postgres,
|
||||
experiments,
|
||||
catalog,
|
||||
version,
|
||||
draft,
|
||||
dataset,
|
||||
input,
|
||||
request,
|
||||
review,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
async function submit(f: Awaited<ReturnType<typeof fixture>>, key = randomUUID()) {
|
||||
await f.review();
|
||||
const preview = await f.experiments.previewValidation(f.input);
|
||||
const body = { ...f.input, previewHash: preview.previewHash },
|
||||
identity = actor(key);
|
||||
return { preview, body, identity, validation: await f.validations.submit(body, identity) };
|
||||
}
|
||||
async function train(f: Awaited<ReturnType<typeof fixture>>, id: string) {
|
||||
const detail = await f.validations.get(id);
|
||||
for (const trial of detail.phases[0].experiment!.trials) {
|
||||
await f.execute(trial.runId!);
|
||||
}
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('durable chronological validation', () => {
|
||||
test('native training→write-once winner→same-winner holdouts→historical report and immutable receipt reopen', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
id = start.validation.id;
|
||||
expect(start.validation.name).toBe(f.input.name);
|
||||
expect(start.validation.phases.map(p => p.status)).toEqual([
|
||||
'admitted',
|
||||
'not-admitted',
|
||||
'not-admitted',
|
||||
]);
|
||||
expect(start.validation.phases[0].experiment!.name).toBe(f.input.name + ' · train');
|
||||
expect(await f.experiments.list()).toEqual([]);
|
||||
expect((await f.validations.list())[0]!.id).toBe(id);
|
||||
expect(await f.validations.submit(start.body, start.identity)).toEqual(start.validation);
|
||||
await expect(
|
||||
f.validations.select(id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow('Every train');
|
||||
await train(f, id);
|
||||
const before = await f.validations.get(id);
|
||||
expect(before.actions.select.available).toBe(true);
|
||||
const newest = await f.review();
|
||||
await f.pool.query(
|
||||
'UPDATE backtests SET name=\'Changed template\',strategy_parameters=\'{"fastPeriod":1,"slowPeriod":4}\' WHERE id=$1',
|
||||
[f.draft.id]
|
||||
);
|
||||
const selectActor = actor(),
|
||||
selectBody = { previewHash: start.preview.previewHash };
|
||||
const selected = await f.validations.select(id, selectBody, selectActor);
|
||||
expect(selected.receipt.operation).toBe('select-and-admit-holdouts');
|
||||
const selection = selected.validation.selection!;
|
||||
expect(selection.training.map(e => e.sourceCandidateIndex)).toEqual([0, 1]);
|
||||
expect(selection.reviewId).toBe(newest.id);
|
||||
expect(selection.training.every(e => e.metrics.totalReturn !== null)).toBe(true);
|
||||
const ranked = [...selection.training].sort(
|
||||
(a, b) =>
|
||||
b.metrics.totalReturn! - a.metrics.totalReturn! ||
|
||||
a.sourceCandidateIndex - b.sourceCandidateIndex
|
||||
);
|
||||
expect(selection.winner.index).toBe(ranked[0]!.sourceCandidateIndex);
|
||||
for (const phase of selected.validation.phases.slice(1)) {
|
||||
expect(phase.experiment!.trials).toHaveLength(1);
|
||||
expect(phase.experiment!.name).toBe(f.input.name + ' · ' + phase.phase);
|
||||
expect(phase.experiment!.preview.request.strategy.reviewId).toBe(newest.id);
|
||||
expect(
|
||||
validationEqual(
|
||||
phase.experiment!.preview.request.strategy.selection.parameters,
|
||||
selection.winner.parameters
|
||||
)
|
||||
).toBe(true);
|
||||
expect(phase.experiment!.preview.request.name).toBe(start.preview.source.request.name);
|
||||
await f.execute(phase.experiment!.trials[0]!.runId!);
|
||||
}
|
||||
expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual(
|
||||
selected.receipt
|
||||
);
|
||||
await expect(f.validations.select(id, selectBody, actor())).rejects.toThrow('another receipt');
|
||||
await f.review('revoke');
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
const finalActor = actor(),
|
||||
finalBody = {
|
||||
previewHash: start.preview.previewHash,
|
||||
selectionHash: selection.selectionHash,
|
||||
};
|
||||
const finalized = await f.validations.finalize(id, finalBody, finalActor),
|
||||
report = finalized.validation.report!;
|
||||
expect(report.training).toEqual(selection.training);
|
||||
expect(report.validation.sourceCandidateIndex).toBe(selection.winner.index);
|
||||
expect(report.test.sourceCandidateIndex).toBe(selection.winner.index);
|
||||
expect(report.validation.parameters).toEqual(report.test.parameters);
|
||||
expect(report.reset).toBe('initial-capital-empty-positions');
|
||||
expect(finalized.validation.stage).toBe('reported');
|
||||
expect((await f.validations.get(id)).report).toEqual(report);
|
||||
await f.validations.cancel(id);
|
||||
expect((await f.validations.finalize(id, finalBody, finalActor)).receipt).toEqual(
|
||||
finalized.receipt
|
||||
);
|
||||
expect((await f.validations.select(id, selectBody, selectActor)).receipt).toEqual(
|
||||
selected.receipt
|
||||
);
|
||||
expect((await f.validations.submit(start.body, start.identity)).id).toBe(id);
|
||||
await expect(f.validations.finalize(id, finalBody, actor())).rejects.toThrow('another receipt');
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(4);
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n
|
||||
).toBe(3);
|
||||
for (const field of [
|
||||
'validation_manifest',
|
||||
'validation_selection',
|
||||
'validation_report',
|
||||
'validation_phase',
|
||||
]) {
|
||||
await expect(
|
||||
f.pool.query(`UPDATE research_experiments SET ${field}=NULL WHERE id=$1`, [id])
|
||||
).rejects.toThrow();
|
||||
}
|
||||
}, 60_000);
|
||||
test('ordinary and direct SQL cancellation latch the whole workflow, including pending heldout claims', async () => {
|
||||
const f = await fixture(),
|
||||
first = await submit(f);
|
||||
await f.experiments.cancel(first.validation.id);
|
||||
expect(
|
||||
(await f.validations.get(first.validation.id)).phases[0].experiment!.trials.every(
|
||||
t => t.status === 'cancelled'
|
||||
)
|
||||
).toBe(true);
|
||||
await expect(
|
||||
f.validations.select(first.validation.id, { previewHash: first.preview.previewHash }, actor())
|
||||
).rejects.toThrow('uncancelled');
|
||||
const second = await submit(f);
|
||||
await train(f, second.validation.id);
|
||||
const selected = await f.validations.select(
|
||||
second.validation.id,
|
||||
{ previewHash: second.preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
await f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [
|
||||
second.validation.id,
|
||||
]);
|
||||
const detail = await f.validations.get(second.validation.id);
|
||||
expect(detail.phases.every(p => p.experiment!.cancelRequested)).toBe(true);
|
||||
for (const child of selected.validation.phases.slice(1)) {
|
||||
const id = child.experiment!.trials[0]!.runId!;
|
||||
await f.execute(id);
|
||||
expect((await f.pool.query('SELECT status FROM runs WHERE id=$1', [id])).rows[0].status).toBe(
|
||||
'cancelled'
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
f.validations.finalize(
|
||||
detail.id,
|
||||
{ previewHash: detail.previewHash, selectionHash: detail.selection!.selectionHash },
|
||||
actor()
|
||||
)
|
||||
).rejects.toThrow('uncancelled');
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_experiments SET cancel_requested=FALSE WHERE id=$1', [
|
||||
detail.id,
|
||||
])
|
||||
).rejects.toThrow();
|
||||
}, 60_000);
|
||||
test('a corrupted heldout dataset or numerically forged training analytics cannot seal selection', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f);
|
||||
await train(f, start.validation.id);
|
||||
const heldout = start.preview.partitions[1].dataset.hash;
|
||||
await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,close}','999') WHERE hash=$1",
|
||||
[heldout]
|
||||
);
|
||||
await expect(
|
||||
f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow('content validation');
|
||||
expect((await f.validations.get(start.validation.id)).selection).toBeNull();
|
||||
const sourceDataset = (
|
||||
await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
start.preview.source.dataset.hash,
|
||||
])
|
||||
).rows[0].payload;
|
||||
const { prepareChronologicalValidation } = await import(
|
||||
'../../apps/stock/web-api/src/services/validation-preview'
|
||||
);
|
||||
const prepared = prepareChronologicalValidation(f.input, start.preview.source, sourceDataset);
|
||||
await f.pool.query('UPDATE backtest_datasets SET payload=$2 WHERE hash=$1', [
|
||||
heldout,
|
||||
prepared.datasets.validation,
|
||||
]);
|
||||
const runId = start.validation.phases[0].experiment!.trials[0]!.runId!;
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{analytics,metrics,totalReturn}','900') WHERE run_id=$1",
|
||||
[runId]
|
||||
);
|
||||
await expect(
|
||||
f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow('analytics validation');
|
||||
expect((await f.validations.get(start.validation.id)).selection).toBeNull();
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n
|
||||
).toBe(1);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
async function selectionDocument(f: Awaited<ReturnType<typeof fixture>>, validationId: string) {
|
||||
const detail = await f.validations.get(validationId),
|
||||
training = [];
|
||||
for (const trial of detail.phases[0].experiment!.trials) {
|
||||
const result = (await f.api.getRunResults(trial.runId!)) as CanonicalRunResult;
|
||||
training.push(validationEvidence('train', validationId, trial, trial.index, result));
|
||||
}
|
||||
const manifest = {
|
||||
version: 'chronological-validation-selection/v1' as const,
|
||||
id: randomUUID(),
|
||||
validationId,
|
||||
previewHash: detail.previewHash,
|
||||
createdAt: new Date().toISOString(),
|
||||
principal: 'operator' as const,
|
||||
reviewId: (await f.catalog.getVersionReviews(f.version.id)).at(-1)!.id,
|
||||
winner: selectValidationWinner(detail.preview.source.candidates, training),
|
||||
training,
|
||||
holdoutExperimentIds: { validation: randomUUID(), test: randomUUID() },
|
||||
};
|
||||
return {
|
||||
...manifest,
|
||||
selectionHash: experimentHash(manifest),
|
||||
_receipt: { key: randomUUID(), hash: 'a'.repeat(64) },
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('durable validation adversarial boundaries', () => {
|
||||
test('first/idempotent SQL24 upgrade preserves ordinary requests/results/receipts and active leases', async () => {
|
||||
const f = await fixture(1, false);
|
||||
await f.review();
|
||||
const ordinaryInput = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Existing ordinary sweep',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
};
|
||||
const preview = await f.experiments.preview(ordinaryInput);
|
||||
const ordinary = await f.experiments.submit(
|
||||
{ ...ordinaryInput, 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();
|
||||
const names = [
|
||||
'require_active_backtest_for_new_run',
|
||||
'require_experiment_retry_failure',
|
||||
'guard_manual_trial_retry',
|
||||
'require_consumed_trial_retry',
|
||||
];
|
||||
const functionBodies = async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace AND proname=ANY($1) ORDER BY proname',
|
||||
[names]
|
||||
)
|
||||
).rows;
|
||||
const priorFunctions = await functionBodies();
|
||||
const migration = readFileSync(
|
||||
new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(migration);
|
||||
const after = await f.snapshot();
|
||||
after.research_experiments = (after.research_experiments as Record<string, unknown>[]).map(
|
||||
({
|
||||
validation_manifest: _manifest,
|
||||
validation_parent_id: _parent,
|
||||
validation_phase: _phase,
|
||||
validation_selection: _selection,
|
||||
validation_report: _report,
|
||||
...row
|
||||
}) => row
|
||||
);
|
||||
expect(after).toEqual(before);
|
||||
expect(await functionBodies()).toEqual(priorFunctions);
|
||||
const first = await f.snapshot();
|
||||
await f.pool.query(migration);
|
||||
expect(await f.snapshot()).toEqual(first);
|
||||
expect((await f.experiments.list())[0]!.id).toBe(ordinary.id);
|
||||
const current = await submit(f);
|
||||
expect(current.validation.stage).toBe('training');
|
||||
expect(
|
||||
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [pending])).rows[0]
|
||||
).toMatchObject({ status: 'running', attempt_number: 1 });
|
||||
}, 60_000);
|
||||
test('SQL independently rejects mixed shapes, changed source/slice/policy, premature or incorrect winners and incomplete commits', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
id = start.validation.id;
|
||||
const sourceRow = (await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [id]))
|
||||
.rows[0];
|
||||
const insertRoot = async (
|
||||
manifest: ChronologicalValidationPreview,
|
||||
phase: string | null = 'train'
|
||||
) => {
|
||||
const trainPreview = validationPhasePreview(manifest, 'train');
|
||||
return f.pool.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash,validation_manifest,validation_phase)
|
||||
VALUES($1,$2,$3,$4,$5,'operator',$6,$7,$8,$9)`,
|
||||
[
|
||||
randomUUID(),
|
||||
f.draft.id,
|
||||
trainPreview.input.name,
|
||||
trainPreview,
|
||||
trainPreview.previewHash,
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
manifest,
|
||||
phase,
|
||||
]
|
||||
);
|
||||
};
|
||||
for (const mutate of [
|
||||
(p: ChronologicalValidationPreview) => {
|
||||
p.source.request.policy.matching.risk.feeRate =
|
||||
'0.02000000' as typeof p.source.request.policy.matching.risk.feeRate;
|
||||
},
|
||||
(p: ChronologicalValidationPreview) => {
|
||||
p.partitions[0].request.policy.matching.risk.maxGrossExposure =
|
||||
'999999.00000000' as (typeof p.partitions)[0]['request']['policy']['matching']['risk']['maxGrossExposure'];
|
||||
},
|
||||
(p: ChronologicalValidationPreview) => {
|
||||
p.partitions[0].counts.admittedWarmup++;
|
||||
},
|
||||
(p: ChronologicalValidationPreview) => {
|
||||
p.partitions[0].dataset = structuredClone(p.source.dataset);
|
||||
},
|
||||
(p: ChronologicalValidationPreview) => {
|
||||
p.input.recipe.train.tradeStart++;
|
||||
},
|
||||
(p: ChronologicalValidationPreview) => {
|
||||
p.source.candidates[0]!.parameters.fastPeriod = 99;
|
||||
},
|
||||
]) {
|
||||
const manifest = structuredClone(start.preview);
|
||||
mutate(manifest);
|
||||
await expect(insertRoot(manifest)).rejects.toThrow();
|
||||
}
|
||||
await expect(insertRoot(start.preview, null)).rejects.toThrow();
|
||||
// A correct root without its run/outbox set fails at COMMIT, not merely at service validation.
|
||||
await expect(insertRoot(start.preview)).rejects.toThrow('complete exact run');
|
||||
expect(
|
||||
(await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n
|
||||
).toBe(1);
|
||||
await train(f, id);
|
||||
const correct = await selectionDocument(f, id);
|
||||
for (const mutate of [
|
||||
(s: typeof correct) => {
|
||||
s.winner = structuredClone(start.preview.source.candidates[1 - correct.winner.index]!);
|
||||
},
|
||||
(s: typeof correct) => {
|
||||
s.training[0]!.metrics.totalReturn = 999;
|
||||
},
|
||||
(s: typeof correct) => {
|
||||
s.training.reverse();
|
||||
},
|
||||
(s: typeof correct) => {
|
||||
s.training.pop();
|
||||
},
|
||||
(s: typeof correct) => {
|
||||
s.training[0]!.datasetHash = start.preview.partitions[1].dataset.hash;
|
||||
},
|
||||
]) {
|
||||
const changed = structuredClone(correct);
|
||||
mutate(changed);
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [
|
||||
id,
|
||||
changed,
|
||||
])
|
||||
).rejects.toThrow();
|
||||
}
|
||||
await expect(
|
||||
f.pool.query('UPDATE research_experiments SET validation_selection=$2 WHERE id=$1', [
|
||||
id,
|
||||
correct,
|
||||
])
|
||||
).rejects.toThrow('atomically admit both');
|
||||
expect((await f.validations.get(id)).selection).toBeNull();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query('SELECT preview,submission_key FROM research_experiments WHERE id=$1', [
|
||||
id,
|
||||
])
|
||||
).rows[0]
|
||||
).toEqual({ preview: sourceRow.preview, submission_key: sourceRow.submission_key });
|
||||
}, 60_000);
|
||||
test('injected training/outbox/second-holdout insert failures roll back every new input, receipt and selection', async () => {
|
||||
const f = await fixture();
|
||||
await f.review();
|
||||
const preview = await f.experiments.previewValidation(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash };
|
||||
const fail = async (table: string, name: string, condition: string) => {
|
||||
await f.pool.query(
|
||||
`CREATE OR REPLACE FUNCTION ${name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN RAISE EXCEPTION 'Injected ${name}'; END IF; RETURN NEW; END $$`
|
||||
);
|
||||
await f.pool.query(
|
||||
`CREATE TRIGGER ${name} BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION ${name}()`
|
||||
);
|
||||
};
|
||||
for (const [table, condition] of [
|
||||
['runs', 'NEW.trial_index=1'],
|
||||
['backtest_dispatch', 'TRUE'],
|
||||
]) {
|
||||
await fail(table!, 'injected_root_failure', condition!);
|
||||
const before = await f.snapshot();
|
||||
await expect(f.validations.submit(body, actor())).rejects.toThrow('Injected');
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await f.pool.query(`DROP TRIGGER injected_root_failure ON ${table}`);
|
||||
}
|
||||
const root = await f.validations.submit(body, actor());
|
||||
await train(f, root.id);
|
||||
await fail('research_experiments', 'injected_holdout_failure', "NEW.validation_phase='test'");
|
||||
const before = await f.snapshot();
|
||||
await expect(
|
||||
f.validations.select(root.id, { previewHash: preview.previewHash }, actor())
|
||||
).rejects.toThrow('Injected');
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
await f.pool.query('DROP TRIGGER injected_holdout_failure ON research_experiments');
|
||||
expect(
|
||||
(await f.validations.select(root.id, { previewHash: preview.previewHash }, actor()))
|
||||
.validation.phases
|
||||
).toHaveLength(3);
|
||||
}, 60_000);
|
||||
test('same and cross-parent receipt races have exactly one atomic owner; conflicting intent never gains children', async () => {
|
||||
const f = await fixture(5);
|
||||
await f.review();
|
||||
const preview = await f.experiments.previewValidation(f.input),
|
||||
body = { ...f.input, previewHash: preview.previewHash },
|
||||
same = actor();
|
||||
const [first, replay] = await Promise.all([
|
||||
f.validations.submit(body, same),
|
||||
f.validations.submit(body, same),
|
||||
]);
|
||||
expect(first.id).toBe(replay.id);
|
||||
const other = await f.cloneTemplate(),
|
||||
otherInput = { ...f.input, backtestId: other.id };
|
||||
const otherPreview = await f.experiments.previewValidation(otherInput),
|
||||
otherBody = { ...otherInput, previewHash: otherPreview.previewHash };
|
||||
const key = actor(),
|
||||
results = await Promise.allSettled([
|
||||
f.validations.submit(body, key),
|
||||
f.validations.submit(otherBody, key),
|
||||
]);
|
||||
expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(results.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
const second = await f.validations.submit(otherBody, actor());
|
||||
await train(f, first.id);
|
||||
await train(f, second.id);
|
||||
const action = actor(),
|
||||
selections = await Promise.allSettled([
|
||||
f.validations.select(first.id, { previewHash: preview.previewHash }, action),
|
||||
f.validations.select(second.id, { previewHash: otherPreview.previewHash }, action),
|
||||
]);
|
||||
expect(selections.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(selections.filter(r => r.status === 'rejected')).toHaveLength(1);
|
||||
const selectedRoot = selections[0]!.status === 'fulfilled' ? first : second;
|
||||
const selectedBody = { previewHash: selectedRoot.previewHash };
|
||||
const a = await f.validations.select(selectedRoot.id, selectedBody, action);
|
||||
const [b, c] = await Promise.all([
|
||||
f.validations.select(selectedRoot.id, selectedBody, action),
|
||||
f.validations.select(selectedRoot.id, selectedBody, action),
|
||||
]);
|
||||
expect(b.receipt).toEqual(a.receipt);
|
||||
expect(c.receipt).toEqual(a.receipt);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS n FROM research_experiments WHERE validation_phase IN ('validation','test')"
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(2);
|
||||
}, 60_000);
|
||||
test('failed training and holdout trials reuse existing manual retry receipts and immutable requests', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
training = start.validation.phases[0].experiment!.trials[0]!,
|
||||
runId = training.runId!;
|
||||
const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0].request_snapshot;
|
||||
const claim = await f.repository.startCanonical(request);
|
||||
await f.repository.fail(runId, 'Training fixture failure', claim.attemptId);
|
||||
await expect(
|
||||
f.validations.select(start.validation.id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow('Every train');
|
||||
await f.experiments.retryTrial(
|
||||
start.validation.id,
|
||||
runId,
|
||||
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
|
||||
actor()
|
||||
);
|
||||
await train(f, start.validation.id);
|
||||
await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow();
|
||||
const selected = await f.validations.select(
|
||||
start.validation.id,
|
||||
{ previewHash: start.preview.previewHash },
|
||||
actor()
|
||||
),
|
||||
child = selected.validation.phases[1].experiment!,
|
||||
childRun = child.trials[0]!.runId!;
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Before claim',completed_at=NOW() WHERE id=$1",
|
||||
[childRun]
|
||||
);
|
||||
await f.experiments.retryTrial(
|
||||
child.id,
|
||||
childRun,
|
||||
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
|
||||
actor()
|
||||
);
|
||||
await f.execute(childRun);
|
||||
await f.execute(selected.validation.phases[2].experiment!.trials[0]!.runId!);
|
||||
const saved = await f.validations.finalize(
|
||||
start.validation.id,
|
||||
{
|
||||
previewHash: start.preview.previewHash,
|
||||
selectionHash: selected.validation.selection!.selectionHash,
|
||||
},
|
||||
actor()
|
||||
);
|
||||
expect(saved.validation.report).not.toBeNull();
|
||||
expect(
|
||||
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
|
||||
.request_snapshot
|
||||
).toEqual(request);
|
||||
expect(
|
||||
(await f.experiments.listTrialRetries(start.validation.id, runId))[0]!.previousAttemptNumber
|
||||
).toBe(1);
|
||||
expect(
|
||||
(await f.experiments.listTrialRetries(child.id, childRun))[0]!.previousAttemptNumber
|
||||
).toBe(0);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe.skipIf(!url)('durable validation isolation proofs', () => {
|
||||
test('selection racing direct SQL cancellation leaves no live orphan holdout work', async () => {
|
||||
const f = await fixture(4),
|
||||
start = await submit(f);
|
||||
await train(f, start.validation.id);
|
||||
const outcomes = await Promise.allSettled([
|
||||
f.validations.select(
|
||||
start.validation.id,
|
||||
{ previewHash: start.preview.previewHash },
|
||||
actor()
|
||||
),
|
||||
f.pool.query('UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1', [
|
||||
start.validation.id,
|
||||
]),
|
||||
]);
|
||||
expect(outcomes[1]!.status).toBe('fulfilled');
|
||||
const detail = await f.validations.get(start.validation.id);
|
||||
expect(detail.cancelRequested).toBe(true);
|
||||
const children = (
|
||||
await f.pool.query(
|
||||
'SELECT id,cancel_requested FROM research_experiments WHERE validation_parent_id=$1',
|
||||
[detail.id]
|
||||
)
|
||||
).rows;
|
||||
expect(children.length).toBe(detail.selection ? 2 : 0);
|
||||
expect(children.every(c => c.cancel_requested)).toBe(true);
|
||||
const childRuns = (
|
||||
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.validation_parent_id=$1',
|
||||
[detail.id]
|
||||
)
|
||||
).rows;
|
||||
expect(childRuns.every(r => r.status === 'cancelled' && r.cancel_requested)).toBe(true);
|
||||
expect(detail.report).toBeNull();
|
||||
}, 60_000);
|
||||
test('changing only future test prices cannot change native training scores or frozen winner', async () => {
|
||||
const f = await fixture(),
|
||||
first = await submit(f);
|
||||
await train(f, first.validation.id);
|
||||
const chosen = await f.validations.select(
|
||||
first.validation.id,
|
||||
{ previewHash: first.preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
const changed = chronologicalDataset(900).dataset;
|
||||
await retainResearchDataset(f.pool, changed);
|
||||
const template = await f.cloneTemplate(changed),
|
||||
secondInput = { ...f.input, backtestId: template.id };
|
||||
const preview = await f.experiments.previewValidation(secondInput);
|
||||
const second = await f.validations.submit(
|
||||
{ ...secondInput, previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
expect(preview.partitions[0].dataset.hash).toBe(first.preview.partitions[0].dataset.hash);
|
||||
expect(preview.partitions[2].dataset.hash).not.toBe(first.preview.partitions[2].dataset.hash);
|
||||
await train(f, second.id);
|
||||
const next = await f.validations.select(
|
||||
second.id,
|
||||
{ previewHash: preview.previewHash },
|
||||
actor()
|
||||
);
|
||||
expect(next.validation.selection!.winner).toEqual(chosen.validation.selection!.winner);
|
||||
expect(next.validation.selection!.training.map(e => e.metrics)).toEqual(
|
||||
chosen.validation.selection!.training.map(e => e.metrics)
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS 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);
|
||||
}, 60_000);
|
||||
test('missing, failed, incomparable and unavailable training candidates each block durable selection', async () => {
|
||||
const f = await fixture(),
|
||||
start = await submit(f),
|
||||
id = start.validation.id,
|
||||
trial = start.validation.phases[0].experiment!.trials[0]!;
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
'UPDATE runs SET experiment_id=NULL,trial_index=NULL,trial_key=NULL WHERE id=$1',
|
||||
[trial.runId]
|
||||
);
|
||||
expect((await f.validations.get(id)).phases[0].experiment!.trials[0]!.status).toBe('missing');
|
||||
await expect(
|
||||
f.validations.select(id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow('Every train');
|
||||
await f.pool.query('UPDATE runs SET experiment_id=$2,trial_index=$3,trial_key=$4 WHERE id=$1', [
|
||||
trial.runId,
|
||||
id,
|
||||
trial.index,
|
||||
trial.trialKey,
|
||||
]);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error='Incomplete candidate',completed_at=NOW() WHERE id=$1",
|
||||
[trial.runId]
|
||||
);
|
||||
await expect(
|
||||
f.validations.select(id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow('Every train');
|
||||
await f.experiments.retryTrial(
|
||||
id,
|
||||
trial.runId!,
|
||||
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
|
||||
actor()
|
||||
);
|
||||
await train(f, id);
|
||||
const result = (
|
||||
await f.pool.query('SELECT canonical_result FROM backtest_results WHERE run_id=$1', [
|
||||
trial.runId,
|
||||
])
|
||||
).rows[0].canonical_result;
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
for (const changed of [
|
||||
{
|
||||
...result,
|
||||
financial: {
|
||||
...result.financial,
|
||||
identity: { ...result.financial.identity, datasetHash: 'a'.repeat(64) },
|
||||
},
|
||||
},
|
||||
{
|
||||
...result,
|
||||
analytics: {
|
||||
...result.analytics,
|
||||
metrics: { ...result.analytics.metrics, totalReturn: null },
|
||||
unavailable: { ...result.analytics.unavailable, totalReturn: 'nonfinite-result' },
|
||||
},
|
||||
},
|
||||
]) {
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [
|
||||
trial.runId,
|
||||
changed,
|
||||
]);
|
||||
await expect(
|
||||
f.validations.select(id, { previewHash: start.preview.previewHash }, actor())
|
||||
).rejects.toThrow();
|
||||
expect((await f.validations.get(id)).selection).toBeNull();
|
||||
expect(
|
||||
(
|
||||
await f.pool.query(
|
||||
'SELECT count(*)::int AS n FROM research_experiments WHERE validation_parent_id=$1',
|
||||
[id]
|
||||
)
|
||||
).rows[0].n
|
||||
).toBe(0);
|
||||
}
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$2 WHERE run_id=$1', [
|
||||
trial.runId,
|
||||
result,
|
||||
]);
|
||||
}, 60_000);
|
||||
});
|
||||
|
|
@ -68,6 +68,7 @@ async function fixture() {
|
|||
'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')
|
||||
|
|
|
|||
|
|
@ -76,6 +76,7 @@ async function fixture() {
|
|||
'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')
|
||||
|
|
|
|||
|
|
@ -87,6 +87,7 @@ async function fixture() {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ async function fixture(poolMax = 4, withRetries = true) {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
...(withRetries ? ['23-experiment-retries.sql'] : []),
|
||||
...(withRetries ? ['23-experiment-retries.sql', '24-chronological-validation.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -745,6 +745,13 @@ describe.skipIf(!url)('guarded failed experiment trial retry', () => {
|
|||
expect(
|
||||
(await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows
|
||||
).toEqual(outbox);
|
||||
// Current services require the later validation columns; verify SQL23 evidence first.
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([]);
|
||||
const accepted = await f.experiments.retryTrial(experimentId, runId, observed(), receipt());
|
||||
const after = await row(f, runId);
|
||||
|
|
|
|||
|
|
@ -64,7 +64,9 @@ async function fixture(poolMax = 4, withExperiments = true) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
...(withExperiments ? ['22-experiments.sql', '23-experiment-retries.sql'] : []),
|
||||
...(withExperiments
|
||||
? ['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')
|
||||
|
|
@ -709,6 +711,12 @@ describe.skipIf(!url)('retained-input experiments', () => {
|
|||
'utf8'
|
||||
)
|
||||
);
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} };
|
||||
const preview = await f.experiments.preview(input);
|
||||
expect(
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ const migrations = [
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,9 @@ const retention =
|
|||
sql('21-run-reproduction.sql') +
|
||||
sql('22-experiments.sql') +
|
||||
'\n' +
|
||||
sql('23-experiment-retries.sql');
|
||||
sql('23-experiment-retries.sql') +
|
||||
'\n' +
|
||||
sql('24-chronological-validation.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ async function fixture() {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,7 +62,12 @@ async function fixture(poolMax = 4, withReproduction = true) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
...(withReproduction
|
||||
? ['21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql']
|
||||
? [
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
]
|
||||
: []),
|
||||
]) {
|
||||
await pool.query(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue