feat(research): preview chronological validation inputs and windows
This commit is contained in:
parent
b373410320
commit
67ab30cb7a
25 changed files with 2917 additions and 54 deletions
|
|
@ -5,6 +5,7 @@ import {
|
|||
canonicalResearchSettingsSchema,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ChronologicalValidationPreview } from '@stock-bot/stock-config/chronological-validation';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
|
|
@ -14,6 +15,7 @@ import type {
|
|||
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 {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
|
|
@ -36,6 +38,134 @@ afterAll(async () => {
|
|||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
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());
|
||||
try {
|
||||
const { dataset, recipe, start, minute } = chronologicalDataset();
|
||||
await retainResearchDataset(f.pool, dataset);
|
||||
const selected = (await f.seedCatalog()).find(
|
||||
item => item.package.program.strategyId === 'sma_crossover'
|
||||
)!;
|
||||
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
|
||||
decision: 'approve',
|
||||
reason: 'Reviewed canonical chronological preflight fixture',
|
||||
});
|
||||
const backtest = await f.request('/api/v2/backtests', 'POST', {
|
||||
name: 'Chronological preflight template',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: selected.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,
|
||||
},
|
||||
autoStart: false,
|
||||
});
|
||||
const evidence = async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
`SELECT (SELECT count(*) FROM backtest_datasets) AS datasets,
|
||||
(SELECT count(*) FROM research_experiments) AS experiments,
|
||||
(SELECT count(*) FROM runs) AS runs,
|
||||
(SELECT count(*) FROM backtest_dispatch) AS dispatch,
|
||||
(SELECT count(*) FROM backtest_results) AS results,
|
||||
(SELECT row_to_json(b) FROM backtests b WHERE id=$1) AS template`,
|
||||
[backtest.id]
|
||||
)
|
||||
).rows[0];
|
||||
const before = await evidence();
|
||||
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('Chronological input check');
|
||||
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'];
|
||||
await f.page
|
||||
.getByLabel(`${phase} warmup start (UTC)`, { exact: true })
|
||||
.fill(new Date(window.warmupStart).toISOString());
|
||||
await f.page
|
||||
.getByLabel(`${phase} trading start (UTC)`, { exact: true })
|
||||
.fill(new Date(window.tradeStart).toISOString());
|
||||
await f.page
|
||||
.getByLabel(`${phase} trading end (UTC)`, { exact: true })
|
||||
.fill(new Date(window.tradeEnd).toISOString());
|
||||
}
|
||||
const prepare = async () => {
|
||||
const reply = f.page.waitForResponse(response =>
|
||||
response.url().endsWith('/api/v2/experiments/validation/preview')
|
||||
);
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Preview chronological validation', exact: true })
|
||||
.click();
|
||||
return reply;
|
||||
};
|
||||
const response = await prepare();
|
||||
expect(response.status()).toBe(200);
|
||||
const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview };
|
||||
expect(response.request().postDataJSON().recipe).toEqual(recipe);
|
||||
expect(preview.execution).toBe('preview-only');
|
||||
expect(preview.source.dataset.hash).toBe(dataset.manifest.hash);
|
||||
expect(preview.partitions.map(partition => partition.phase)).toEqual([
|
||||
'train',
|
||||
'validation',
|
||||
'test',
|
||||
]);
|
||||
expect(preview.source.candidates).toHaveLength(2);
|
||||
const preparedInputs = f.page.getByRole('region', {
|
||||
name: 'Prepared chronological inputs',
|
||||
exact: true,
|
||||
});
|
||||
await visible(f.page, 'Exact chronological preview inputs and policies');
|
||||
await f.page
|
||||
.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/);
|
||||
for (const partition of preview.partitions) {
|
||||
await visible(f.page, partition.dataset.hash);
|
||||
expect(partition.requiredWarmup).toBe(4);
|
||||
}
|
||||
expect(await evidence()).toEqual(before);
|
||||
// Structurally valid bounds with too few available warmup observations reject explicitly.
|
||||
await f.page
|
||||
.getByLabel('Train warmup start (UTC)', { exact: true })
|
||||
.fill(new Date(start + 4 * minute).toISOString());
|
||||
expect(await preparedInputs.count()).toBe(0);
|
||||
const invalid = await prepare();
|
||||
expect(invalid.status()).toBe(400);
|
||||
const failure = (await invalid.json()) as { error: string };
|
||||
await visible(f.page, failure.error);
|
||||
await f.page
|
||||
.getByLabel('Train warmup start (UTC)', { exact: true })
|
||||
.fill(new Date(recipe.train.warmupStart).toISOString());
|
||||
const repeated = await prepare();
|
||||
expect(repeated.status()).toBe(200);
|
||||
expect((await repeated.json()).preview.previewHash).toBe(preview.previewHash);
|
||||
await visible(f.page, 'Exact chronological preview inputs and policies');
|
||||
await f.page
|
||||
.getByText('Exact chronological preview inputs and policies', { exact: true })
|
||||
.click();
|
||||
expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash);
|
||||
await f.page.getByLabel('Experiment name', { exact: true }).fill('Changed input');
|
||||
expect(await preparedInputs.count()).toBe(0);
|
||||
await f.page.reload();
|
||||
await visible(f.page, /No experiments yet/);
|
||||
expect(await preparedInputs.count()).toBe(0);
|
||||
expect(await evidence()).toEqual(before);
|
||||
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());
|
||||
|
|
|
|||
43
test/fixtures/chronological-validation.ts
vendored
Normal file
43
test/fixtures/chronological-validation.ts
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { nativeReplayFixture } from './native-replay';
|
||||
|
||||
/** Three explicit windows; a later suffix can change without changing earlier observations. */
|
||||
export function chronologicalDataset(testSuffixPrice?: number) {
|
||||
const fixture = nativeReplayFixture(36);
|
||||
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 >= 28 && testSuffixPrice !== undefined
|
||||
? testSuffixPrice + 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;
|
||||
return {
|
||||
...fixture,
|
||||
dataset,
|
||||
recipe: {
|
||||
version: 1 as const,
|
||||
labelHorizonMs: 0 as const,
|
||||
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) },
|
||||
},
|
||||
};
|
||||
}
|
||||
137
test/integration/chronological-validation-api.test.ts
Normal file
137
test/integration/chronological-validation-api.test.ts
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
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(body: string, role?: keyof typeof tokens) {
|
||||
return app.request('/api/v2/experiments/validation/preview', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
},
|
||||
body,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('chronological validation HTTP boundary', () => {
|
||||
test('verified credentials are mandatory even for disabled development auth; read roles cannot prepare', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
expect((await f.request(JSON.stringify(input))).status).toBe(401);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
expect((await f.request(JSON.stringify(input), 'read')).status).toBe(403);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('malformed bodies, raw reserved keys, nonzero labels, fitted models and implicit windows reject before storage', async () => {
|
||||
for (const body of [
|
||||
'{',
|
||||
'[]',
|
||||
'null',
|
||||
JSON.stringify({ ...input, backtestId: 'invalid' }),
|
||||
JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }),
|
||||
JSON.stringify({ ...input, modelArtifacts: ['fit'] }),
|
||||
JSON.stringify({ ...input, recipe: { ...input.recipe, labelHorizonMs: 1 } }),
|
||||
JSON.stringify({ ...input, recipe: { ...input.recipe, embargoMs: 0 } }),
|
||||
JSON.stringify({
|
||||
...input,
|
||||
recipe: {
|
||||
...input.recipe,
|
||||
train: { ...input.recipe.train, tradeStart: '2024-01-01T09:06:00Z' },
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
...input,
|
||||
recipe: {
|
||||
...input.recipe,
|
||||
train: { ...input.recipe.train, warmupStart: input.recipe.train.tradeStart },
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
...input,
|
||||
recipe: {
|
||||
...input.recipe,
|
||||
validation: { ...input.recipe.validation, tradeStart: input.recipe.train.tradeEnd - 1 },
|
||||
},
|
||||
}),
|
||||
JSON.stringify(input).replace('"fastPeriod":[1,2]', '"__proto__":[1]'),
|
||||
]) {
|
||||
const f = fixture();
|
||||
const response = await f.request(body, 'operator');
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('operator and service requests bind the preview method without requiring a receipt; missing and archived are distinct', async () => {
|
||||
for (const role of ['operator', 'service'] as const) {
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
expect(sql).toBe('SELECT * FROM backtests WHERE id=$1 FOR UPDATE');
|
||||
expect(values).toEqual([input.backtestId]);
|
||||
return { rows: [] };
|
||||
});
|
||||
const response = await f.request(JSON.stringify(input), role);
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.json()).toEqual({ error: 'Backtest not found' });
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(1);
|
||||
}
|
||||
const f = fixture('enabled', async () => ({
|
||||
rows: [{ id: input.backtestId, archived_at: new Date() }],
|
||||
}));
|
||||
expect((await f.request(JSON.stringify(input), 'operator')).status).toBe(409);
|
||||
});
|
||||
test('unexpected storage and internal schema failures remain sanitized server errors, never invalid user input', async () => {
|
||||
for (const error of [new Error('secret database connection detail'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await f.request(JSON.stringify(input), 'operator');
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
156
test/integration/chronological-validation-native.test.ts
Normal file
156
test/integration/chronological-validation-native.test.ts
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
|
||||
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
|
||||
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { prepareChronologicalValidation } from '../../apps/stock/web-api/src/services/validation-preview';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
|
||||
const versionId = '00000000-0000-4000-8000-000000000021';
|
||||
const backtestId = '00000000-0000-4000-8000-000000000022';
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
async function prepared(testSuffixPrice?: number) {
|
||||
const fixture = chronologicalDataset(testSuffixPrice);
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const policy = structuredClone(fixture.config);
|
||||
const ownerId = `strategy:${versionId}`;
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
policy.matching.risk.ledger.ownerIds = [ownerId];
|
||||
policy.matching.owners = [{ ownerId, mode: 'Target' }];
|
||||
policy.cadence = [{ owner_id: ownerId, series_ids: ['X0.US:1m'] }];
|
||||
const clock = canonicalRiskSessionClock(fixture.dataset);
|
||||
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: 'Chronological fixture',
|
||||
strategy: {
|
||||
familyId: '00000000-0000-4000-8000-000000000023',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '00000000-0000-4000-8000-000000000024',
|
||||
package: pkg,
|
||||
selection: {
|
||||
strategyId: pkg.program.strategyId,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
ownerId,
|
||||
seed: 42,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '40',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
},
|
||||
},
|
||||
datasetHash: fixture.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: Bun.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
},
|
||||
modelArtifacts: [],
|
||||
});
|
||||
const input: ChronologicalValidationInput = {
|
||||
backtestId,
|
||||
name: 'Three-window input check',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
recipe: fixture.recipe,
|
||||
};
|
||||
const { recipe: _recipe, ...experimentInput } = input;
|
||||
const source = buildExperimentPreview(experimentInput, request, fixture.dataset.manifest);
|
||||
const original = JSON.stringify({ source, dataset: fixture.dataset });
|
||||
const preparation = prepareChronologicalValidation(input, source, fixture.dataset);
|
||||
expect(JSON.stringify({ source, dataset: fixture.dataset })).toBe(original);
|
||||
return preparation;
|
||||
}
|
||||
|
||||
type Prepared = Awaited<ReturnType<typeof prepared>>;
|
||||
function execute(preparation: Prepared, index: number) {
|
||||
const partition = preparation.preview.partitions[index]!;
|
||||
const strategy = createBuiltinStrategy(partition.request.strategy.selection);
|
||||
let decisions = 0;
|
||||
const run = runStrategyReplay(
|
||||
prepareReplayLoad(preparation.datasets[partition.phase], partition.request.policy),
|
||||
[
|
||||
{
|
||||
...strategy,
|
||||
decide(context) {
|
||||
expect(context.now).toBeGreaterThanOrEqual(partition.dataset.bounds.tradeStart);
|
||||
expect(context.now).toBeLessThan(partition.dataset.bounds.tradeEnd);
|
||||
expect(context.observations.every(bar => bar.available_at <= context.now)).toBe(true);
|
||||
if (decisions++ === 0) {
|
||||
expect(context.portfolio.portfolio.cash).toBe(parseFinancialDecimal('10000'));
|
||||
expect(context.positions).toEqual([]);
|
||||
expect(context.portfolio.orders).toEqual([]);
|
||||
expect(context.state).toEqual(strategy.initialState);
|
||||
}
|
||||
return strategy.decide(context);
|
||||
},
|
||||
},
|
||||
],
|
||||
{ resultFormat: 'report', eventBudget: 3 }
|
||||
);
|
||||
expect(decisions).toBeGreaterThan(0);
|
||||
expect(run.result.reporting.initialEquity).toBe(parseFinancialDecimal('10000'));
|
||||
expect(run.result.projection.fills.length).toBeGreaterThan(0);
|
||||
for (const fill of run.result.projection.fills) {
|
||||
expect(fill.eventTime).toBeGreaterThanOrEqual(partition.dataset.bounds.tradeStart);
|
||||
expect(fill.eventTime).toBeLessThan(partition.dataset.bounds.tradeEnd);
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
describe('chronological preflight slices on the authoritative native engine', () => {
|
||||
test('each phase independently starts with initial cash, empty positions and fresh state; warmup cannot trade', async () => {
|
||||
const preparation = await prepared();
|
||||
expect(preparation.preview.execution).toBe('preview-only');
|
||||
for (const index of [0, 1, 2]) {
|
||||
const first = execute(preparation, index);
|
||||
const repeated = execute(preparation, index);
|
||||
expect(repeated.result).toEqual(first.result);
|
||||
expect(repeated.diagnostics).toEqual(first.diagnostics);
|
||||
}
|
||||
});
|
||||
|
||||
test('changing only the test suffix cannot change training or validation inputs, native economics or decisions', async () => {
|
||||
const before = await prepared();
|
||||
const after = await prepared(1000);
|
||||
expect(after.preview.previewHash).not.toBe(before.preview.previewHash);
|
||||
expect(after.preview.source.dataset.hash).not.toBe(before.preview.source.dataset.hash);
|
||||
expect(after.preview.partitions[2].dataset.hash).not.toBe(
|
||||
before.preview.partitions[2].dataset.hash
|
||||
);
|
||||
for (const index of [0, 1] as const) {
|
||||
const phase = before.preview.partitions[index]!.phase;
|
||||
expect(after.preview.partitions[index]).toEqual(before.preview.partitions[index]);
|
||||
expect(after.datasets[phase]).toEqual(before.datasets[phase]);
|
||||
const original = execute(before, index);
|
||||
const changed = execute(after, index);
|
||||
expect(changed.result).toEqual(original.result);
|
||||
expect(changed.diagnostics).toEqual(original.diagnostics);
|
||||
}
|
||||
});
|
||||
});
|
||||
621
test/integration/chronological-validation-ui.test.tsx
Normal file
621
test/integration/chronological-validation-ui.test.tsx
Normal file
|
|
@ -0,0 +1,621 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
chronologicalValidationPolicy,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import type { ExperimentPreview } from '@stock-bot/stock-config/experiments';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
const backtestId = '11111111-1111-4111-8111-111111111111';
|
||||
const otherBacktestId = '22222222-2222-4222-8222-222222222222';
|
||||
const versionId = '55555555-5555-4555-8555-555555555555';
|
||||
const endpoint = '/api/v2/experiments/validation/preview';
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (cause: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
headers: Headers;
|
||||
settled: boolean;
|
||||
signal?: AbortSignal | null;
|
||||
credentials?: RequestCredentials;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing ${method} ${path}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, value: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(value, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function field(label: string) {
|
||||
const found = [...host.querySelectorAll('label')]
|
||||
.find(
|
||||
item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label
|
||||
)
|
||||
?.querySelector('input,select,textarea');
|
||||
if (!found) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
|
||||
}
|
||||
function change(label: string, value: string) {
|
||||
const input = field(label);
|
||||
const prototype =
|
||||
input.tagName === 'SELECT'
|
||||
? browser.HTMLSelectElement.prototype
|
||||
: input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(
|
||||
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
||||
bubbles: true,
|
||||
}) as unknown as Event
|
||||
);
|
||||
}
|
||||
function Probe() {
|
||||
navigate = router.useNavigate();
|
||||
location = router.useLocation().pathname + router.useLocation().search;
|
||||
return null;
|
||||
}
|
||||
const template = (id = backtestId): Backtest => ({
|
||||
id,
|
||||
name: `Template ${id}`,
|
||||
strategy: 'sma',
|
||||
strategyVersionId: versionId,
|
||||
symbols: ['X0.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-01-02',
|
||||
initialCapital: 100,
|
||||
config: { canonical: {}, datasetHash: 'a'.repeat(64) },
|
||||
archivedAt: null,
|
||||
createdAt: '2026-10-24',
|
||||
updatedAt: '2026-10-24',
|
||||
});
|
||||
function sourcePreview(count = 2, parent = backtestId): ExperimentPreview {
|
||||
const owner = `strategy:${versionId}`;
|
||||
const { config, dataset } = nativeReplayFixture(60, 1, [owner]);
|
||||
const previewId = '00000000-0000-4000-8000-000000000001';
|
||||
config.matching.risk.ledger.sessionId = previewId;
|
||||
config.matching.risk.ledger.accountId = `research:${previewId}`;
|
||||
const builtin = builtinCatalogDescriptors[0]!;
|
||||
const candidates = Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 1).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 2, slowPeriod: 20 },
|
||||
}));
|
||||
return {
|
||||
version: 'research-experiment-preview/v1',
|
||||
previewHash: 'e'.repeat(64),
|
||||
input: {
|
||||
backtestId: parent,
|
||||
name: 'Trend study',
|
||||
grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) },
|
||||
},
|
||||
dataset: dataset.manifest,
|
||||
candidates,
|
||||
request: canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: previewId,
|
||||
backtestId: parent,
|
||||
name: 'Frozen template name',
|
||||
strategy: {
|
||||
familyId: '66666666-6666-4666-8666-666666666666',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '88888888-8888-4888-8888-888888888888',
|
||||
package: {
|
||||
version: 1,
|
||||
program: builtin.program,
|
||||
parameterSchema: builtin.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: builtin.entryExport,
|
||||
content: 'Never execute fixture code',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: {
|
||||
format: 'bun-lock/v1',
|
||||
content: 'Retained lock',
|
||||
sha256: 'b'.repeat(64),
|
||||
},
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
},
|
||||
selection: {
|
||||
strategyId: builtin.program.strategyId,
|
||||
strategyVersion: builtin.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 17,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 20 },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
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: '1.2.17',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function prepared(): ChronologicalValidationPreview {
|
||||
const source = sourcePreview();
|
||||
const start = source.dataset.bounds.warmupStart;
|
||||
const minute = 60000;
|
||||
const bounds = (offset: number) => ({
|
||||
warmupStart: start + offset * minute,
|
||||
tradeStart: start + (offset + 22) * minute,
|
||||
tradeEnd: start + (offset + 30) * minute,
|
||||
});
|
||||
const input: ChronologicalValidationInput = {
|
||||
...source.input,
|
||||
recipe: {
|
||||
version: 1,
|
||||
train: bounds(0),
|
||||
validation: bounds(10),
|
||||
test: bounds(20),
|
||||
labelHorizonMs: 0,
|
||||
},
|
||||
};
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const partitions = phases.map((phase, index) => {
|
||||
const dataset = {
|
||||
...structuredClone(source.dataset),
|
||||
hash: ['a', 'b', 'c'][index]!.repeat(64),
|
||||
bounds: input.recipe[phase],
|
||||
barCount: 30,
|
||||
};
|
||||
const request = { ...structuredClone(source.request), datasetHash: dataset.hash };
|
||||
return {
|
||||
phase,
|
||||
dataset,
|
||||
request,
|
||||
counts: {
|
||||
totalBars: 30,
|
||||
availableWarmup: 21,
|
||||
admittedWarmup: 21,
|
||||
ignoredLateWarmup: 0,
|
||||
availableEvaluation: 8,
|
||||
terminalAtEnd: 1,
|
||||
unavailableAtEnd: 0,
|
||||
},
|
||||
requiredWarmup: 21,
|
||||
warnings: ['Input history sufficiency does not establish statistical adequacy.'],
|
||||
};
|
||||
}) as ChronologicalValidationPreview['partitions'];
|
||||
return {
|
||||
version: 'chronological-validation-preview/v1',
|
||||
execution: 'preview-only',
|
||||
previewHash: 'f'.repeat(64),
|
||||
input,
|
||||
source,
|
||||
policy: chronologicalValidationPolicy,
|
||||
partitions,
|
||||
};
|
||||
}
|
||||
async function mount() {
|
||||
root ??= createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: [`/experiments?backtestId=${backtestId}`] },
|
||||
createElement(ExperimentListPage),
|
||||
createElement(Probe)
|
||||
)
|
||||
)
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(), template(otherBacktestId)]);
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] });
|
||||
});
|
||||
}
|
||||
async function fill(value = prepared()) {
|
||||
await mount();
|
||||
await flush(() => {
|
||||
change('Experiment name', value.input.name);
|
||||
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
|
||||
for (const phase of ['train', 'validation', 'test'] as const) {
|
||||
const label = phase[0]!.toUpperCase() + phase.slice(1);
|
||||
change(
|
||||
`${label} warmup start (UTC)`,
|
||||
new Date(value.input.recipe[phase].warmupStart).toISOString()
|
||||
);
|
||||
change(
|
||||
`${label} trading start (UTC)`,
|
||||
new Date(value.input.recipe[phase].tradeStart).toISOString()
|
||||
);
|
||||
change(
|
||||
`${label} trading end (UTC)`,
|
||||
new Date(value.input.recipe[phase].tradeEnd).toISOString()
|
||||
);
|
||||
}
|
||||
});
|
||||
return value;
|
||||
}
|
||||
async function ready(value = prepared()) {
|
||||
await fill(value);
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
await flush(() => reply(request(endpoint, 'POST'), { preview: value }));
|
||||
return value;
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
Event: browser.Event,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ExperimentListPage } = await import('../../apps/stock/web-app/src/features/experiments'));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
location = '';
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
Object.defineProperty(browser, 'fetch', {
|
||||
configurable: true,
|
||||
value: (input: unknown, init?: RequestInit) => {
|
||||
const url = new URL(String(input));
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: url.pathname + url.search,
|
||||
method: init?.method ?? 'GET',
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
headers: new Headers(init?.headers),
|
||||
signal: init?.signal,
|
||||
credentials: init?.credentials,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Ignore abort so generation/identity fencing is exercised.
|
||||
},
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const old = originals.get(key);
|
||||
if (old) {
|
||||
Object.defineProperty(globalThis, key, old);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Preview chronological validation').click();
|
||||
button('Preview chronological validation').click();
|
||||
});
|
||||
expect(host.textContent).toContain('Preparing chronological validation preview...');
|
||||
const post = request(endpoint, 'POST');
|
||||
expect(post.body).toEqual(value.input);
|
||||
expect(post.headers.has('Idempotency-Key')).toBe(false);
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
await flush(() => reply(post, { preview: value }));
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain('2 parameter candidates checked');
|
||||
expect(host.textContent).toContain('No candidate has been selected or evaluated.');
|
||||
expect(host.textContent).toContain('maximize train total return');
|
||||
expect(host.textContent).toContain('Validation is diagnostic only; test is holdout only');
|
||||
expect(host.textContent).toContain('independent reset segments');
|
||||
for (const phase of ['Train', 'Validation', 'Test']) {
|
||||
const card = host.querySelector(`[aria-label="${phase} partition"]`)!;
|
||||
expect(card.textContent).toContain('21 / 21');
|
||||
expect(card.textContent).toContain('Available exactly at end (terminal mark only)');
|
||||
expect(card.textContent).toContain('Input history sufficiency');
|
||||
}
|
||||
expect(
|
||||
host
|
||||
.querySelector('[aria-label="Chronological validation preflight"]')!
|
||||
.querySelectorAll('button')
|
||||
).toHaveLength(1);
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
});
|
||||
test.each([
|
||||
'Experiment name',
|
||||
'Parameter grid (JSON)',
|
||||
'Saved backtest',
|
||||
'Train trading end (UTC)',
|
||||
])(
|
||||
'%s changes invalidate visible and pending previews without automatically reposting',
|
||||
async label => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
const old = request(endpoint, 'POST');
|
||||
const next =
|
||||
label === 'Experiment name'
|
||||
? 'Changed'
|
||||
: label === 'Parameter grid (JSON)'
|
||||
? '{}'
|
||||
: label === 'Saved backtest'
|
||||
? otherBacktestId
|
||||
: '2024-01-01T09:29:00Z';
|
||||
await flush(() => change(label, next));
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(old, { preview: value }));
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
expect(requests.filter(item => item.path === endpoint)).toHaveLength(2);
|
||||
}
|
||||
);
|
||||
test.each([
|
||||
'2024-01-01T09:00:00',
|
||||
'2024-01-01T09:00:00+00:00',
|
||||
'2024-02-30T09:00:00Z',
|
||||
'2024-01-01T09:00:00.0001Z',
|
||||
'',
|
||||
])('rejects ambiguous or invalid UTC value %s before any request', async text => {
|
||||
await fill();
|
||||
await flush(() => change('Train warmup start (UTC)', text));
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
expect(host.textContent).toContain('must be a real UTC instant ending in Z');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
});
|
||||
test('chronology and invalid grid reject locally, including overlapping evaluation windows', async () => {
|
||||
await fill();
|
||||
await flush(() => change('Validation trading start (UTC)', '2024-01-01T09:29:00Z'));
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
expect(host.textContent).toContain('chronological and nonoverlapping');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => {
|
||||
change('Validation trading start (UTC)', '2024-01-01T09:32:00Z');
|
||||
change('Parameter grid (JSON)', '{"__proto__":[1]}');
|
||||
});
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
expect(host.textContent).toContain('Invalid parameter name');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
});
|
||||
test.each([400, 401, 404, 409, 500])(
|
||||
'HTTP %s has a visible retryable error and never admits a sweep',
|
||||
async status => {
|
||||
const value = await fill();
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
await flush(() =>
|
||||
reply(
|
||||
request(endpoint, 'POST'),
|
||||
{ error: 'Train has insufficient admitted warmup: 4 of 21 observations' },
|
||||
status
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('Train has insufficient admitted warmup');
|
||||
expect(button('Preview chronological validation').disabled).toBe(false);
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
await flush(() => reply(request(endpoint, 'POST'), { preview: value }));
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).not.toBeNull();
|
||||
expect(
|
||||
requests.filter(item => item.method === 'POST').every(item => item.path === endpoint)
|
||||
).toBe(true);
|
||||
}
|
||||
);
|
||||
test.each([
|
||||
'wrong-parent',
|
||||
'wrong-name',
|
||||
'wrong-grid',
|
||||
'wrong-policy',
|
||||
'phase-order',
|
||||
'phase-bounds',
|
||||
'changed-finance',
|
||||
'changed-metadata',
|
||||
'count-mismatch',
|
||||
'manifest-count',
|
||||
'missing-terminal',
|
||||
'invalid-warmup',
|
||||
'partial',
|
||||
] as const)('malformed %s response fails closed', async kind => {
|
||||
const value = await fill();
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
const invalid = structuredClone(value);
|
||||
if (kind === 'wrong-parent') {
|
||||
invalid.source.input.backtestId = otherBacktestId;
|
||||
}
|
||||
if (kind === 'wrong-name') {
|
||||
invalid.source.input.name = 'Different';
|
||||
}
|
||||
if (kind === 'wrong-grid') {
|
||||
invalid.source.input.grid = {};
|
||||
}
|
||||
if (kind === 'wrong-policy') {
|
||||
(invalid.policy.selection as unknown as Record<string, unknown>).metric = 'sharpeRatio';
|
||||
}
|
||||
if (kind === 'phase-order') {
|
||||
invalid.partitions.reverse();
|
||||
}
|
||||
if (kind === 'phase-bounds') {
|
||||
invalid.partitions[0].dataset = {
|
||||
...invalid.partitions[0].dataset,
|
||||
bounds: {
|
||||
...invalid.partitions[0].dataset.bounds,
|
||||
tradeEnd: value.input.recipe.train.tradeEnd - 60000,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (kind === 'changed-finance') {
|
||||
invalid.partitions[0].request.policy.matching.risk.maxDailyLoss = '123.00000000' as never;
|
||||
}
|
||||
if (kind === 'changed-metadata') {
|
||||
invalid.partitions[0].dataset = {
|
||||
...invalid.partitions[0].dataset,
|
||||
series: invalid.partitions[0].dataset.series.map(item => ({ ...item, interval: '5m' })),
|
||||
};
|
||||
}
|
||||
if (kind === 'count-mismatch') {
|
||||
invalid.partitions[0].counts.totalBars = 99;
|
||||
}
|
||||
if (kind === 'manifest-count') {
|
||||
invalid.partitions[0].dataset = { ...invalid.partitions[0].dataset, barCount: 99 };
|
||||
}
|
||||
if (kind === 'missing-terminal') {
|
||||
delete (invalid.partitions[0].counts as Partial<(typeof invalid.partitions)[0]['counts']>)
|
||||
.terminalAtEnd;
|
||||
}
|
||||
if (kind === 'invalid-warmup') {
|
||||
invalid.partitions[0].requiredWarmup = 22;
|
||||
}
|
||||
await flush(() =>
|
||||
reply(
|
||||
request(endpoint, 'POST'),
|
||||
kind === 'partial' ? { preview: { previewHash: value.previewHash } } : { preview: invalid }
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
});
|
||||
test('network loss and stale route responses are recoverable without creating records', async () => {
|
||||
const value = await fill();
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
const post = request(endpoint, 'POST');
|
||||
await flush(() => {
|
||||
post.settled = true;
|
||||
post.reject(new Error('Connection lost'));
|
||||
});
|
||||
expect(host.textContent).toContain('Connection lost');
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
const stale = request(endpoint, 'POST');
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() => reply(stale, { preview: value }));
|
||||
expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`);
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
expect(field('Train warmup start (UTC)').value).toBe('');
|
||||
});
|
||||
test('ordinary unresolved submission disables and invalidates preflight without changing its exact sweep body', async () => {
|
||||
const value = await fill();
|
||||
await flush(() => button('Preview chronological validation').click());
|
||||
const stale = request(endpoint, 'POST');
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/experiments/preview', 'POST'), { preview: value.source })
|
||||
);
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const ordinary = request('/api/v2/experiments', 'POST');
|
||||
expect(ordinary.body).toEqual({ ...value.source.input, previewHash: value.source.previewHash });
|
||||
expect(ordinary.headers.has('Idempotency-Key')).toBe(true);
|
||||
await flush(() => {
|
||||
ordinary.settled = true;
|
||||
ordinary.reject(new Error('Lost ordinary receipt'));
|
||||
});
|
||||
await flush(() => reply(stale, { preview: value }));
|
||||
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'
|
||||
);
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(button('Preview chronological validation').disabled).toBe(false);
|
||||
expect(field('Train warmup start (UTC)').value).toBe(
|
||||
new Date(value.input.recipe.train.warmupStart).toISOString()
|
||||
);
|
||||
expect(host.querySelector('[aria-label="Prepared chronological inputs"]')).toBeNull();
|
||||
});
|
||||
test('window-only draft participates in the existing owned-navigation discard guard', async () => {
|
||||
await mount();
|
||||
await flush(() => change('Train warmup start (UTC)', '2024-01-01T09:00:00Z'));
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
expect(field('Train warmup start (UTC)').value).toBe('2024-01-01T09:00:00Z');
|
||||
});
|
||||
test('delayed observations remain explicit and tiny evaluation warnings are not performance evidence', async () => {
|
||||
const value = prepared();
|
||||
value.partitions[2].counts.availableEvaluation = 1;
|
||||
value.partitions[2].counts.unavailableAtEnd = 7;
|
||||
value.partitions[2].warnings = [
|
||||
'Only one evaluation observation is available.',
|
||||
'Seven delayed observations remain unavailable at the end.',
|
||||
];
|
||||
await ready(value);
|
||||
const card = host.querySelector('[aria-label="Test partition"]')!;
|
||||
expect(card.textContent).toContain('Only one evaluation observation');
|
||||
expect(card.textContent).toContain('Seven delayed observations');
|
||||
expect(host.textContent).toContain(
|
||||
'Warmup sufficiency is not evidence of profitability or statistical adequacy'
|
||||
);
|
||||
});
|
||||
});
|
||||
423
test/integration/chronological-validation.test.ts
Normal file
423
test/integration/chronological-validation.test.ts
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
HistoricalDataset,
|
||||
HistoricalDatasetInputV2,
|
||||
HistoricalDatasetV2,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
convertDatasetV1ToV2,
|
||||
createDatasetV2,
|
||||
sliceDatasetV2,
|
||||
validateDatasetV2,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import {
|
||||
parseChronologicalValidation,
|
||||
prepareChronologicalValidation,
|
||||
} from '../../apps/stock/web-api/src/services/validation-preview';
|
||||
import { chronologicalDataset } from '../fixtures/chronological-validation';
|
||||
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const backtestId = '10000000-0000-4000-8000-000000000001';
|
||||
const versionId = '20000000-0000-4000-8000-000000000001';
|
||||
const owner = `strategy:${versionId}`;
|
||||
const input = (): ChronologicalValidationInput => ({
|
||||
backtestId,
|
||||
name: 'Chronological input checks',
|
||||
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
|
||||
recipe: chronologicalDataset().recipe,
|
||||
});
|
||||
function source(
|
||||
dataset: HistoricalDatasetV2,
|
||||
raw = input(),
|
||||
meanParameters?: Record<string, string | number>
|
||||
) {
|
||||
const { recipe: _recipe, ...experiment } = raw;
|
||||
const descriptor = builtinCatalogDescriptors[meanParameters ? 1 : 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: meanParameters ?? { 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);
|
||||
}
|
||||
function providerInput(dataset: HistoricalDatasetV2): HistoricalDatasetInputV2 {
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
dataset.manifest;
|
||||
return {
|
||||
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
||||
bars: dataset.bars.map(
|
||||
({
|
||||
seriesId,
|
||||
intervalStart,
|
||||
availableAt,
|
||||
sourceSequence,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
vwap,
|
||||
}) => ({
|
||||
seriesId,
|
||||
timestamp: intervalStart,
|
||||
availableAt,
|
||||
sourceSequence,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
vwap,
|
||||
})
|
||||
),
|
||||
};
|
||||
}
|
||||
function changedAvailability(delays: Record<number, number>) {
|
||||
const fixture = chronologicalDataset();
|
||||
const raw = providerInput(fixture.dataset);
|
||||
return createDatasetV2({
|
||||
...raw,
|
||||
bars: raw.bars.map((bar, index) => ({
|
||||
...bar,
|
||||
availableAt: fixture.start + (delays[index] ?? index + 1) * fixture.minute,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
describe('chronological validation input preparation', () => {
|
||||
test('exact slices retain observations and all provenance without mutating the source or financial policy', () => {
|
||||
const dataset = chronologicalDataset().dataset,
|
||||
raw = input(),
|
||||
preview = source(dataset, raw);
|
||||
const before = structuredClone({ dataset, preview, raw });
|
||||
const result = prepareChronologicalValidation(raw, preview, dataset);
|
||||
expect(prepareChronologicalValidation(raw, preview, dataset)).toEqual(result);
|
||||
expect({ dataset, preview, raw }).toEqual(before);
|
||||
expect(result.preview.execution).toBe('preview-only');
|
||||
expect(result.preview.policy).toMatchObject({
|
||||
selection: { phase: 'train', metric: 'totalReturn', requireAllCandidates: true },
|
||||
reset: 'initial-capital-empty-positions',
|
||||
});
|
||||
for (const phase of ['train', 'validation', 'test'] as const) {
|
||||
const slice = result.datasets[phase],
|
||||
partition = result.preview.partitions.find(p => p.phase === phase)!;
|
||||
expect(validateDatasetV2(slice)).toEqual(slice);
|
||||
expect(slice.bars).toEqual(
|
||||
dataset.bars.filter(
|
||||
b =>
|
||||
b.intervalStart >= raw.recipe[phase].warmupStart &&
|
||||
b.intervalEnd <= raw.recipe[phase].tradeEnd
|
||||
)
|
||||
);
|
||||
expect(slice.manifest.parentDatasetHash).toBeNull();
|
||||
for (const key of [
|
||||
'calendars',
|
||||
'series',
|
||||
'executionSeries',
|
||||
'universe',
|
||||
'corporateActions',
|
||||
] as const) {
|
||||
expect(slice.manifest[key]).toEqual(dataset.manifest[key]);
|
||||
}
|
||||
const expected = structuredClone(preview.request),
|
||||
clock = canonicalRiskSessionClock(slice);
|
||||
expected.datasetHash = slice.manifest.hash;
|
||||
expected.policy.matching.risk.ledger.riskSession = clock.riskSession;
|
||||
expected.policy.risk_boundaries = clock.riskBoundaries;
|
||||
expect(partition.request).toEqual(expected);
|
||||
expect(partition.counts.terminalAtEnd).toBe(1);
|
||||
const c = partition.counts;
|
||||
expect(c.availableWarmup + c.availableEvaluation + c.terminalAtEnd + c.unavailableAtEnd).toBe(
|
||||
c.totalBars
|
||||
);
|
||||
}
|
||||
});
|
||||
test('direct slice rejects out-of-source bounds, invalid ordering and every bar-cut boundary', () => {
|
||||
const dataset = chronologicalDataset().dataset,
|
||||
bounds = input().recipe.train;
|
||||
for (const changed of [
|
||||
{ ...bounds, warmupStart: bounds.warmupStart - 1 },
|
||||
{ ...bounds, tradeStart: dataset.manifest.bounds.tradeStart - 1 },
|
||||
{ ...bounds, tradeEnd: dataset.manifest.bounds.tradeEnd + 1 },
|
||||
{ ...bounds, warmupStart: bounds.tradeStart + 60_000 },
|
||||
{ ...bounds, tradeStart: bounds.tradeEnd },
|
||||
{ ...bounds, tradeEnd: bounds.tradeStart - 60_000 },
|
||||
...(['warmupStart', 'tradeStart', 'tradeEnd'] as const).map(key => ({
|
||||
...bounds,
|
||||
[key]: bounds[key] + 1,
|
||||
})),
|
||||
]) {
|
||||
expect(() => sliceDatasetV2(dataset, changed)).toThrow();
|
||||
}
|
||||
});
|
||||
test('later test suffix cannot change earlier datasets, requests or counts; full source identity still changes', () => {
|
||||
const raw = input(),
|
||||
first = chronologicalDataset().dataset,
|
||||
changed = chronologicalDataset(900).dataset;
|
||||
const before = prepareChronologicalValidation(raw, source(first, raw), first);
|
||||
const after = prepareChronologicalValidation(raw, source(changed, raw), changed);
|
||||
expect(after.preview.previewHash).not.toBe(before.preview.previewHash);
|
||||
expect(after.datasets.train).toEqual(before.datasets.train);
|
||||
expect(after.datasets.validation).toEqual(before.datasets.validation);
|
||||
expect(after.preview.partitions.slice(0, 2)).toEqual(before.preview.partitions.slice(0, 2));
|
||||
expect(after.datasets.test.manifest.hash).not.toBe(before.datasets.test.manifest.hash);
|
||||
});
|
||||
test('availability, terminal-only and ignored late warmup counts reflect arrival order without dropping delayed bars', () => {
|
||||
const raw = input(),
|
||||
dataset = changedAvailability({ 0: 5, 10: 13 });
|
||||
const result = prepareChronologicalValidation(raw, source(dataset, raw), dataset);
|
||||
expect(result.preview.partitions[0].counts).toEqual({
|
||||
totalBars: 12,
|
||||
availableWarmup: 5,
|
||||
admittedWarmup: 4,
|
||||
ignoredLateWarmup: 1,
|
||||
availableEvaluation: 5,
|
||||
terminalAtEnd: 1,
|
||||
unavailableAtEnd: 1,
|
||||
});
|
||||
expect(result.datasets.train.bars).toHaveLength(12);
|
||||
expect(result.preview.partitions[0].warnings).toHaveLength(2);
|
||||
const insufficient = changedAvailability({ 0: 5, 1: 5 });
|
||||
expect(() =>
|
||||
prepareChronologicalValidation(raw, source(insufficient, raw), insufficient)
|
||||
).toThrow('3 admitted warmup');
|
||||
const unavailable = changedAvailability(
|
||||
Object.fromEntries(Array.from({ length: 6 }, (_, i) => [i + 5, 13]))
|
||||
);
|
||||
expect(() =>
|
||||
prepareChronologicalValidation(raw, source(unavailable, raw), unavailable)
|
||||
).toThrow('no observations');
|
||||
});
|
||||
test('SMA readiness uses the largest candidate period and rejects warmup at the exact trading start', () => {
|
||||
const dataset = chronologicalDataset().dataset;
|
||||
const ready = { ...input(), grid: { fastPeriod: [1], slowPeriod: [3, 4] } };
|
||||
expect(
|
||||
prepareChronologicalValidation(ready, source(dataset, ready), dataset).preview.partitions[0]
|
||||
.requiredWarmup
|
||||
).toBe(5);
|
||||
const insufficient = { ...ready, grid: { fastPeriod: [1], slowPeriod: [3, 5] } };
|
||||
expect(() =>
|
||||
prepareChronologicalValidation(insufficient, source(dataset, insufficient), dataset)
|
||||
).toThrow('5 admitted warmup observations; 6 required');
|
||||
});
|
||||
test('mean reversion readiness covers trend, lookback and both return-history periods across the grid', () => {
|
||||
const dataset = chronologicalDataset().dataset;
|
||||
const parameters = {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 2,
|
||||
exitZScore: 1,
|
||||
minTrendReturn: 0,
|
||||
minMomentumReturn: 0,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: '0',
|
||||
regimeFilter: 'volatility',
|
||||
};
|
||||
for (const [grid, required] of [
|
||||
[{ trendPeriod: [3, 5] }, 5],
|
||||
[{ momentumPeriod: [1, 4] }, 5],
|
||||
[{ volatilityPeriod: [2, 4] }, 5],
|
||||
[{ lookbackPeriod: [2, 3], trendPeriod: [4] }, 4],
|
||||
] as const) {
|
||||
const raw = parseChronologicalValidation({ ...input(), grid });
|
||||
expect(
|
||||
prepareChronologicalValidation(raw, source(dataset, raw, parameters), dataset).preview
|
||||
.partitions[0].requiredWarmup
|
||||
).toBe(required);
|
||||
}
|
||||
for (const grid of [
|
||||
{ trendPeriod: [6] },
|
||||
{ momentumPeriod: [5] },
|
||||
{ volatilityPeriod: [5] },
|
||||
{ lookbackPeriod: [6], trendPeriod: [7] },
|
||||
]) {
|
||||
const raw = parseChronologicalValidation({ ...input(), grid });
|
||||
expect(() =>
|
||||
prepareChronologicalValidation(raw, source(dataset, raw, parameters), dataset)
|
||||
).toThrow('admitted warmup');
|
||||
}
|
||||
});
|
||||
test('sparse calendar gaps remain sparse and each segment receives the exact original clock inclusivity', () => {
|
||||
const fixture = nativeReplayFixture(1208),
|
||||
dataset = fixture.dataset;
|
||||
const sessions = dataset.manifest.calendars[0]!.sessions;
|
||||
const raw = input();
|
||||
raw.recipe.train = {
|
||||
warmupStart: sessions[0]!.open,
|
||||
tradeStart: sessions[0]!.open + 6 * fixture.minute,
|
||||
tradeEnd: sessions[1]!.open,
|
||||
};
|
||||
raw.recipe.validation = {
|
||||
warmupStart: sessions[1]!.open,
|
||||
tradeStart: sessions[1]!.open + 6 * fixture.minute,
|
||||
tradeEnd: sessions[2]!.open,
|
||||
};
|
||||
raw.recipe.test = {
|
||||
warmupStart: sessions[2]!.open,
|
||||
tradeStart: sessions[2]!.open + 6 * fixture.minute,
|
||||
tradeEnd: dataset.manifest.bounds.tradeEnd,
|
||||
};
|
||||
const result = prepareChronologicalValidation(raw, source(dataset, raw), dataset);
|
||||
expect(result.datasets.train.bars).toHaveLength(600);
|
||||
expect(result.datasets.validation.bars).toHaveLength(600);
|
||||
expect(result.datasets.test.bars).toHaveLength(8);
|
||||
const expected = (i: number) => ({
|
||||
calendarId: 'fixture-calendar',
|
||||
calendarRevision: '1',
|
||||
sessionId: sessions[i]!.date,
|
||||
startsAt: sessions[i]!.open,
|
||||
});
|
||||
expect(canonicalRiskSessionClock(dataset)).toEqual({
|
||||
riskSession: expected(0),
|
||||
riskBoundaries: [expected(1), expected(2)],
|
||||
});
|
||||
for (const [index, partition] of result.preview.partitions.entries()) {
|
||||
expect(partition.request.policy.matching.risk.ledger.riskSession).toEqual(expected(index));
|
||||
expect(partition.request.policy.risk_boundaries).toEqual(
|
||||
index < 2 ? [expected(index + 1)] : []
|
||||
);
|
||||
}
|
||||
expect(result.preview.partitions[2].warnings).toContain(
|
||||
'Only 2 evaluation observations; input readiness does not establish statistical adequacy'
|
||||
);
|
||||
});
|
||||
test('v1 conversion lineage and null VWAP provenance survive slicing without inventing v2 ancestry', () => {
|
||||
const fixture = datasetInput();
|
||||
const bars = fixture.bars.map(row => ({
|
||||
symbol: 'A.US',
|
||||
timestamp: Date.parse(String(row.timestamp)),
|
||||
open: row.open,
|
||||
high: row.high,
|
||||
low: row.low,
|
||||
close: row.close,
|
||||
volume: row.volume,
|
||||
vwap: 101,
|
||||
}));
|
||||
const manifest = {
|
||||
version: 1 as const,
|
||||
instruments: [{ id: 'A.US', symbol: 'A', exchange: 'US' }],
|
||||
startDate: '2024-03-08T00:00:00.000Z',
|
||||
endDate: '2024-11-30T00:00:00.000Z',
|
||||
interval: '1d',
|
||||
policy: { adjustment: 'raw' as const, timestamp: 'utc-session-date' as const },
|
||||
volumePolicy: 'reported' as const,
|
||||
qualityPolicy: 'reject-invalid-no-interpolation' as const,
|
||||
sources: [
|
||||
{ instrumentId: 'A.US', provider: 'eod' as const, revision: 'historical-normalization-v1' },
|
||||
],
|
||||
barCount: bars.length,
|
||||
};
|
||||
const legacy: HistoricalDataset = {
|
||||
manifest: {
|
||||
...manifest,
|
||||
hash: createHash('sha256').update(JSON.stringify({ manifest, bars })).digest('hex'),
|
||||
},
|
||||
bars,
|
||||
};
|
||||
const converted = convertDatasetV1ToV2(legacy, fixture.metadata);
|
||||
const bounds = {
|
||||
...converted.manifest.bounds,
|
||||
tradeEnd: fixture.metadata.calendars[0]!.sessions[1]!.close,
|
||||
};
|
||||
const slice = sliceDatasetV2(converted, bounds);
|
||||
expect(slice.manifest.parentDatasetHash).toBe(legacy.manifest.hash);
|
||||
expect(slice.manifest.parentDatasetHash).not.toBe(converted.manifest.hash);
|
||||
expect(slice.bars.every(b => b.vwap === null)).toBe(true);
|
||||
expect(slice.manifest.limitations).toEqual(converted.manifest.limitations);
|
||||
expect(validateDatasetV2(slice)).toEqual(slice);
|
||||
});
|
||||
test('corrupt source identities fail closed and strict recipe forbids fitting, labels, overlap and unknown fields', () => {
|
||||
const dataset = chronologicalDataset().dataset,
|
||||
raw = input(),
|
||||
preview = source(dataset, raw);
|
||||
expect(() =>
|
||||
prepareChronologicalValidation({ ...raw, name: 'other' }, preview, dataset)
|
||||
).toThrow('identity mismatch');
|
||||
const bad = structuredClone(preview);
|
||||
bad.candidates[0]!.parameters = {};
|
||||
expect(() => prepareChronologicalValidation(raw, bad, dataset)).toThrow('integrity');
|
||||
for (const recipe of [
|
||||
{ ...raw.recipe, labelHorizonMs: 1 },
|
||||
{ ...raw.recipe, fit: true },
|
||||
{
|
||||
...raw.recipe,
|
||||
validation: { ...raw.recipe.validation, tradeStart: raw.recipe.train.tradeEnd - 1 },
|
||||
},
|
||||
{ ...raw.recipe, train: { ...raw.recipe.train, warmupStart: raw.recipe.train.tradeStart } },
|
||||
]) {
|
||||
expect(() => parseChronologicalValidation({ ...raw, recipe })).toThrow(
|
||||
'Invalid chronological'
|
||||
);
|
||||
}
|
||||
expect(() => parseChronologicalValidation({ ...raw, modelArtifacts: [] })).toThrow();
|
||||
const tooMany = {
|
||||
...raw,
|
||||
grid: { fastPeriod: Array.from({ length: 101 }, (_, i) => i + 1), slowPeriod: [199] },
|
||||
};
|
||||
expect(() => source(dataset, tooMany)).toThrow('at most');
|
||||
});
|
||||
});
|
||||
333
test/postgres/chronological-validation.test.ts
Normal file
333
test/postgres/chronological-validation.test.ts
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool, type PoolClient } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type {
|
||||
ChronologicalValidationInput,
|
||||
ChronologicalValidationPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
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() {
|
||||
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: 1,
|
||||
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',
|
||||
]) {
|
||||
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;
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
experiments,
|
||||
catalog,
|
||||
version,
|
||||
draft,
|
||||
dataset,
|
||||
input,
|
||||
request,
|
||||
review,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('chronological validation PostgreSQL preflight', () => {
|
||||
test('real approved retained preview uses one transaction/connection, writes no tables and leaves ordinary economic policy unchanged', async () => {
|
||||
const f = await fixture(),
|
||||
review = await f.review(),
|
||||
before = await f.snapshot();
|
||||
const observed: string[] = [],
|
||||
transaction = f.postgres.transaction.bind(f.postgres);
|
||||
Object.defineProperty(f.postgres, 'transaction', {
|
||||
value: <T>(work: (client: PoolClient) => Promise<T>) =>
|
||||
transaction(client =>
|
||||
work(
|
||||
new Proxy(client, {
|
||||
get(target, property) {
|
||||
if (property === 'query') {
|
||||
return (sql: string, values?: unknown[]) => {
|
||||
observed.push(sql);
|
||||
return target.query(sql, values);
|
||||
};
|
||||
}
|
||||
const value = Reflect.get(target, property);
|
||||
return typeof value === 'function' ? value.bind(target) : value;
|
||||
},
|
||||
})
|
||||
)
|
||||
),
|
||||
});
|
||||
const response = await f.request();
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview };
|
||||
expect(preview.source.request.strategy.reviewId).toBe(review.id);
|
||||
expect(preview.source.dataset).toEqual(f.dataset.manifest);
|
||||
expect(preview.execution).toBe('preview-only');
|
||||
expect(preview.source.candidates).toHaveLength(2);
|
||||
expect(preview.partitions.map(p => p.phase)).toEqual(['train', 'validation', 'test']);
|
||||
expect(preview.source.request.build.engineBinarySha256).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(observed.length).toBeGreaterThan(0);
|
||||
expect(observed.every(sql => sql.trimStart().startsWith('SELECT'))).toBe(true);
|
||||
expect(observed[0]).toContain('FROM backtests WHERE id=$1 FOR UPDATE');
|
||||
expect(observed[1]).toContain('FOR UPDATE OF s');
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
const ordinary = await f.experiments.preview({
|
||||
backtestId: f.draft.id,
|
||||
name: f.input.name,
|
||||
grid: f.input.grid,
|
||||
});
|
||||
expect(preview.source).toEqual(ordinary);
|
||||
expect(ordinary.request.policy.matching.risk).toEqual({
|
||||
ledger: {
|
||||
version: 1,
|
||||
sessionId: ordinary.request.runId,
|
||||
accountId: `research:${ordinary.request.runId}`,
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
ownerIds: [`strategy:${f.version.id}`],
|
||||
initialCapital: parseFinancialDecimal('10000'),
|
||||
riskSession: {
|
||||
calendarId: 'fixture-calendar',
|
||||
calendarRevision: '1',
|
||||
sessionId: '2024-01-01',
|
||||
startsAt: f.dataset.manifest.bounds.warmupStart,
|
||||
},
|
||||
},
|
||||
feeRate: parseFinancialDecimal(canonicalSettings.feeRate),
|
||||
maxOrderQuantity: parseFinancialDecimal(canonicalSettings.maxOrderQuantity),
|
||||
maxPositionQuantity: parseFinancialDecimal(canonicalSettings.maxPositionQuantity),
|
||||
maxSymbolExposure: parseFinancialDecimal(canonicalSettings.maxSymbolExposure),
|
||||
maxGrossExposure: parseFinancialDecimal(canonicalSettings.maxGrossExposure),
|
||||
maxDailyLoss: parseFinancialDecimal(canonicalSettings.maxDailyLoss),
|
||||
maxDrawdownAmount: parseFinancialDecimal(canonicalSettings.maxDrawdownAmount),
|
||||
maxMarkAgeMs: canonicalSettings.maxMarkAgeMs,
|
||||
});
|
||||
expect(ordinary.request.policy.risk_boundaries).toEqual([]);
|
||||
expect(await (await f.request(f.input, 'service')).json()).toEqual({ preview });
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
}, 30_000);
|
||||
test('current approval, family/template availability and exact saved dataset remain authoritative', async () => {
|
||||
const f = await fixture();
|
||||
expect((await f.request()).status).toBe(409);
|
||||
const first = await f.review(),
|
||||
initial = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview };
|
||||
expect(initial.preview.source.request.strategy.reviewId).toBe(first.id);
|
||||
await f.review('revoke');
|
||||
expect((await f.request()).status).toBe(409);
|
||||
const latest = await f.review(),
|
||||
newer = (await (await f.request()).json()) as { preview: ChronologicalValidationPreview };
|
||||
expect(newer.preview.source.request.strategy.reviewId).toBe(latest.id);
|
||||
expect(newer.preview.previewHash).not.toBe(initial.preview.previewHash);
|
||||
expect(newer.preview.partitions.map(p => p.dataset.hash)).toEqual(
|
||||
initial.preview.partitions.map(p => p.dataset.hash)
|
||||
);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
const archivedFamily = await f.snapshot();
|
||||
expect((await f.request()).status).toBe(409);
|
||||
expect(await f.snapshot()).toEqual(archivedFamily);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NULL WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
expect((await f.request()).status).toBe(409);
|
||||
expect((await f.request({ ...f.input, backtestId: randomUUID() })).status).toBe(404);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
|
||||
}, 30_000);
|
||||
test('recipe cuts, insufficient candidate history and invalid or excessive grids reject without persistence', async () => {
|
||||
const f = await fixture();
|
||||
await f.review();
|
||||
const before = await f.snapshot();
|
||||
for (const raw of [
|
||||
{
|
||||
...f.input,
|
||||
recipe: {
|
||||
...f.input.recipe,
|
||||
train: { ...f.input.recipe.train, tradeStart: f.input.recipe.train.tradeStart + 1 },
|
||||
},
|
||||
},
|
||||
{
|
||||
...f.input,
|
||||
recipe: {
|
||||
...f.input.recipe,
|
||||
train: {
|
||||
...f.input.recipe.train,
|
||||
warmupStart: f.input.recipe.train.warmupStart - 60_000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ ...f.input, grid: { fastPeriod: [1], slowPeriod: [5] } },
|
||||
{ ...f.input, grid: { unknown: [1] } },
|
||||
{ ...f.input, grid: { fastPeriod: [1, 1] } },
|
||||
{
|
||||
...f.input,
|
||||
grid: {
|
||||
fastPeriod: Array.from({ length: 11 }, (_, i) => i + 1),
|
||||
slowPeriod: Array.from({ length: 10 }, (_, i) => i + 20),
|
||||
},
|
||||
},
|
||||
]) {
|
||||
const response = await f.request(raw);
|
||||
expect(response.status).toBe(400);
|
||||
expect(await f.snapshot()).toEqual(before);
|
||||
}
|
||||
}, 30_000);
|
||||
test('missing or corrupt retained input is unavailable, arbitrary storage failures remain sanitized500', async () => {
|
||||
const f = await fixture();
|
||||
await f.review();
|
||||
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",
|
||||
[f.dataset.manifest.hash]
|
||||
);
|
||||
const corrupt = await f.snapshot();
|
||||
expect((await f.request()).status).toBe(409);
|
||||
expect(await f.snapshot()).toEqual(corrupt);
|
||||
await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]);
|
||||
expect((await f.request()).status).toBe(409);
|
||||
await f.pool.query('ALTER TABLE backtest_datasets RENAME TO unavailable_datasets');
|
||||
const response = await f.request();
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}, 30_000);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue