feat(research): add strategy catalog and versioned backtest setup
This commit is contained in:
parent
8cca0ee588
commit
d929db707a
44 changed files with 4198 additions and 209 deletions
|
|
@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events';
|
|||
import { readFileSync } from 'node:fs';
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { Pool } from 'pg';
|
||||
import { chromium, type Page } from 'playwright';
|
||||
import type { Browser, Page } from 'playwright';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
|
|
@ -27,10 +27,12 @@ import {
|
|||
handleWebSocketConnection,
|
||||
} from '../../apps/stock/web-api/src/routes/websocket.routes';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import {
|
||||
getWebSocketHandler,
|
||||
type RunSocketData,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('browser-fixture');
|
||||
|
|
@ -214,7 +216,7 @@ class FixtureEngine extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
export async function fixture(native = false) {
|
||||
export async function fixture(browser: Browser, native = false) {
|
||||
const database = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
if (
|
||||
|
|
@ -285,7 +287,9 @@ export async function fixture(native = false) {
|
|||
'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',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -399,6 +403,8 @@ export async function fixture(native = false) {
|
|||
(!pathname.startsWith('/api/v2/backtests') &&
|
||||
!pathname.startsWith('/api/v2/runs') &&
|
||||
!pathname.startsWith('/api/v2/datasets') &&
|
||||
!pathname.startsWith('/api/v2/strategies') &&
|
||||
!pathname.startsWith('/api/v2/strategy-versions') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
/\/(pause|resume|speed)$/.test(pathname)
|
||||
) {
|
||||
|
|
@ -458,9 +464,8 @@ export async function fixture(native = false) {
|
|||
}
|
||||
});
|
||||
const origin = `http://127.0.0.1:${server.port}`;
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
cleanup.push(() => browser.close());
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
|
||||
cleanup.push(() => context.close());
|
||||
await context.route('**/*', route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin !== origin && !['data:', 'blob:'].includes(url.protocol)) {
|
||||
|
|
@ -520,10 +525,19 @@ export async function fixture(native = false) {
|
|||
await target.getByRole('button', { name: 'Sign in', exact: true }).click();
|
||||
await visible(target, 'Create and manage backtest configurations');
|
||||
};
|
||||
const request = async (path: string, method = 'GET', body?: unknown) => {
|
||||
const request = async (
|
||||
path: string,
|
||||
method = 'GET',
|
||||
body?: unknown,
|
||||
headers: Record<string, string> = {}
|
||||
) => {
|
||||
const response = await fetch(origin + path, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
|
|
@ -546,6 +560,7 @@ export async function fixture(native = false) {
|
|||
login,
|
||||
close,
|
||||
unexpectedNetwork,
|
||||
seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)),
|
||||
};
|
||||
} catch (error) {
|
||||
try {
|
||||
|
|
@ -560,7 +575,7 @@ export async function fixture(native = false) {
|
|||
export async function createInBrowser(page: Page, name: string, run = false) {
|
||||
await page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await page.getByPlaceholder('My Strategy Backtest').fill(name);
|
||||
await page.locator('select').first().selectOption('moving-average');
|
||||
await page.getByLabel('Legacy strategy', { exact: true }).selectOption('moving-average');
|
||||
await page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await page.locator('input[type="date"]').nth(1).fill('2024-03-15');
|
||||
await page.getByRole('button', { name: run ? 'Save and run' : 'Save', exact: true }).click();
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { expect, test } from 'bun:test';
|
||||
import type { Request } from 'playwright';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { afterAll, beforeAll, expect, test } from 'bun:test';
|
||||
import { chromium, type Browser, type Request } from 'playwright';
|
||||
import {
|
||||
fixture as createFixture,
|
||||
createInBrowser,
|
||||
fixture,
|
||||
gate,
|
||||
retainDataset,
|
||||
submitInBrowser,
|
||||
|
|
@ -11,6 +11,18 @@ import {
|
|||
visible,
|
||||
} from './fixture';
|
||||
|
||||
// Repeated launch/close cycles lost Chromium's control pipe under Bun 1.2.17.
|
||||
// Keep one suite-owned process; each fixture still owns
|
||||
// a fresh context, server, database schema and queue. No retries hide failures.
|
||||
let browser: Browser;
|
||||
beforeAll(async () => {
|
||||
browser = await chromium.launch({ headless: true });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser?.close();
|
||||
});
|
||||
const fixture = (native = false) => createFixture(browser, native);
|
||||
|
||||
// Serial by design: the production WebSocket projection has a process-local handler.
|
||||
test('browser_saved_run_lifecycle', async () => {
|
||||
const f = await fixture();
|
||||
|
|
@ -479,3 +491,213 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
|
|||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
||||
const f = await fixture();
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/strategies`);
|
||||
await visible(f.page, /No strategies found/);
|
||||
await f.page.getByRole('button', { name: 'New strategy', exact: true }).click();
|
||||
await f.page.getByLabel('Strategy name', { exact: true }).fill('Browser research family');
|
||||
await f.page
|
||||
.getByLabel('Strategy description', { exact: true })
|
||||
.fill('A hypothesis awaiting evidence.');
|
||||
await f.page.getByRole('button', { name: 'Create strategy', exact: true }).click();
|
||||
await f.page.waitForURL(/\/strategies\/[^/]+$/);
|
||||
await visible(f.page, /No immutable versions have been published/);
|
||||
await f.page
|
||||
.getByLabel('Strategy description', { exact: true })
|
||||
.fill('Revised hypothesis, still unvalidated.');
|
||||
await f.page.getByRole('button', { name: 'Save metadata', exact: true }).click();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.request('/api/v2/strategies')).strategies[0]?.description ===
|
||||
'Revised hypothesis, still unvalidated.',
|
||||
'saved strategy metadata'
|
||||
);
|
||||
|
||||
const seeded = await f.seedCatalog();
|
||||
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
|
||||
const versionUrl = `${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`;
|
||||
await f.page.goto(versionUrl);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('20');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('10');
|
||||
const invalid = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/strategy-versions/${selected.id}/validate`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
expect((await invalid).status()).toBe(400);
|
||||
expect(
|
||||
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isDisabled()
|
||||
).toBe(true);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('5');
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
|
||||
await f.page.waitForURL(
|
||||
url =>
|
||||
url.pathname === '/backtests' && url.searchParams.get('strategyVersionId') === selected.id
|
||||
);
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Pinned version browser draft');
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
|
||||
selected.id,
|
||||
'loaded exact immutable version selection'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()
|
||||
).toBe(selected.id);
|
||||
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await f.page.locator('input[type="date"]').nth(1).fill('2024-03-15');
|
||||
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
|
||||
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('5');
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
|
||||
).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
await f.page.waitForURL(/\/backtests\/[^/?]+$/);
|
||||
const draftUrl = f.page.url();
|
||||
const draftId = draftUrl.split('/').at(-1)!;
|
||||
const saved = await f.request(`/api/v2/backtests/${draftId}`);
|
||||
expect(saved.strategy).toBe('catalog');
|
||||
expect(saved.strategyVersionId).toBe(selected.id);
|
||||
expect(saved.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 5 });
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
await expect(f.request(`/api/v2/backtests/${draftId}/runs`, 'POST', {})).rejects.toThrow('409');
|
||||
|
||||
// A later immutable publication must never move the saved selection to the newest version.
|
||||
const { package: retained } = await f.request(
|
||||
`/api/v2/strategy-versions/${selected.id}/artifact`
|
||||
);
|
||||
const changed = structuredClone(retained);
|
||||
changed.artifact.content +=
|
||||
'\n/* </pre><script>globalThis.__catalogBrowserExecuted=true</script> */\nglobalThis.__catalogBrowserExecuted=true;';
|
||||
changed.artifact.sha256 = createHash('sha256').update(changed.artifact.content).digest('hex');
|
||||
const revision = await f.request(
|
||||
`/api/v2/strategies/${selected.strategyId}/versions`,
|
||||
'POST',
|
||||
{ package: changed },
|
||||
{ 'Idempotency-Key': randomUUID() }
|
||||
);
|
||||
await f.page.reload();
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await until(
|
||||
async () =>
|
||||
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
|
||||
selected.id,
|
||||
'loaded exact immutable version selection'
|
||||
);
|
||||
expect(
|
||||
await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()
|
||||
).toBe(selected.id);
|
||||
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
|
||||
const validateVisibleParameters = async () => {
|
||||
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
||||
await visible(
|
||||
f.page,
|
||||
'Parameters validated for this immutable version. Execution remains unavailable.'
|
||||
);
|
||||
};
|
||||
const saveVisibleSettings = async () => {
|
||||
const update = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${draftId}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
const response = await update;
|
||||
expect(response.status()).toBe(200);
|
||||
const updated = await response.json();
|
||||
expect(updated.strategyVersionId).toBe(selected.id);
|
||||
expect(updated.config).not.toHaveProperty('speedMultiplier');
|
||||
return updated;
|
||||
};
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('3');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('7');
|
||||
await validateVisibleParameters();
|
||||
expect((await saveVisibleSettings()).strategyParameters).toEqual({
|
||||
fastPeriod: 3,
|
||||
slowPeriod: 7,
|
||||
});
|
||||
// Archive/restore replaces authoritative settings; stale validated child state must reset too.
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('4');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('9');
|
||||
await validateVisibleParameters();
|
||||
await f.page.getByRole('button', { name: 'Archive backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
|
||||
await visible(f.page, 'Restore backtest');
|
||||
await f.page.getByRole('button', { name: 'Restore backtest', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Confirm restore', exact: true }).click();
|
||||
await visible(f.page, 'Archive backtest');
|
||||
await until(
|
||||
async () => (await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()) === '3',
|
||||
'restored saved parameter state'
|
||||
);
|
||||
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('7');
|
||||
expect(await f.page.getByRole('button', { name: 'Save', exact: true }).isDisabled()).toBe(true);
|
||||
await f.page.getByLabel('fastPeriod', { exact: true }).fill('4');
|
||||
await f.page.getByLabel('slowPeriod', { exact: true }).fill('9');
|
||||
await validateVisibleParameters();
|
||||
expect((await saveVisibleSettings()).strategyParameters).toEqual({
|
||||
fastPeriod: 4,
|
||||
slowPeriod: 9,
|
||||
});
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
||||
true
|
||||
);
|
||||
expect(f.page.url()).toBe(draftUrl);
|
||||
await f.page.goto(
|
||||
`${f.origin}/strategies/${selected.strategyId}/versions/${revision.version.id}`
|
||||
);
|
||||
await f.page.getByLabel('Compare with version', { exact: true }).selectOption(selected.id);
|
||||
await visible(f.page, 'Different artifact bytes');
|
||||
expect(
|
||||
await f.page.getByLabel('Selected bundled JavaScript', { exact: true }).textContent()
|
||||
).toContain('__catalogBrowserExecuted');
|
||||
expect(await f.page.evaluate(() => Object.hasOwn(globalThis, '__catalogBrowserExecuted'))).toBe(
|
||||
false
|
||||
);
|
||||
|
||||
await f.page.goto(versionUrl);
|
||||
await f.page.getByRole('button', { name: 'Clone version', exact: true }).click();
|
||||
await f.page.getByLabel('Clone name', { exact: true }).fill('Browser candidate clone');
|
||||
const cloned = f.page.waitForResponse(response =>
|
||||
response.url().endsWith(`/strategy-versions/${selected.id}/clone`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Create clone', exact: true }).click();
|
||||
const cloneResponse = await cloned;
|
||||
expect(cloneResponse.status()).toBe(201);
|
||||
const clone = await cloneResponse.json();
|
||||
expect(clone.version.parentVersionId).toBe(selected.id);
|
||||
expect(clone.version.origin).toBe('candidate');
|
||||
expect(clone.version.reviewStatus).toBe('pending');
|
||||
expect(clone.version.runnable).toBe(false);
|
||||
await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${clone.version.id}`));
|
||||
await f.page.getByLabel('Compare with version', { exact: true }).selectOption(selected.id);
|
||||
await visible(f.page, 'Identical artifact bytes');
|
||||
await f.page.reload();
|
||||
await f.page.getByLabel('Strategy version', { exact: true }).waitFor();
|
||||
expect(await f.page.getByLabel('Strategy version', { exact: true }).inputValue()).toBe(
|
||||
clone.version.id
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ async function fixture(
|
|||
});
|
||||
db.public
|
||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz,
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz, strategy_version_id uuid, strategy_parameters jsonb,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
|
|
|
|||
138
test/integration/catalog-backtest-contract.test.ts
Normal file
138
test/integration/catalog-backtest-contract.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
backtestSettingsFromDefinition,
|
||||
CatalogBacktestDefinitionSchema,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
builtinCatalogDescriptors,
|
||||
parseStrategyVersionPackage,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
|
||||
const definition = {
|
||||
name: 'Catalog setup',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: randomUUID(),
|
||||
strategyParameters: {},
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-02-01T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
config: { dataFrequency: '1d', commission: 0.002 },
|
||||
};
|
||||
describe('catalog draft and execution contracts', () => {
|
||||
test('shared settings validation is independent of execution and never merges strategy parameters', () => {
|
||||
const parsed = CatalogBacktestDefinitionSchema.parse({
|
||||
...definition,
|
||||
strategyParameters: { commission: 99 },
|
||||
});
|
||||
const settings = backtestSettingsFromDefinition(parsed);
|
||||
expect(settings).toMatchObject({
|
||||
commission: 0.002,
|
||||
slippage: 0.0001,
|
||||
symbols: ['AAPL.US'],
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
expect(settings).not.toHaveProperty('strategy');
|
||||
expect(settings).not.toHaveProperty('strategyParameters');
|
||||
expect(() => backtestRequestFromDefinition(parsed)).toThrow('Retained strategy versions');
|
||||
for (const config of [
|
||||
{ ...definition.config, lookback: 5 },
|
||||
{ ...definition.config, strategyVersionId: randomUUID() },
|
||||
]) {
|
||||
expect(() => CatalogBacktestDefinitionSchema.parse({ ...definition, config })).toThrow();
|
||||
}
|
||||
expect(() => backtestSettingsFromDefinition({ ...definition, initialCapital: 0 })).toThrow();
|
||||
expect(() =>
|
||||
backtestSettingsFromDefinition({ ...definition, endDate: definition.startDate })
|
||||
).toThrow();
|
||||
});
|
||||
test('legacy parsers and direct repository refuse markers even when null or nested', async () => {
|
||||
const legacy = {
|
||||
mode: 'backtest',
|
||||
name: 'Legacy',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate,
|
||||
endDate: definition.endDate,
|
||||
dataFrequency: '1d',
|
||||
initialCapital: 1000,
|
||||
};
|
||||
const database = {
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Unexpected write');
|
||||
}),
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(database);
|
||||
for (const marker of [
|
||||
{ strategy: 'catalog' },
|
||||
{ strategyVersionId: null },
|
||||
{ strategyVersionIds: [] },
|
||||
{ strategyParameters: {} },
|
||||
{ config: { strategyVersionId: null } },
|
||||
{ strategies: [{ name: 'sma-crossover', config: { strategyVersionId: 'retained' } }] },
|
||||
]) {
|
||||
const input = { ...legacy, ...marker };
|
||||
expect(() => parseBacktestRequest(input)).toThrow('Retained strategy versions');
|
||||
await expect(
|
||||
repository.start(input as ReturnType<typeof parseBacktestRequest>)
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
}
|
||||
expect(database.transaction.mock.calls).toHaveLength(0);
|
||||
const facade = new BacktestService({
|
||||
postgres: database,
|
||||
logger: { info() {} },
|
||||
} as unknown as IServiceContainer);
|
||||
await expect(facade.createBacktest(definition)).rejects.toThrow('Retained strategy versions');
|
||||
expect(database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('builtin parameter validation preserves decimal strings and refuses invalid Unicode', () => {
|
||||
const descriptor = builtinCatalogDescriptors.find(
|
||||
item => item.program.strategyId === 'mean_reversion'
|
||||
)!;
|
||||
const pkg = parseStrategyVersionPackage({
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'retained-not-executed',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: '{}', sha256: 'b'.repeat(64) },
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
source: { revision: 'a'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
});
|
||||
const parameters = {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0,
|
||||
minTrendReturn: -0.9,
|
||||
minMomentumReturn: -0.9,
|
||||
maxVolatility: 0,
|
||||
minNotionalVolume: '0.01',
|
||||
regimeFilter: 'none',
|
||||
};
|
||||
expect(() => validateStrategyParameters(pkg, {})).toThrow('Missing parameter');
|
||||
expect(validateStrategyParameters(pkg, parameters).minNotionalVolume).toBe('0.01000000');
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: 100 })
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: '\ud800' })
|
||||
).toThrow('UTF-8');
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: '1\u0000' })
|
||||
).toThrow('UTF-8');
|
||||
});
|
||||
});
|
||||
986
test/integration/strategy-workbench.test.tsx
Normal file
986
test/integration/strategy-workbench.test.tsx
Normal file
|
|
@ -0,0 +1,986 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, useState, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type {
|
||||
StrategyParameterSchema,
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import type { CatalogSelection } from '../../apps/stock/web-app/src/features/strategies/components/StrategySelection';
|
||||
import type { Parameters } from '../../apps/stock/web-app/src/features/strategies/services/strategyApi';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', '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 StrategyListPage: typeof import('../../apps/stock/web-app/src/features/strategies').StrategyListPage;
|
||||
let StrategyDetailPage: typeof import('../../apps/stock/web-app/src/features/strategies').StrategyDetailPage;
|
||||
let StrategyParameterForm: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategyParameterForm').StrategyParameterForm;
|
||||
let StrategySelection: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategySelection').StrategySelection;
|
||||
let LegacyStrategySelect: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategySelection').LegacyStrategySelect;
|
||||
let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog;
|
||||
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
|
||||
let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2;
|
||||
let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
let latest: ReturnType<typeof useBacktestV2>;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: 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;
|
||||
};
|
||||
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(
|
||||
`No pending ${method} ${path}; requests: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
||||
);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, body: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(body, { status }));
|
||||
}
|
||||
function fail(item: Pending) {
|
||||
item.settled = true;
|
||||
item.reject(new Error('Response lost'));
|
||||
}
|
||||
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 || item.getAttribute('aria-label') === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function click(label: string) {
|
||||
button(label).click();
|
||||
}
|
||||
function field(label: string) {
|
||||
const found = host.querySelector(`[aria-label="${label}"]`) as
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLTextAreaElement
|
||||
| null;
|
||||
if (!found) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function edit(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() {
|
||||
location = router.useLocation().pathname + router.useLocation().search;
|
||||
navigate = router.useNavigate();
|
||||
return null;
|
||||
}
|
||||
async function mount(element: ReactElement, path = '/') {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
|
||||
)
|
||||
);
|
||||
}
|
||||
const family = (id = 'family', extra: Partial<StrategyRecord> = {}): StrategyRecord => ({
|
||||
id,
|
||||
name: `Strategy ${id}`,
|
||||
description: 'Reviewed fixture',
|
||||
ownerPrincipal: 'operator',
|
||||
updatedBy: 'operator',
|
||||
archived: false,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
...extra,
|
||||
});
|
||||
const schema: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: [],
|
||||
properties: {
|
||||
fastPeriod: { type: 'integer', minimum: 1, default: 5 },
|
||||
slowPeriod: { type: 'integer', minimum: 2, default: 15 },
|
||||
},
|
||||
};
|
||||
const pkg = (
|
||||
content = 'globalThis.CATALOG_MUST_NOT_EXECUTE = true; <img src=x onerror=alert(1)>'
|
||||
): StrategyVersionPackage => ({
|
||||
version: 1,
|
||||
program: {
|
||||
strategyId: 'fixture',
|
||||
strategyVersion: 'v1',
|
||||
apiVersion: 'canonical-ts/v1',
|
||||
checkpointVersion: 'fixture/v1',
|
||||
},
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: 'createFixture',
|
||||
content,
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'lock', sha256: 'b'.repeat(64) },
|
||||
parameterSchema: schema,
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
});
|
||||
const version = (
|
||||
id = 'version-one',
|
||||
extra: Partial<StrategyVersionSummary> = {}
|
||||
): StrategyVersionSummary => {
|
||||
const full = pkg();
|
||||
const { content: _artifact, ...artifact } = full.artifact;
|
||||
const { content: _lock, ...dependencyLock } = full.dependencyLock;
|
||||
return {
|
||||
id,
|
||||
strategyId: 'family',
|
||||
ordinal: 1,
|
||||
parentVersionId: null,
|
||||
createdBy: 'operator',
|
||||
origin: 'builtin',
|
||||
createdAt: '2026-01-01',
|
||||
package: { ...full, artifact, dependencyLock },
|
||||
reviewStatus: 'approved',
|
||||
runnable: false,
|
||||
reason: 'Execution unavailable',
|
||||
...extra,
|
||||
};
|
||||
};
|
||||
const definition = {
|
||||
id: 'definition',
|
||||
name: 'Catalog fixture',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-03-01',
|
||||
initialCapital: 100000,
|
||||
config: {},
|
||||
archivedAt: null,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
};
|
||||
async function detail(path = '/strategies/family/versions/version-one', versions = [version()]) {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/strategies/:strategyId/versions/:versionId',
|
||||
element: createElement(StrategyDetailPage),
|
||||
})
|
||||
),
|
||||
path
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies/family'), { strategy: family() });
|
||||
reply(request('/api/v2/strategies/family/versions'), { versions });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: versions[0], reviews: [] });
|
||||
});
|
||||
}
|
||||
async function selected(archived = false) {
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies'), { strategies: [family('family', { archived })] });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] });
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family'), { strategy: family('family', { archived }) })
|
||||
);
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family/versions'), { versions: [version()] })
|
||||
);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
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');
|
||||
({ StrategyListPage, StrategyDetailPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies'
|
||||
));
|
||||
({ StrategyParameterForm } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/StrategyParameterForm'
|
||||
));
|
||||
({ StrategySelection, LegacyStrategySelect } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/StrategySelection'
|
||||
));
|
||||
({ CreateBacktestDialog } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog'
|
||||
));
|
||||
({ BacktestDetailPageV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
|
||||
));
|
||||
({ useBacktestV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
|
||||
));
|
||||
({ RunControlsCompact } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'
|
||||
));
|
||||
});
|
||||
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,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(url)).pathname,
|
||||
method: init?.method ?? 'GET',
|
||||
headers: new Headers(init?.headers),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Ignore abort deliberately: stale-response fences must still hold.
|
||||
}) as unknown as typeof browser.fetch;
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const descriptor = originals.get(key);
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('strategy workbench', () => {
|
||||
test('catalog_navigation: loading, failure, retry, empty and metadata create route', async () => {
|
||||
await mount(createElement(StrategyListPage), '/strategies');
|
||||
expect(host.textContent).toContain('Loading strategies...');
|
||||
await flush(() => reply(request('/api/v2/strategies'), { error: 'Catalog offline' }, 503));
|
||||
expect(host.textContent).toContain('Catalog offline');
|
||||
await flush(() => click('Retry strategies'));
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [] }));
|
||||
expect(host.textContent).toContain('No strategies found');
|
||||
await flush(() => click('New strategy'));
|
||||
await flush(() => {
|
||||
edit('Strategy name', 'My hypothesis');
|
||||
edit('Strategy description', 'Research only');
|
||||
});
|
||||
expect(host.textContent).toContain('Unsaved strategy metadata');
|
||||
await flush(() => click('Create strategy'));
|
||||
expect(request('/api/v2/strategies', 'POST').body).toEqual({
|
||||
name: 'My hypothesis',
|
||||
description: 'Research only',
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies', 'POST'), { strategy: family('new-family') }, 201)
|
||||
);
|
||||
expect(location).toBe('/strategies/new-family');
|
||||
});
|
||||
|
||||
test('metadata errors retain unsaved edits; local exit can be declined; archive is explicit', async () => {
|
||||
await detail();
|
||||
await flush(() => edit('Strategy name', 'Edited'));
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => false,
|
||||
});
|
||||
await flush(() => click('Discard metadata changes'));
|
||||
expect(field('Strategy name').value).toBe('Edited');
|
||||
await flush(() => click('Save metadata'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family', 'PATCH'), { error: 'Write failed' }, 503)
|
||||
);
|
||||
expect(field('Strategy name').value).toBe('Edited');
|
||||
expect(host.textContent).toContain('Write failed');
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
await flush(() => click('Discard metadata changes'));
|
||||
await flush(() => click('Archive strategy'));
|
||||
expect(request('/api/v2/strategies/family', 'PATCH').body).toEqual({ archived: true });
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family', 'PATCH'), {
|
||||
strategy: family('family', { archived: true }),
|
||||
})
|
||||
);
|
||||
expect(button('Use in backtest').disabled).toBe(true);
|
||||
expect(button('Restore strategy')).toBeDefined();
|
||||
});
|
||||
|
||||
test('parameter_form_validation: false, zero, typed enums, optional omission and decimal strings survive', async () => {
|
||||
const mixed: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['enabled', 'budget'],
|
||||
properties: {
|
||||
enabled: { type: 'boolean', default: false },
|
||||
count: { type: 'integer', minimum: 0, default: 0 },
|
||||
budget: { type: 'string', default: '000.10' },
|
||||
choice: { type: 'number', enum: [0, 1], default: 0 },
|
||||
optional: { type: 'string' },
|
||||
},
|
||||
};
|
||||
let result: Parameters = {};
|
||||
let valid = false;
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'mixed',
|
||||
schema: mixed,
|
||||
onChange: (parameters, checked) => {
|
||||
result = parameters;
|
||||
valid = checked;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/mixed/validate', 'POST').body).toEqual({
|
||||
parameters: { enabled: false, count: 0, budget: '000.10', choice: 0 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/mixed/validate', 'POST'), {
|
||||
parameters: { enabled: false, count: 0, budget: '0.1', choice: 0 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(valid).toBe(true);
|
||||
expect(result.budget).toBe('0.1');
|
||||
await flush(() => edit('count', '-1'));
|
||||
expect(valid).toBe(false);
|
||||
expect(host.textContent).toContain('outside the allowed range');
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('parameter_form_validation: present empty strings survive defaults; omitted strings stay omitted', async () => {
|
||||
const strings: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['requiredText'],
|
||||
properties: {
|
||||
requiredText: { type: 'string' },
|
||||
optionalText: { type: 'string', default: 'fallback' },
|
||||
absent: { type: 'string' },
|
||||
},
|
||||
};
|
||||
let result: Parameters = {};
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'strings',
|
||||
schema: strings,
|
||||
initialParameters: { requiredText: '', optionalText: '' },
|
||||
onChange: next => {
|
||||
result = next;
|
||||
},
|
||||
})
|
||||
);
|
||||
expect((field('Include requiredText') as HTMLInputElement).checked).toBe(true);
|
||||
expect((field('Include optionalText') as HTMLInputElement).checked).toBe(true);
|
||||
expect((field('Include absent') as HTMLInputElement).checked).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const payload = request('/api/v2/strategy-versions/strings/validate', 'POST');
|
||||
expect(payload.body).toEqual({ parameters: { requiredText: '', optionalText: '' } });
|
||||
await flush(() =>
|
||||
reply(payload, {
|
||||
parameters: { requiredText: '', optionalText: '' },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(result).toEqual({ requiredText: '', optionalText: '' });
|
||||
await flush(() => (field('Include optionalText') as HTMLInputElement).click());
|
||||
expect(result).toEqual({ requiredText: '' });
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/strings/validate', 'POST').body).toEqual({
|
||||
parameters: { requiredText: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('parameter_form_validation: a missing required string can be explicitly included as empty', async () => {
|
||||
const required: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['text'],
|
||||
properties: { text: { type: 'string' } },
|
||||
};
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'required',
|
||||
schema: required,
|
||||
onChange: () => {},
|
||||
})
|
||||
);
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('text: Required');
|
||||
await flush(() => (field('Include text') as HTMLInputElement).click());
|
||||
expect(button('Validate parameters').disabled).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/required/validate', 'POST').body).toEqual({
|
||||
parameters: { text: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('create-family double click is coalesced and late completion cannot navigate after unmount', async () => {
|
||||
await mount(createElement(StrategyListPage), '/strategies');
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [] }));
|
||||
await flush(() => click('New strategy'));
|
||||
await flush(() => edit('Strategy name', 'One family'));
|
||||
await flush(() => {
|
||||
click('Create strategy');
|
||||
click('Create strategy');
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
const pending = request('/api/v2/strategies', 'POST');
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: ['/elsewhere'] }, createElement(Probe))
|
||||
)
|
||||
);
|
||||
await flush(() => reply(pending, { strategy: family('late') }, 201));
|
||||
expect(location).not.toBe('/strategies/late');
|
||||
});
|
||||
|
||||
test('parameter_form_validation: stale success cannot approve edited inputs; server cross-field error is visible', async () => {
|
||||
let valid = false;
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'version-one',
|
||||
schema,
|
||||
onChange: (_parameters, checked) => {
|
||||
valid = checked;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const old = request('/api/v2/strategy-versions/version-one/validate', 'POST');
|
||||
await flush(() => edit('fastPeriod', '20'));
|
||||
await flush(() =>
|
||||
reply(old, {
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(valid).toBe(false);
|
||||
expect(field('fastPeriod').value).toBe('20');
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/strategy-versions/version-one/validate', 'POST'),
|
||||
{ error: 'fastPeriod must be below slowPeriod' },
|
||||
400
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
|
||||
test('immutable_version_selection: late version response cannot replace current route', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version(),
|
||||
version('version-two', { ordinal: 2 }),
|
||||
]);
|
||||
await flush(() => edit('Strategy version', 'version-two'));
|
||||
const old = request('/api/v2/strategy-versions/version-two');
|
||||
await flush(() => navigate('/strategies/family/versions/version-one'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] })
|
||||
);
|
||||
await flush(() => reply(old, { version: version('version-two', { ordinal: 2 }), reviews: [] }));
|
||||
expect(location).toBe('/strategies/family/versions/version-one');
|
||||
expect(host.textContent).toContain('Immutable version ID: version-one');
|
||||
expect(host.textContent).not.toContain('Immutable version ID: version-two');
|
||||
});
|
||||
|
||||
test('clone_revision_diff: clone retries exact frozen body/key and compares inert retained bundles to parent', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version('version-one', {
|
||||
origin: 'candidate',
|
||||
parentVersionId: 'parent',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
]);
|
||||
await flush(() => edit('Compare with version', 'parent'));
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategy-versions/version-one/artifact'), { package: pkg() });
|
||||
reply(request('/api/v2/strategy-versions/parent/artifact'), { package: pkg() });
|
||||
});
|
||||
expect(host.textContent).toContain('Identical artifact bytes');
|
||||
expect(host.querySelector('img')).toBeNull();
|
||||
expect((globalThis as Record<string, unknown>).CATALOG_MUST_NOT_EXECUTE).toBeUndefined();
|
||||
expect(host.querySelector('[aria-label="Selected bundled JavaScript"]')?.textContent).toContain(
|
||||
'<img src=x'
|
||||
);
|
||||
await flush(() => click('Clone version'));
|
||||
await flush(() => edit('Clone name', 'Cloned hypothesis'));
|
||||
await flush(() => click('Create clone'));
|
||||
const first = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
await flush(() => fail(first));
|
||||
expect(field('Clone name').disabled).toBe(true);
|
||||
await flush(() => click('Retry clone'));
|
||||
const second = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(second.body).toEqual(first.body);
|
||||
await flush(() =>
|
||||
reply(
|
||||
second,
|
||||
{
|
||||
strategy: family('clone-family'),
|
||||
version: version('clone-version', {
|
||||
strategyId: 'clone-family',
|
||||
parentVersionId: 'version-one',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
expect(location).toBe('/strategies/clone-family/versions/clone-version');
|
||||
});
|
||||
|
||||
test('clone source identity and retry key stay frozen across same-family history navigation', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version(),
|
||||
version('version-two', { ordinal: 2 }),
|
||||
]);
|
||||
await flush(() => click('Clone version'));
|
||||
await flush(() => edit('Clone name', 'Clone original version'));
|
||||
await flush(() => click('Create clone'));
|
||||
const first = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
// Browser history can change the route even while the version select is disabled.
|
||||
await flush(() => navigate('/strategies/family/versions/version-two'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-two'), {
|
||||
version: version('version-two', { ordinal: 2 }),
|
||||
reviews: [],
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Clone immutable version 1');
|
||||
expect(host.textContent).toContain('Clone source version ID: version-one');
|
||||
expect(host.textContent).toContain('even while you view version 2 (version-two)');
|
||||
const cloned = {
|
||||
strategy: family('clone-family'),
|
||||
version: version('clone-version', {
|
||||
strategyId: 'clone-family',
|
||||
parentVersionId: 'version-one',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
};
|
||||
await flush(() => reply(first, cloned, 201));
|
||||
expect(location).toBe('/strategies/family/versions/version-two');
|
||||
expect(host.textContent).toContain('Clone immutable version 1');
|
||||
await flush(() => click('Retry clone'));
|
||||
const retry = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toEqual(first.body);
|
||||
expect(requests.some(item => item.path === '/api/v2/strategy-versions/version-two/clone')).toBe(
|
||||
false
|
||||
);
|
||||
await flush(() => reply(retry, cloned, 201));
|
||||
expect(location).toBe('/strategies/family/versions/version-two');
|
||||
expect(host.textContent).toContain('Clone source version ID: version-one');
|
||||
});
|
||||
|
||||
test('immutable_version_selection: create saves exact validated ID and parameters without any run request', async () => {
|
||||
let saved: unknown;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
initialSelection: {
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
},
|
||||
onClose: () => {},
|
||||
onCreated: value => {
|
||||
saved = value;
|
||||
},
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
expect(button('Save and run').disabled).toBe(true);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/version-one/validate', 'POST').body).toEqual({
|
||||
parameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
input,
|
||||
'Saved research draft'
|
||||
);
|
||||
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Save'));
|
||||
const post = request('/api/v2/backtests', 'POST');
|
||||
expect(post.body).toMatchObject({
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
autoStart: false,
|
||||
});
|
||||
expect((post.body as { config: object }).config).not.toHaveProperty('fastPeriod');
|
||||
await flush(() => reply(post, definition));
|
||||
expect(saved).toEqual(definition);
|
||||
expect(requests.some(item => item.path.endsWith('/runs'))).toBe(false);
|
||||
});
|
||||
|
||||
test('reopened catalog settings save exact version parameters without legacy pacing and keep notices outside heading', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
expect(host.querySelector('h1 p')).toBeNull();
|
||||
expect(host.querySelector('h1')?.textContent).not.toContain('save-only');
|
||||
expect(host.querySelector('a[href="/strategies/versions/version-one"]')).not.toBeNull();
|
||||
await flush(() => click('Settings'));
|
||||
await selected();
|
||||
expect(host.querySelector('input[name="speedMultiplier"]')).toBeNull();
|
||||
await flush(() => edit('fastPeriod', '2'));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => click('Save'));
|
||||
const saved = request('/api/v2/backtests/definition', 'PUT');
|
||||
expect(saved.body).toMatchObject({
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
});
|
||||
expect((saved.body as { config: object }).config).not.toHaveProperty('speedMultiplier');
|
||||
expect((saved.body as { config: object }).config).toMatchObject({
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
dataSource: 'auto',
|
||||
});
|
||||
await flush(() =>
|
||||
reply(saved, { ...definition, strategyParameters: { fastPeriod: 2, slowPeriod: 15 } })
|
||||
);
|
||||
await selected();
|
||||
expect(field('fastPeriod').value).toBe('2');
|
||||
await flush(() => click('Runs'));
|
||||
expect(button('New Run').disabled).toBe(true);
|
||||
expect(requests.some(item => item.method === 'POST' && item.path.endsWith('/runs'))).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('catalog authoritative archive/restore resets visible parameters and validation together', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
await selected();
|
||||
await flush(() => edit('fastPeriod', '2'));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(button('Save').disabled).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const staleValidation = request('/api/v2/strategy-versions/version-one/validate', 'POST');
|
||||
await flush(() => click('Archive backtest'));
|
||||
await flush(() => click('Confirm archive'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/archive', 'POST'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
archivedAt: '2026-01-02',
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(field('fastPeriod').disabled).toBe(true);
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
await flush(() => click('Restore backtest'));
|
||||
await flush(() => click('Confirm restore'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/archive', 'POST'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
await flush(() =>
|
||||
reply(staleValidation, {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(field('fastPeriod').disabled).toBe(false);
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/version-one/validate', 'POST').body).toEqual({
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => click('Save'));
|
||||
expect(request('/api/v2/backtests/definition', 'PUT').body).toMatchObject({
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
});
|
||||
|
||||
test('legacy settings retain the existing pacing field and submitted speed', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
strategy: 'moving-average',
|
||||
strategyVersionId: null,
|
||||
strategyParameters: null,
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
const speed = host.querySelector('input[name="speedMultiplier"]')!;
|
||||
expect(speed).not.toBeNull();
|
||||
await flush(() => {
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
speed,
|
||||
'0.2'
|
||||
);
|
||||
speed.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Save'));
|
||||
expect(request('/api/v2/backtests/definition', 'PUT').body).toMatchObject({
|
||||
strategy: 'moving-average',
|
||||
config: { speedMultiplier: 0.2 },
|
||||
});
|
||||
});
|
||||
|
||||
test('retained archived family is readable but cannot validate a new selection; existing saved selection can', async () => {
|
||||
let checked = false;
|
||||
function Selection({ retained = false }: { retained?: boolean }) {
|
||||
const [value, setValue] = useState<CatalogSelection>({
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: {},
|
||||
});
|
||||
return createElement(StrategySelection, {
|
||||
value,
|
||||
onChange: setValue,
|
||||
onValidityChange: valid => {
|
||||
checked = valid;
|
||||
},
|
||||
allowArchivedSelection: retained,
|
||||
});
|
||||
}
|
||||
await mount(createElement(Selection));
|
||||
await selected(true);
|
||||
expect(host.textContent).toContain('archived');
|
||||
expect(field('Immutable strategy version').disabled).toBe(true);
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
expect(checked).toBe(false);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, null, createElement(Selection, { retained: true }))
|
||||
)
|
||||
);
|
||||
// The retained selection stays loaded when its edit policy changes.
|
||||
expect(button('Validate parameters').disabled).toBe(false);
|
||||
});
|
||||
|
||||
test('missing selected version is not cleared; retry preserves exact ID and blocks saving', async () => {
|
||||
let selectedId: string | null | undefined = 'version-one';
|
||||
await mount(
|
||||
createElement(StrategySelection, {
|
||||
value: { strategyVersionId: selectedId },
|
||||
onChange: next => {
|
||||
selectedId = next.strategyVersionId;
|
||||
},
|
||||
onValidityChange: () => {},
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies'), { strategies: [] });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { error: 'Version missing' }, 404);
|
||||
});
|
||||
expect(host.textContent).toContain('selection has been retained');
|
||||
expect(selectedId).toBe('version-one');
|
||||
await flush(() => click('Retry strategy catalog'));
|
||||
expect(request('/api/v2/strategy-versions/version-one')).toBeDefined();
|
||||
});
|
||||
|
||||
test('legacy filtering preserves unsupported saved labels and offers only independently supported choices', async () => {
|
||||
await mount(createElement(LegacyStrategySelect, { value: 'custom', onChange: () => {} }));
|
||||
expect(field('Legacy strategy').value).toBe('custom');
|
||||
expect(host.querySelector('option[value="custom"]')?.hasAttribute('disabled')).toBe(true);
|
||||
expect(host.querySelector('option[value="pairs-trading"]')).toBeNull();
|
||||
expect(host.querySelector('option[value="ml-enhanced"]')).toBeNull();
|
||||
expect(host.querySelector('option[value="moving-average"]')).not.toBeNull();
|
||||
expect(host.querySelector('option[value="momentum"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('catalog execution stays blocked in the hook and controls; accepted run cancellation remains enabled', async () => {
|
||||
function Hook() {
|
||||
latest = useBacktestV2();
|
||||
return null;
|
||||
}
|
||||
await mount(createElement(Hook));
|
||||
await flush(() => {
|
||||
void latest.loadBacktest('definition');
|
||||
});
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), definition);
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => {
|
||||
void latest.createRun(null);
|
||||
});
|
||||
expect(latest.submissionError).toContain('save-only');
|
||||
expect(requests.some(item => item.method === 'POST')).toBe(false);
|
||||
let cancelled = false;
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(RunControlsCompact, {
|
||||
run: {
|
||||
id: 'accepted',
|
||||
backtestId: 'definition',
|
||||
runNumber: 1,
|
||||
status: 'running',
|
||||
speedMultiplier: null,
|
||||
progress: 10,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
},
|
||||
cancelRequested: false,
|
||||
onCancel: () => {
|
||||
cancelled = true;
|
||||
},
|
||||
onRerun: () => {},
|
||||
executionUnavailable: true,
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
expect(button('Cancel run').disabled).toBe(false);
|
||||
await flush(() => click('Cancel run'));
|
||||
expect(cancelled).toBe(true);
|
||||
});
|
||||
});
|
||||
373
test/postgres/catalog-backtest-drafts.test.ts
Normal file
373
test/postgres/catalog-backtest-drafts.test.ts
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
import { createHash, 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 { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { createBacktestRoutes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type BacktestRequest,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('catalog-draft-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const sql = (name: string) =>
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
|
||||
const hash = (text: string) => createHash('sha256').update(text).digest('hex');
|
||||
function pkg(): StrategyVersionPackage {
|
||||
const content = 'throw new Error("CANDIDATE_MUST_NOT_EXECUTE");';
|
||||
const lock = '{"lockfileVersion":1}';
|
||||
return {
|
||||
version: 1,
|
||||
program: {
|
||||
strategyId: 'draft-fixture',
|
||||
strategyVersion: 'v1',
|
||||
apiVersion: 'canonical-ts/v1',
|
||||
checkpointVersion: 'v1',
|
||||
},
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: 'createStrategy',
|
||||
content,
|
||||
sha256: hash(content),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: lock, sha256: hash(lock) },
|
||||
parameterSchema: {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: [],
|
||||
properties: {
|
||||
commission: { type: 'number', minimum: 0, default: 0 },
|
||||
enabled: { type: 'boolean', default: false },
|
||||
budget: { type: 'string', default: '100.25' },
|
||||
lookback: { type: 'integer', minimum: 1, default: 3 },
|
||||
label: { type: 'string', default: '📈' },
|
||||
},
|
||||
},
|
||||
source: { revision: 'a'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
};
|
||||
}
|
||||
const common = {
|
||||
name: 'Catalog draft',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-05T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
config: { commission: 0.001, slippage: 0, dataFrequency: '1d' },
|
||||
};
|
||||
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('Dedicated safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_drafts_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
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',
|
||||
'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',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
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 api = new BacktestServiceV2({ postgres, logger });
|
||||
const catalog = new StrategyCatalogService({ postgres, logger });
|
||||
const family = await catalog.createStrategy({ name: 'Candidate' }, 'operator');
|
||||
const version = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'initial');
|
||||
const second = await catalog.publishVersion(family.id, pkg(), null, 'operator', 'second');
|
||||
const draft = () => ({
|
||||
...common,
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: {},
|
||||
});
|
||||
const app = new Hono()
|
||||
.route('/', createBacktestV2Routes({ postgres, logger }))
|
||||
.route('/', createBacktestRoutes({ postgres, logger }));
|
||||
return { schema, pool, postgres, api, catalog, family, version, second, draft, app };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('saved catalog backtest drafts on PostgreSQL', () => {
|
||||
test('normalizes exact defaults and separates financial settings from arbitrary strategy parameter names', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
expect(saved.strategy).toBe('catalog');
|
||||
expect(saved.strategyVersionId).toBe(f.version.id);
|
||||
expect(saved.strategyParameters).toEqual({
|
||||
commission: 0,
|
||||
enabled: false,
|
||||
budget: '100.25',
|
||||
lookback: 3,
|
||||
label: '📈',
|
||||
});
|
||||
expect(saved.config.commission).toBe(0.001);
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyParameters).toEqual(
|
||||
saved.strategyParameters!
|
||||
);
|
||||
const edited = await f.api.updateBacktest(saved.id, { name: 'Edited' });
|
||||
expect(edited?.strategyVersionId).toBe(f.version.id);
|
||||
expect(edited?.strategyParameters).toEqual(saved.strategyParameters!);
|
||||
const revised = await f.api.updateBacktest(saved.id, {
|
||||
strategyParameters: {
|
||||
commission: 0.04,
|
||||
enabled: false,
|
||||
budget: '0.00',
|
||||
lookback: 1,
|
||||
label: '東京',
|
||||
},
|
||||
});
|
||||
expect(revised?.config.commission).toBe(0.001);
|
||||
expect(revised?.strategyParameters?.budget).toBe('0.00');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('strict save-only input, version integrity and invalid parameters fail atomically', async () => {
|
||||
const f = await fixture();
|
||||
for (const options of [{}, { autoStart: true }]) {
|
||||
await expect(f.api.createBacktest(f.draft(), options)).rejects.toThrow('autoStart:false');
|
||||
}
|
||||
const invalidInputs: BacktestRequest[] = [
|
||||
{ ...f.draft(), strategyVersionId: null },
|
||||
{ ...f.draft(), strategyParameters: null },
|
||||
{ ...f.draft(), config: { ...common.config, lookback: 9 } },
|
||||
{ ...f.draft(), strategyParameters: { unknown: 1 } },
|
||||
{ ...f.draft(), strategyParameters: { lookback: 0 } },
|
||||
{ ...f.draft(), strategyParameters: { enabled: 'false' } },
|
||||
{ ...f.draft(), strategyParameters: { budget: 100.25 } },
|
||||
{ ...f.draft(), strategyParameters: { label: 'bad\u0000text' } },
|
||||
{ ...f.draft(), strategyParameters: { label: '\ud800' } },
|
||||
{ ...f.draft(), strategyParameters: JSON.parse('{"__proto__":1}') },
|
||||
];
|
||||
for (const input of invalidInputs) {
|
||||
await expect(f.api.createBacktest(input, { autoStart: false })).rejects.toThrow();
|
||||
}
|
||||
await expect(
|
||||
f.api.createBacktest({ ...f.draft(), strategyVersionId: randomUUID() }, { autoStart: false })
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
const corrupt = pkg();
|
||||
corrupt.artifact.content += 'changed';
|
||||
const invalidVersionId = randomUUID();
|
||||
await f.pool.query(
|
||||
"INSERT INTO strategy_versions(id,strategy_id,ordinal,envelope,created_by,origin,submission_key,submission_fingerprint) VALUES($1,$2,3,$3,'operator','candidate','imported-corrupt',$4)",
|
||||
[invalidVersionId, f.family.id, JSON.stringify(corrupt), 'f'.repeat(64)]
|
||||
);
|
||||
await expect(
|
||||
f.api.createBacktest(
|
||||
{ ...f.draft(), strategyVersionId: invalidVersionId },
|
||||
{ autoStart: false }
|
||||
)
|
||||
).rejects.toThrow('hash mismatch');
|
||||
expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('partial edits retain selection, explicit changes require parameters, and neither mode silently converts', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id })
|
||||
).rejects.toThrow('explicit strategyParameters');
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { strategyParameters: JSON.parse('{"__proto__":1}') })
|
||||
).rejects.toThrow('Unsupported strategy metadata key');
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyParameters?.lookback).toBe(3);
|
||||
expect(
|
||||
(
|
||||
await f.api.updateBacktest(saved.id, {
|
||||
strategyVersionId: f.second.id,
|
||||
strategyParameters: { lookback: 8 },
|
||||
})
|
||||
)?.strategyParameters?.lookback
|
||||
).toBe(8);
|
||||
for (const update of [
|
||||
{ strategy: 'sma-crossover' },
|
||||
{ strategyVersionId: null },
|
||||
{ strategyParameters: null },
|
||||
{ strategyParameters: { lookback: -1 } },
|
||||
]) {
|
||||
await expect(f.api.updateBacktest(saved.id, update)).rejects.toThrow();
|
||||
}
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.second.id);
|
||||
const legacy = await f.api.createBacktest(
|
||||
{ ...common, strategy: 'sma-crossover' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await expect(f.api.updateBacktest(legacy.id, f.draft())).rejects.toThrow(
|
||||
'Retained strategy versions'
|
||||
);
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE backtests SET strategy='sma-crossover',strategy_version_id=NULL,strategy_parameters=NULL WHERE id=$1",
|
||||
[saved.id]
|
||||
)
|
||||
).rejects.toThrow('separate template');
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"UPDATE backtests SET strategy='catalog',strategy_version_id=$2,strategy_parameters='{}' WHERE id=$1",
|
||||
[legacy.id, f.version.id]
|
||||
)
|
||||
).rejects.toThrow('separate template');
|
||||
});
|
||||
|
||||
test('family archive serializes new selection while existing selected draft remains editable', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.family.id]);
|
||||
const admission = f.api.createBacktest(f.draft(), { autoStart: false }).then(
|
||||
() => null,
|
||||
error => error
|
||||
);
|
||||
let waiting = false;
|
||||
for (let n = 0; n < 100; n++) {
|
||||
if (
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows.length
|
||||
) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [f.family.id]);
|
||||
await blocker.query('COMMIT');
|
||||
blocker.release();
|
||||
expect(await admission).toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { strategyVersionId: f.second.id, strategyParameters: {} })
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(
|
||||
(await f.api.updateBacktest(saved.id, { strategyParameters: { lookback: 4 } }))
|
||||
?.strategyParameters?.lookback
|
||||
).toBe(4);
|
||||
await f.api.archiveBacktest(saved.id, true);
|
||||
await expect(f.api.updateBacktest(saved.id, { name: 'Blocked' })).rejects.toMatchObject({
|
||||
code: 'backtest_archived',
|
||||
});
|
||||
});
|
||||
|
||||
test('all execution paths refuse catalog drafts and independent legacy receipts still replay unchanged', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(f.draft(), { autoStart: false });
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toMatchObject({
|
||||
code: 'catalog_execution_unavailable',
|
||||
});
|
||||
const repository = new PostgresBacktestRunRepository(f.postgres);
|
||||
const legacyConfig = parseBacktestRequest({
|
||||
...common,
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
dataFrequency: '1d',
|
||||
backtestId: saved.id,
|
||||
});
|
||||
await expect(repository.start(legacyConfig)).rejects.toThrow('Catalog strategy execution');
|
||||
await expect(
|
||||
repository.start({ ...legacyConfig, strategyVersionId: f.version.id } as typeof legacyConfig)
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
await expect(
|
||||
f.pool.query(
|
||||
"INSERT INTO runs(backtest_id,run_number,status,request_snapshot) VALUES($1,1,'pending','{}')",
|
||||
[saved.id]
|
||||
)
|
||||
).rejects.toThrow('Catalog strategy execution');
|
||||
await expect(
|
||||
new BacktestService({ postgres: f.postgres, logger }).createBacktest(f.draft())
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
const legacy = await f.api.createBacktest(
|
||||
{ ...common, strategy: 'sma-crossover' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const receipt = { principal: 'operator' as const, key: 'legacy' };
|
||||
const run = await f.api.createRun({ backtestId: legacy.id }, receipt);
|
||||
const before = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id]))
|
||||
.rows[0].request_snapshot;
|
||||
await f.api.updateBacktest(legacy.id, { name: 'Later edit' });
|
||||
await f.api.archiveBacktest(legacy.id, true);
|
||||
expect((await f.api.createRun({ backtestId: legacy.id }, receipt)).id).toBe(run.id);
|
||||
expect(
|
||||
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [run.id])).rows[0]
|
||||
.request_snapshot
|
||||
).toEqual(before);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('HTTP persisted selection reopens, malformed drafts reject, and v1 cannot save or run them', async () => {
|
||||
const f = await fixture();
|
||||
const submit = (path: string, input: unknown) =>
|
||||
f.app.request(path, { method: 'POST', body: JSON.stringify(input) });
|
||||
for (const input of [
|
||||
f.draft(),
|
||||
{ ...f.draft(), autoStart: true },
|
||||
{ ...f.draft(), autoStart: false, extra: true },
|
||||
]) {
|
||||
expect((await submit('/api/v2/backtests', input)).status).toBe(400);
|
||||
}
|
||||
expect((await submit('/api/backtests', f.draft())).status).toBe(400);
|
||||
expect((await f.pool.query('SELECT * FROM backtests')).rows).toHaveLength(0);
|
||||
const created = await submit('/api/v2/backtests', { ...f.draft(), autoStart: false });
|
||||
expect(created.status).toBe(201);
|
||||
const saved = await created.json();
|
||||
expect(await (await f.app.request(`/api/v2/backtests/${saved.id}`)).json()).toMatchObject({
|
||||
strategyVersionId: f.version.id,
|
||||
strategyParameters: { enabled: false, budget: '100.25' },
|
||||
});
|
||||
const denied = await submit(`/api/v2/backtests/${saved.id}/runs`, {});
|
||||
expect(denied.status).toBe(409);
|
||||
expect(await denied.json()).toMatchObject({ code: 'catalog_execution_unavailable' });
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
await f.pool.query(sql('18-backtest-strategy-versions.sql'));
|
||||
expect((await f.api.getBacktest(saved.id))?.strategyVersionId).toBe(f.version.id);
|
||||
const fks = await f.pool.query(
|
||||
"SELECT confdeltype FROM pg_constraint WHERE conrelid='backtests'::regclass AND conname='backtests_strategy_version_id_fkey'"
|
||||
);
|
||||
expect(fks.rows[0].confdeltype).toBe('r');
|
||||
await expect(
|
||||
f.pool.query('DELETE FROM strategy_versions WHERE id=$1', [f.version.id])
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -69,7 +69,9 @@ async function fixture() {
|
|||
'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',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -80,7 +80,9 @@ async function fixture() {
|
|||
'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',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
@ -127,6 +129,16 @@ async function fixture() {
|
|||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
// A response DTO includes nullable catalog markers; legacy input deliberately omits them.
|
||||
const definitionInput = {
|
||||
name: definition.name,
|
||||
strategy: definition.strategy,
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate.toISOString(),
|
||||
endDate: definition.endDate.toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: definition.config,
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
|
|
@ -197,6 +209,7 @@ async function fixture() {
|
|||
postgres,
|
||||
api,
|
||||
definition,
|
||||
definitionInput,
|
||||
repository,
|
||||
runner,
|
||||
engine,
|
||||
|
|
@ -243,7 +256,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const second = await f.api.createBacktest(
|
||||
{
|
||||
...f.definition,
|
||||
...f.definitionInput,
|
||||
startDate: f.definition.startDate.toISOString(),
|
||||
endDate: f.definition.endDate.toISOString(),
|
||||
name: 'Second',
|
||||
|
|
@ -339,7 +352,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const body = { ...f.definition, autoStart: false };
|
||||
const body = { ...f.definitionInput, autoStart: false };
|
||||
expect(
|
||||
(
|
||||
await app.request('/api/v2/backtests', {
|
||||
|
|
@ -585,7 +598,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const f = await fixture();
|
||||
const runId = randomUUID();
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...f.definition, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } },
|
||||
{ runId, backtestId: f.definition.id }
|
||||
);
|
||||
// Imported history can reference unavailable storage; retain its request and report the loss.
|
||||
|
|
@ -637,7 +650,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
const snapshot = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0].request_snapshot;
|
||||
const expected = backtestRequestFromDefinition(f.definition, {
|
||||
const expected = backtestRequestFromDefinition(f.definitionInput, {
|
||||
runId: run.id,
|
||||
backtestId: f.definition.id,
|
||||
speedMultiplier: 7,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ const migrations = [
|
|||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@ const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|||
const cleanup: (() => Promise<void>)[] = [];
|
||||
const sql = (name: string) =>
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8');
|
||||
const retention = sql('17-research-retention.sql');
|
||||
const retention =
|
||||
sql('17-research-retention.sql') + '\n' + sql('18-backtest-strategy-versions.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
@ -34,7 +35,7 @@ afterEach(async () => {
|
|||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(install = true) {
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
|
|
@ -58,14 +59,11 @@ async function fixture(install = true) {
|
|||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
// The pre17 setup mode is only for constructing historical/corrupt imported rows.
|
||||
await pool.query('ALTER TABLE backtests ADD COLUMN archived_at timestamptz');
|
||||
if (install) {
|
||||
await pool.query(retention);
|
||||
}
|
||||
await pool.query(retention);
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
|
|
@ -391,18 +389,20 @@ describe.skipIf(!url)('research evidence retention on real PostgreSQL', () => {
|
|||
});
|
||||
|
||||
test('preexisting corrupted datasets remain immutable and fail checksum verification on retrieval', async () => {
|
||||
const f = await fixture(false);
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const claim = await f.repository.start(await f.snapshot(run.id));
|
||||
const dataset = await f.repository.freezeDataset(
|
||||
const dataset = await f.dataset(run.id);
|
||||
const corrupt = structuredClone(dataset);
|
||||
corrupt.bars[0]!.volume = 0;
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [
|
||||
dataset.manifest.hash,
|
||||
corrupt,
|
||||
]);
|
||||
await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [
|
||||
run.id,
|
||||
claim.attemptId,
|
||||
await f.dataset(run.id)
|
||||
);
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_datasets SET payload=jsonb_set(payload,'{bars,0,volume}','0') WHERE hash=$1",
|
||||
[dataset.manifest.hash]
|
||||
);
|
||||
dataset.manifest.hash,
|
||||
]);
|
||||
await f.pool.query(retention);
|
||||
await expect(f.repository.loadDataset(run.id, claim.attemptId)).rejects.toThrow('hash/content');
|
||||
await expect(
|
||||
|
|
|
|||
|
|
@ -65,7 +65,9 @@ async function fixture() {
|
|||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue