feat(research): select and reuse frozen datasets in workbench
This commit is contained in:
parent
6a67ae8683
commit
b106c1ca85
29 changed files with 2295 additions and 426 deletions
|
|
@ -103,6 +103,26 @@ const storage: Pick<StorageService, 'getHistoricalBars'> = {
|
|||
},
|
||||
};
|
||||
|
||||
/** Retain a real hash-validated v1 fixture through the same preparation function as a run. */
|
||||
export async function retainDataset(pool: Pool, overrides: Partial<BacktestConfig> = {}) {
|
||||
const dataset = await loadDataset(storage, {
|
||||
mode: 'backtest',
|
||||
strategy: 'moving-average',
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
dataFrequency: '1d',
|
||||
initialCapital: 100000,
|
||||
speed: 'max',
|
||||
...overrides,
|
||||
});
|
||||
await pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)', [
|
||||
dataset.manifest.hash,
|
||||
JSON.stringify(dataset),
|
||||
]);
|
||||
return dataset;
|
||||
}
|
||||
|
||||
/** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */
|
||||
class FixtureEngine extends EventEmitter {
|
||||
completion = gate();
|
||||
|
|
@ -377,6 +397,7 @@ export async function fixture(native = false) {
|
|||
if (
|
||||
(!pathname.startsWith('/api/v2/backtests') &&
|
||||
!pathname.startsWith('/api/v2/runs') &&
|
||||
!pathname.startsWith('/api/v2/datasets') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
/\/(pause|resume|speed)$/.test(pathname)
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,15 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { expect, test } from 'bun:test';
|
||||
import type { Request } from 'playwright';
|
||||
import { createInBrowser, fixture, gate, submitInBrowser, until, visible } from './fixture';
|
||||
import {
|
||||
createInBrowser,
|
||||
fixture,
|
||||
gate,
|
||||
retainDataset,
|
||||
submitInBrowser,
|
||||
until,
|
||||
visible,
|
||||
} from './fixture';
|
||||
|
||||
// Serial by design: the production WebSocket projection has a process-local handler.
|
||||
test('browser_saved_run_lifecycle', async () => {
|
||||
|
|
@ -24,6 +32,7 @@ test('browser_saved_run_lifecycle', async () => {
|
|||
expect(response.headers().location).toBe(`/api/v2/runs/${run.id}`);
|
||||
expect(response.request().headers()['idempotency-key']).toBeTruthy();
|
||||
await visible(f.page, 'Pending');
|
||||
await visible(f.page, /Source request \(auto\) — unpinned/);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
|
||||
expect(await f.page.getByRole('button', { name: /pause|resume/i }).count()).toBe(0);
|
||||
|
|
@ -31,6 +40,9 @@ test('browser_saved_run_lifecycle', async () => {
|
|||
f.dispatcher.start();
|
||||
await visible(f.page, 'Running');
|
||||
await visible(f.page, '25%');
|
||||
expect(
|
||||
await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent()
|
||||
).toContain('Pinned dataset hash');
|
||||
await until(
|
||||
() =>
|
||||
f.frames.some(
|
||||
|
|
@ -278,3 +290,117 @@ test('native_smoke', async () => {
|
|||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_frozen_dataset_native_run_and_reopen', async () => {
|
||||
const f = await fixture(true);
|
||||
try {
|
||||
const dataset = await retainDataset(f.pool);
|
||||
const hash = dataset.manifest.hash;
|
||||
await f.login();
|
||||
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Frozen dataset browser run');
|
||||
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
|
||||
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
|
||||
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).inputValue()).toBe(
|
||||
'2024-01-01'
|
||||
);
|
||||
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).isDisabled()).toBe(true);
|
||||
await f.page.getByRole('button', { name: 'Save and run', exact: true }).click();
|
||||
await f.page.waitForURL(/\/backtests\/[^/]+\/run\/[^/]+$/);
|
||||
const runId = f.page.url().split('/').at(-1)!;
|
||||
await visible(f.page, 'Pending');
|
||||
const pending = await f.request(`/api/v2/runs/${runId}`);
|
||||
expect(pending.dataset).toMatchObject({
|
||||
requestedHash: hash,
|
||||
pinnedHash: null,
|
||||
state: 'requested',
|
||||
});
|
||||
expect(
|
||||
await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent()
|
||||
).toContain(hash);
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, 'Completed');
|
||||
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
||||
expect(result.config.dataset.hash).toBe(hash);
|
||||
expect(result.engine).toBe('native');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1');
|
||||
await visible(f.page, 'Research only · Unverified economics');
|
||||
const runDataset = f.page.getByRole('region', { name: 'Run dataset', exact: true });
|
||||
expect(await runDataset.textContent()).toContain('Pinned dataset hash');
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Completed');
|
||||
expect(await runDataset.textContent()).toContain(hash);
|
||||
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
||||
await visible(f.page, result.trades[0].side.toUpperCase());
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('browser_intraday_dataset_exact_settings_and_incompatible_submission', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
const startDate = '2024-01-02T13:30:00.123Z';
|
||||
const endDate = '2024-01-02T15:30:00.456Z';
|
||||
const dataset = await retainDataset(f.pool, { startDate, endDate, dataFrequency: '1m' });
|
||||
const hash = dataset.manifest.hash;
|
||||
await f.login();
|
||||
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await f.page.getByPlaceholder('My Strategy Backtest').fill('Exact intraday frozen settings');
|
||||
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
|
||||
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
await f.page.waitForURL(/\/backtests\/[^/]+$/);
|
||||
const backtestId = f.page.url().split('/').at(-1)!;
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByLabel('Start instant (UTC)', { exact: true }).inputValue()).toBe(
|
||||
startDate
|
||||
);
|
||||
expect(await f.page.getByLabel('End instant (UTC)', { exact: true }).inputValue()).toBe(
|
||||
endDate
|
||||
);
|
||||
const saved = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' &&
|
||||
response.url().endsWith(`/api/v2/backtests/${backtestId}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
expect((await saved).status()).toBe(200);
|
||||
const stored = (
|
||||
await f.pool.query('SELECT start_date,end_date,config FROM backtests WHERE id=$1', [
|
||||
backtestId,
|
||||
])
|
||||
).rows[0];
|
||||
expect(stored.start_date.toISOString()).toBe(startDate);
|
||||
expect(stored.end_date.toISOString()).toBe(endDate);
|
||||
expect(stored.config.datasetHash).toBe(hash);
|
||||
expect(stored.config.dataFrequency).toBe('1m');
|
||||
await f.page.reload();
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByLabel('Start instant (UTC)', { exact: true }).inputValue()).toBe(
|
||||
startDate
|
||||
);
|
||||
// Simulate a template changed outside this browser; API must reject before durable dispatch.
|
||||
await f.pool.query(
|
||||
"UPDATE backtests SET config=jsonb_set(config,'{dataFrequency}','\"5m\"') WHERE id=$1",
|
||||
[backtestId]
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'New Run', exact: true }).click();
|
||||
const rejected = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/api/v2/backtests/${backtestId}/runs`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Run current settings', exact: true }).click();
|
||||
expect((await rejected).status()).toBe(400);
|
||||
await visible(f.page, /Frozen dataset does not match/);
|
||||
expect((await f.pool.query('SELECT count(*) FROM runs')).rows[0].count).toBe('0');
|
||||
expect((await f.pool.query('SELECT count(*) FROM backtest_dispatch')).rows[0].count).toBe('0');
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
await f.close();
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -63,6 +63,23 @@ describe('shared backtest request contract', () => {
|
|||
expect(runnerParser).toBe(parseBacktestRequest);
|
||||
});
|
||||
|
||||
test('historical provider selection is retained as execution configuration', () => {
|
||||
for (const dataSource of ['auto', 'questdb', 'eod'] as const) {
|
||||
const snapshot = backtestRequestFromDefinition({
|
||||
...definition,
|
||||
config: { ...definition.config, dataSource },
|
||||
});
|
||||
expect(snapshot.dataSource).toBe(dataSource);
|
||||
expect(parseBacktestRequest(snapshot).dataSource).toBe(dataSource);
|
||||
expect(normalizeBacktestStrategyConfig(snapshot.config ?? {}).parameters).toEqual(
|
||||
definition.config
|
||||
);
|
||||
}
|
||||
expect(() =>
|
||||
backtestRequestFromDefinition({ ...definition, config: { dataSource: 'unknown' } })
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
test('definition snapshots and direct requests share defaults without mutating their inputs', () => {
|
||||
const input = structuredClone(request);
|
||||
const parsed = parseBacktestRequest(input);
|
||||
|
|
|
|||
85
test/integration/dataset-catalog.test.ts
Normal file
85
test/integration/dataset-catalog.test.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { datasetSelectionForRun } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const hash = 'a'.repeat(64);
|
||||
const logger = getLogger('dataset-catalog-http-test');
|
||||
test('dataset endpoints return explicit empty/missing states and reject invalid query inputs before database reads', async () => {
|
||||
const calls: { text: string; values?: unknown[] }[] = [];
|
||||
const postgres = {
|
||||
async query(text: string, values?: unknown[]) {
|
||||
calls.push({ text, values });
|
||||
return { rows: [] };
|
||||
},
|
||||
} as unknown as PostgresClient;
|
||||
const app = new Hono().route('/', createDatasetRoutes({ postgres, logger }));
|
||||
const list = await app.request('/api/v2/datasets');
|
||||
expect(list.status).toBe(200);
|
||||
expect(await list.json()).toEqual({ datasets: [] });
|
||||
expect(calls[0]!.values).toEqual([50, 0]);
|
||||
expect((await app.request(`/api/v2/datasets/${hash}`)).status).toBe(404);
|
||||
const count = calls.length;
|
||||
for (const path of [
|
||||
'/api/v2/datasets/bad',
|
||||
'/api/v2/datasets?limit=1x',
|
||||
'/api/v2/datasets?limit=0',
|
||||
'/api/v2/datasets?offset=-1',
|
||||
'/api/v2/datasets?offset=1.5',
|
||||
]) {
|
||||
expect((await app.request(path)).status).toBe(400);
|
||||
}
|
||||
expect(calls).toHaveLength(count);
|
||||
});
|
||||
|
||||
test('catalog database errors are failures, never an empty success or leaked internal diagnostic', async () => {
|
||||
const postgres = {
|
||||
async query() {
|
||||
throw new Error('private database detail');
|
||||
},
|
||||
} as unknown as PostgresClient;
|
||||
const app = new Hono().route('/', createDatasetRoutes({ postgres, logger }));
|
||||
for (const path of ['/api/v2/datasets', `/api/v2/datasets/${hash}`]) {
|
||||
const response = await app.request(path);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.text()).not.toContain('private database detail');
|
||||
}
|
||||
});
|
||||
|
||||
test('run dataset provenance distinguishes accepted request, active preparation, terminal failure and actual binding', () => {
|
||||
const snapshot = parseBacktestRequest({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-02T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
dataFrequency: '1d',
|
||||
datasetHash: hash,
|
||||
});
|
||||
const row = {
|
||||
request_snapshot: snapshot,
|
||||
dataset_hash: null,
|
||||
status: 'pending',
|
||||
config: { dataSource: 'questdb', datasetHash: 'b'.repeat(64) },
|
||||
};
|
||||
expect(datasetSelectionForRun(row)).toEqual({
|
||||
requestedHash: hash,
|
||||
pinnedHash: null,
|
||||
source: 'auto',
|
||||
state: 'requested',
|
||||
});
|
||||
for (const status of ['running', 'paused']) {
|
||||
expect(datasetSelectionForRun({ ...row, status }).state).toBe('preparing');
|
||||
}
|
||||
for (const status of ['completed', 'failed', 'cancelled']) {
|
||||
expect(datasetSelectionForRun({ ...row, status }).state).toBe('unavailable');
|
||||
expect(datasetSelectionForRun({ ...row, status, dataset_hash: hash }).state).toBe('pinned');
|
||||
}
|
||||
expect(datasetSelectionForRun({ ...row, request_snapshot: null }).state).toBe('unknown');
|
||||
expect(datasetSelectionForRun({ ...row, request_snapshot: {} }).state).toBe('unknown');
|
||||
});
|
||||
373
test/integration/dataset-workbench.test.ts
Normal file
373
test/integration/dataset-workbench.test.ts
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, useState } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import type { HistoricalDatasetCatalogEntry } from '@stock-bot/types';
|
||||
import { RunDataset } from '../../apps/stock/web-app/src/features/backtest/components/RunDataset';
|
||||
import {
|
||||
historicalDateInput,
|
||||
historicalSelectionError,
|
||||
retainedDatasetSelection,
|
||||
type HistoricalSelection,
|
||||
} from '../../apps/stock/web-app/src/features/backtest/services/historical-selection';
|
||||
|
||||
const hash = 'a'.repeat(64);
|
||||
const retained: HistoricalDatasetCatalogEntry = {
|
||||
hash,
|
||||
version: 1,
|
||||
createdAt: '2024-01-03T00:00:00.000Z',
|
||||
status: 'available',
|
||||
reason: null,
|
||||
coverage: 'unknown',
|
||||
integrity: 'not-verified',
|
||||
manifest: {
|
||||
version: 1,
|
||||
hash,
|
||||
instruments: [
|
||||
{ id: 'AAPL.US', symbol: 'AAPL', exchange: 'US' },
|
||||
{ id: 'MSFT.US', symbol: 'MSFT', exchange: 'US' },
|
||||
],
|
||||
startDate: '2024-01-02T14:30:00.123Z',
|
||||
endDate: '2024-01-02T20:59:59.999Z',
|
||||
interval: '1m',
|
||||
policy: { adjustment: 'provider-adjusted', timestamp: 'utc-instant' },
|
||||
volumePolicy: 'reported',
|
||||
qualityPolicy: 'reject-invalid-no-interpolation',
|
||||
sources: [
|
||||
{ instrumentId: 'AAPL.US', provider: 'eod', revision: 'fixture-a' },
|
||||
{ instrumentId: 'MSFT.US', provider: 'questdb', revision: 'fixture-b' },
|
||||
],
|
||||
barCount: 2,
|
||||
},
|
||||
};
|
||||
|
||||
describe('dataset workbench selection', () => {
|
||||
test('select_hash_compatibility adopts exact manifest settings and UTC milliseconds', () => {
|
||||
const selected = retainedDatasetSelection(retained);
|
||||
expect(selected).toEqual({
|
||||
symbols: ['AAPL.US', 'MSFT.US'],
|
||||
startDate: '2024-01-02T14:30:00.123Z',
|
||||
endDate: '2024-01-02T20:59:59.999Z',
|
||||
dataFrequency: '1m',
|
||||
dataSource: 'auto',
|
||||
priceAdjustment: 'provider-adjusted',
|
||||
datasetHash: hash,
|
||||
});
|
||||
expect(historicalSelectionError(selected, retained)).toBeNull();
|
||||
expect(historicalDateInput(selected.startDate, '1m')).toBe(selected.startDate);
|
||||
expect(historicalDateInput('2024-01-02T00:00:00.000Z', '1d')).toBe('2024-01-02');
|
||||
});
|
||||
|
||||
test('equivalent explicit offsets and reordered instrument sets preserve exact identity', () => {
|
||||
const selected = retainedDatasetSelection(retained);
|
||||
expect(
|
||||
historicalSelectionError(
|
||||
{
|
||||
...selected,
|
||||
symbols: [...selected.symbols].reverse(),
|
||||
startDate: '2024-01-02T09:30:00.123-05:00',
|
||||
},
|
||||
retained
|
||||
)
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test('subsets, cropped bounds, different policies, intervals and explicit providers cannot reuse a hash', () => {
|
||||
const selected = retainedDatasetSelection(retained);
|
||||
for (const change of [
|
||||
{ symbols: ['AAPL.US'] },
|
||||
{ startDate: '2024-01-02T14:30:00.124Z' },
|
||||
{ endDate: '2024-01-02T20:59:59.998Z' },
|
||||
{ priceAdjustment: 'raw' as const },
|
||||
{ dataFrequency: '5m' as const },
|
||||
{ dataSource: 'eod' as const },
|
||||
]) {
|
||||
expect(historicalSelectionError({ ...selected, ...change }, retained)).toContain(
|
||||
'do not match'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('unresolved, missing, unsupported and invalid retained selections remain blocked', () => {
|
||||
const selected = retainedDatasetSelection(retained);
|
||||
expect(historicalSelectionError(selected)).toContain('wait for its metadata');
|
||||
expect(historicalSelectionError(selected, { ...retained, hash: 'b'.repeat(64) })).toContain(
|
||||
'wait for its metadata'
|
||||
);
|
||||
expect(
|
||||
historicalSelectionError(selected, {
|
||||
...retained,
|
||||
status: 'invalid',
|
||||
reason: 'Invalid metadata',
|
||||
})
|
||||
).toBe('Invalid metadata');
|
||||
expect(
|
||||
historicalSelectionError(selected, {
|
||||
...retained,
|
||||
status: 'unsupported',
|
||||
version: 2,
|
||||
manifest: null,
|
||||
reason: 'Version 2 is unsupported',
|
||||
})
|
||||
).toBe('Version 2 is unsupported');
|
||||
expect(selected.datasetHash).toBe(hash);
|
||||
});
|
||||
|
||||
test('source requests need no catalog and retain the selected source and exact range', () => {
|
||||
const selected = {
|
||||
...retainedDatasetSelection(retained),
|
||||
datasetHash: undefined,
|
||||
dataSource: 'questdb' as const,
|
||||
};
|
||||
expect(historicalSelectionError(selected)).toBeNull();
|
||||
expect(selected.startDate).toBe(retained.manifest!.startDate);
|
||||
expect(historicalSelectionError({ ...selected, symbols: [] })).toContain('one or more');
|
||||
expect(historicalSelectionError({ ...selected, startDate: '2024-01-02T14:30:00' })).toContain(
|
||||
'explicit UTC offset'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('historical picker interactions', () => {
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const globals = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originalGlobals = new Map(
|
||||
globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
|
||||
);
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let HistoricalDataSelection: typeof import('../../apps/stock/web-app/src/features/backtest/components/HistoricalDataSelection').HistoricalDataSelection;
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
let current: HistoricalSelection;
|
||||
let valid = false;
|
||||
type BrowserResponse = Awaited<ReturnType<typeof browser.fetch>>;
|
||||
const requests: { path: string; done: boolean; reply: (response: BrowserResponse) => void }[] =
|
||||
[];
|
||||
|
||||
const flush = async (action: () => void) => {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
};
|
||||
const respond = async (path: string, body: object, status = 200) => {
|
||||
const request = requests.find(item => item.path === path && !item.done);
|
||||
if (!request) {
|
||||
throw new Error(`No pending request for ${path}`);
|
||||
}
|
||||
await flush(() => {
|
||||
request.done = true;
|
||||
request.reply(browser.Response.json(body, { status }));
|
||||
});
|
||||
};
|
||||
const select = async (label: string, value: string) => {
|
||||
const element = host.querySelector(`select[aria-label="${label}"]`) as HTMLSelectElement;
|
||||
await flush(() => {
|
||||
element.value = value;
|
||||
element.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
};
|
||||
function Picker({ initial }: { initial: HistoricalSelection }) {
|
||||
const [selection, setSelection] = useState(initial);
|
||||
current = selection;
|
||||
return createElement(HistoricalDataSelection, {
|
||||
value: selection,
|
||||
onChange: setSelection,
|
||||
onValidityChange: value => {
|
||||
valid = value;
|
||||
},
|
||||
});
|
||||
}
|
||||
async function mount(initial: HistoricalSelection) {
|
||||
await flush(() => root.render(createElement(Picker, { initial })));
|
||||
}
|
||||
|
||||
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'));
|
||||
({ HistoricalDataSelection } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/HistoricalDataSelection'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
valid = false;
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
root = createRoot(host);
|
||||
browser.fetch = input =>
|
||||
new Promise<BrowserResponse>(reply => {
|
||||
const url = new URL(String(input));
|
||||
requests.push({ path: `${url.pathname}${url.search}`, done: false, reply });
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
await flush(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
afterAll(() => {
|
||||
for (const key of globals) {
|
||||
const original = originalGlobals.get(key);
|
||||
if (original) {
|
||||
Object.defineProperty(globalThis, key, original);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
void browser.happyDOM.abort();
|
||||
});
|
||||
|
||||
test('choosing a snapshot applies its exact settings and locks data fields', async () => {
|
||||
await mount({
|
||||
...retainedDatasetSelection(retained),
|
||||
datasetHash: undefined,
|
||||
dataSource: 'eod',
|
||||
});
|
||||
await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [retained] });
|
||||
await select('Historical data input', 'frozen');
|
||||
expect(valid).toBe(false);
|
||||
await select('Frozen dataset', hash);
|
||||
expect(valid).toBe(true);
|
||||
expect(current).toEqual(retainedDatasetSelection(retained));
|
||||
expect(host.querySelector('fieldset')?.disabled).toBe(true);
|
||||
expect(host.textContent).toContain('Coverage: unknown');
|
||||
expect(host.textContent).toContain('not verified by this catalog');
|
||||
await select('Historical data input', 'source');
|
||||
expect(current.datasetHash).toBeUndefined();
|
||||
expect(host.querySelector('fieldset')?.disabled).toBe(false);
|
||||
expect(valid).toBe(true);
|
||||
});
|
||||
|
||||
test('a saved selection outside the catalog page loads by hash and remains blocked until resolved', async () => {
|
||||
await mount(retainedDatasetSelection(retained));
|
||||
expect(valid).toBe(false);
|
||||
await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [] });
|
||||
// Replacing the catalog aborts/restarts any earlier detail lookup. A stale
|
||||
// reply must not make the selected dataset eligible.
|
||||
await respond(`/api/v2/datasets/${hash}`, { dataset: retained });
|
||||
expect(valid).toBe(false);
|
||||
await respond(`/api/v2/datasets/${hash}`, { dataset: retained });
|
||||
expect(valid).toBe(true);
|
||||
expect(current.datasetHash).toBe(hash);
|
||||
expect(host.querySelector('select[aria-label="Frozen dataset"]')?.textContent).toContain(hash);
|
||||
});
|
||||
|
||||
test('missing selected metadata never clears the hash and a successful retry restores eligibility', async () => {
|
||||
await mount(retainedDatasetSelection(retained));
|
||||
await respond(`/api/v2/datasets/${hash}`, { error: 'Frozen dataset not found' }, 404);
|
||||
expect(valid).toBe(false);
|
||||
expect(current.datasetHash).toBe(hash);
|
||||
expect(host.textContent).toContain('Frozen dataset not found');
|
||||
await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [] });
|
||||
await respond(`/api/v2/datasets/${hash}`, { error: 'Frozen dataset not found' }, 404);
|
||||
const retry = [...host.querySelectorAll('button')].find(
|
||||
button => button.textContent === 'Retry datasets'
|
||||
)!;
|
||||
await flush(() => retry.click());
|
||||
await respond(`/api/v2/datasets/${hash}`, { dataset: retained });
|
||||
expect(valid).toBe(true);
|
||||
expect(current.datasetHash).toBe(hash);
|
||||
});
|
||||
|
||||
test('catalog failure and late lookup failure cannot prevent a source request', async () => {
|
||||
await mount(retainedDatasetSelection(retained));
|
||||
await select('Historical data input', 'source');
|
||||
await respond('/api/v2/datasets?limit=50&offset=0', { error: 'Catalog unavailable' }, 503);
|
||||
await respond(`/api/v2/datasets/${hash}`, { error: 'Late missing dataset' }, 404);
|
||||
expect(valid).toBe(true);
|
||||
expect(current.datasetHash).toBeUndefined();
|
||||
expect(host.textContent).not.toContain('Late missing dataset');
|
||||
await select('Historical source', 'questdb');
|
||||
expect(current.dataSource).toBe('questdb');
|
||||
expect(valid).toBe(true);
|
||||
});
|
||||
|
||||
test('unsupported catalog versions are visible but not selectable', async () => {
|
||||
await mount({ ...retainedDatasetSelection(retained), datasetHash: '' });
|
||||
const unsupported = {
|
||||
...retained,
|
||||
hash: 'b'.repeat(64),
|
||||
status: 'unsupported',
|
||||
version: 2,
|
||||
manifest: null,
|
||||
reason: 'Version 2 needs a canonical run',
|
||||
};
|
||||
await respond('/api/v2/datasets?limit=50&offset=0', { datasets: [unsupported] });
|
||||
const option = host.querySelector(`option[value="${unsupported.hash}"]`) as HTMLOptionElement;
|
||||
expect(option.disabled).toBe(true);
|
||||
expect(option.textContent).toContain('Version 2 needs a canonical run');
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('persisted run dataset presentation', () => {
|
||||
test('pending source requests are unpinned and awaiting asynchronous preparation', () => {
|
||||
for (const source of ['eod', 'auto'] as const) {
|
||||
const requested = renderToStaticMarkup(
|
||||
createElement(RunDataset, {
|
||||
dataset: { requestedHash: null, pinnedHash: null, source, state: 'requested' },
|
||||
})
|
||||
);
|
||||
expect(requested).toContain(`Source request (${source})`);
|
||||
expect(requested).toContain('unpinned');
|
||||
expect(requested).toContain('will be prepared asynchronously');
|
||||
expect(requested).not.toContain('is preparing');
|
||||
expect(requested).not.toContain('provenance is unavailable');
|
||||
expect(requested).not.toContain('Pinned dataset hash');
|
||||
}
|
||||
});
|
||||
|
||||
test('source_request_freeze_status differentiates preparation from a bound hash', () => {
|
||||
const preparing = renderToStaticMarkup(
|
||||
createElement(RunDataset, {
|
||||
dataset: {
|
||||
requestedHash: null,
|
||||
pinnedHash: null,
|
||||
source: 'questdb',
|
||||
state: 'preparing',
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(preparing).toContain('unpinned');
|
||||
expect(preparing).toContain('questdb');
|
||||
expect(preparing).not.toContain('Pinned dataset hash');
|
||||
const pinned = renderToStaticMarkup(
|
||||
createElement(RunDataset, {
|
||||
dataset: {
|
||||
requestedHash: null,
|
||||
pinnedHash: hash,
|
||||
source: 'questdb',
|
||||
state: 'pinned',
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(pinned).toContain(`Pinned dataset hash: <code>${hash}</code>`);
|
||||
expect(pinned).not.toContain('succeeded');
|
||||
});
|
||||
|
||||
test('requested, failed preparation and legacy unknown provenance are never presented as pinned', () => {
|
||||
for (const state of ['requested', 'unavailable'] as const) {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(RunDataset, {
|
||||
dataset: {
|
||||
requestedHash: hash,
|
||||
pinnedHash: null,
|
||||
source: 'auto',
|
||||
state,
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(html).toContain('Requested frozen dataset hash');
|
||||
expect(html).not.toContain('Pinned dataset hash');
|
||||
expect(html).toContain(state === 'unavailable' ? 'unavailable' : 'Waiting');
|
||||
}
|
||||
expect(renderToStaticMarkup(createElement(RunDataset))).toContain('provenance is unavailable');
|
||||
});
|
||||
});
|
||||
|
|
@ -40,8 +40,11 @@ function memoryStore() {
|
|||
const index = documents.findIndex(
|
||||
old => old.date === row.date && old.eodSearchCode === row.eodSearchCode
|
||||
);
|
||||
if (index >= 0) documents[index] = row;
|
||||
else documents.push(row);
|
||||
if (index >= 0) {
|
||||
documents[index] = row;
|
||||
} else {
|
||||
documents.push(row);
|
||||
}
|
||||
}
|
||||
return {
|
||||
insertedCount: rows.length,
|
||||
|
|
@ -175,6 +178,30 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
expect(a.manifest.hash).not.toBe(b.manifest.hash);
|
||||
});
|
||||
|
||||
test('explicit source requests reach storage and cannot silently reuse another provider', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const providers: unknown[] = [];
|
||||
const selected = await loadDataset(
|
||||
{
|
||||
getHistoricalBars: (...args: Parameters<StorageService['getHistoricalBars']>) => {
|
||||
providers.push(args[6]);
|
||||
return storage.getHistoricalBars(...args);
|
||||
},
|
||||
},
|
||||
{ ...datasetConfig(), dataSource: 'eod' }
|
||||
);
|
||||
expect(providers).toEqual(['eod']);
|
||||
expect(selected.manifest.sources.map(source => source.provider)).toEqual(['eod']);
|
||||
expect(() => validateDataset(selected, { ...datasetConfig(), dataSource: 'questdb' })).toThrow(
|
||||
'does not match'
|
||||
);
|
||||
await expect(
|
||||
loadDataset(storage, { ...datasetConfig(), dataSource: 'questdb' })
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('missing provider factors cannot silently turn adjusted requests into raw data', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, [fixture[0]!]);
|
||||
|
|
|
|||
346
test/postgres/dataset-catalog.test.ts
Normal file
346
test/postgres/dataset-catalog.test.ts
Normal file
|
|
@ -0,0 +1,346 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type BacktestRequest,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { DatasetCatalogService } from '../../apps/stock/web-api/src/services/dataset-catalog.service';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('dataset-catalog-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
const hash = '1'.repeat(64);
|
||||
const manifest = (key = hash): HistoricalDatasetManifest => ({
|
||||
version: 1,
|
||||
hash: key,
|
||||
instruments: [{ id: 'FIXTURE.TEST', symbol: 'FIXTURE', exchange: 'TEST' }],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-01-03T00:00:00.000Z',
|
||||
interval: '1d',
|
||||
policy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
volumePolicy: 'reported',
|
||||
qualityPolicy: 'reject-invalid-no-interpolation',
|
||||
sources: [{ instrumentId: 'FIXTURE.TEST', provider: 'eod', revision: 'fixture-v1' }],
|
||||
barCount: 1,
|
||||
});
|
||||
const request = (): BacktestRequest => ({
|
||||
name: 'Dataset choice',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
startDate: manifest().startDate,
|
||||
endDate: manifest().endDate,
|
||||
initialCapital: 1000,
|
||||
config: { fastPeriod: 2, slowPeriod: 3, datasetHash: hash, dataFrequency: '1d' },
|
||||
});
|
||||
async function fixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_' + 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',
|
||||
]) {
|
||||
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 insert = async (key: string, payload: unknown) =>
|
||||
pool.query(
|
||||
"INSERT INTO backtest_datasets(hash,payload,created_at) VALUES($1,$2::jsonb,'2024-02-01T00:00:00Z')",
|
||||
[key, JSON.stringify(payload)]
|
||||
);
|
||||
const api = new BacktestServiceV2({ postgres, logger }, async () => {
|
||||
throw new Error('Catalog must not fetch source data');
|
||||
});
|
||||
return {
|
||||
pool,
|
||||
schema,
|
||||
postgres,
|
||||
api,
|
||||
insert,
|
||||
catalog: new DatasetCatalogService(postgres),
|
||||
routes: new Hono().route('/', createDatasetRoutes({ postgres, logger })),
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('dataset catalog and selected-run submission on real PostgreSQL', () => {
|
||||
test('dataset_list_metadata_only projects no bars and diagnoses malformed shapes without SQL errors', async () => {
|
||||
const f = await fixture();
|
||||
await f.insert(hash, {
|
||||
manifest: manifest(),
|
||||
bars: [{ payloadMustStayInPostgres: 'SECRET_BAR_CONTENT' }],
|
||||
});
|
||||
const cases = [
|
||||
null,
|
||||
[],
|
||||
'malformed',
|
||||
{ manifest: manifest('2'.repeat(64)), bars: {} },
|
||||
{ manifest: manifest('3'.repeat(64)), bars: [] },
|
||||
{ manifest: manifest('4'.repeat(64)), bars: [1], extra: true },
|
||||
{ manifest: { version: 2 }, bars: [] },
|
||||
];
|
||||
for (let index = 0; index < cases.length; index++) {
|
||||
await f.insert(String(index + 2).repeat(64), cases[index]);
|
||||
}
|
||||
const result = await f.routes.request('/api/v2/datasets');
|
||||
expect(result.status).toBe(200);
|
||||
const body = await result.json();
|
||||
expect(body.datasets).toHaveLength(8);
|
||||
expect(body.datasets[0]).toMatchObject({
|
||||
hash,
|
||||
status: 'available',
|
||||
coverage: 'unknown',
|
||||
integrity: 'not-verified',
|
||||
manifest: { barCount: 1 },
|
||||
});
|
||||
expect(body.datasets.at(-1)).toMatchObject({
|
||||
version: 2,
|
||||
status: 'unsupported',
|
||||
manifest: null,
|
||||
});
|
||||
expect(body.datasets.at(-1).reason).toContain('R05');
|
||||
expect(JSON.stringify(body)).not.toContain('SECRET_BAR_CONTENT');
|
||||
expect(JSON.stringify(body)).not.toContain('"bars"');
|
||||
for (const item of body.datasets.slice(1, -1)) {
|
||||
expect(item.status).toBe('invalid');
|
||||
}
|
||||
const queries: string[] = [];
|
||||
const projected = new DatasetCatalogService({
|
||||
async query(text, values) {
|
||||
queries.push(text);
|
||||
const rows = await f.pool.query(text, values);
|
||||
expect(rows.rows[0]).not.toHaveProperty('payload');
|
||||
expect(rows.rows[0]).not.toHaveProperty('bars');
|
||||
expect(rows.rows[0].bar_count).toBe(1);
|
||||
return rows;
|
||||
},
|
||||
});
|
||||
await projected.get(hash);
|
||||
expect(queries[0]).not.toContain('SELECT *');
|
||||
expect(queries[0]).toContain("payload->'manifest' AS manifest");
|
||||
expect((await f.routes.request('/api/v2/datasets?limit=1&offset=1')).status).toBe(200);
|
||||
expect((await f.routes.request(`/api/v2/datasets/${'f'.repeat(64)}`)).status).toBe(404);
|
||||
expect((await f.routes.request('/api/v2/datasets/not-a-hash')).status).toBe(400);
|
||||
});
|
||||
|
||||
test('select_hash_compatibility validates exact assets, interval, range, policy and explicit source on create and update', async () => {
|
||||
const f = await fixture();
|
||||
await f.insert(hash, { manifest: manifest(), bars: [{}] });
|
||||
const saved = await f.api.createBacktest(request(), { autoStart: false });
|
||||
for (const changed of [
|
||||
{ symbols: ['OTHER.TEST'] },
|
||||
{ startDate: '2024-01-02T00:00:00.000Z' },
|
||||
{ endDate: '2024-01-04T00:00:00.000Z' },
|
||||
{ config: { ...request().config, dataFrequency: '1h' } },
|
||||
{
|
||||
config: {
|
||||
...request().config,
|
||||
dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' },
|
||||
},
|
||||
},
|
||||
{ config: { ...request().config, dataSource: 'questdb' } },
|
||||
]) {
|
||||
await expect(
|
||||
f.api.createBacktest({ ...request(), ...changed }, { autoStart: false })
|
||||
).rejects.toThrow('does not match');
|
||||
await expect(f.api.updateBacktest(saved.id, changed)).rejects.toThrow('does not match');
|
||||
}
|
||||
expect((await f.api.getBacktest(saved.id))!.config).toEqual(request().config!);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtests')).rows[0].n).toBe(1);
|
||||
for (const dataSource of ['eod', 'auto']) {
|
||||
await expect(
|
||||
f.api.updateBacktest(saved.id, { config: { ...request().config, dataSource } })
|
||||
).resolves.not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
test('missing, inconsistent, malformed and unsupported selected snapshots reject before any run/outbox is inserted', async () => {
|
||||
const f = await fixture();
|
||||
const saved = await f.api.createBacktest(
|
||||
{ ...request(), config: { fastPeriod: 2, slowPeriod: 3 } },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const payloads = [
|
||||
{ manifest: manifest('f'.repeat(64)), bars: [{}] },
|
||||
{ manifest: { ...manifest(), barCount: 2 }, bars: [{}] },
|
||||
{ manifest: { ...manifest(), sources: [] }, bars: [{}] },
|
||||
{ manifest: { version: 2 }, bars: [] },
|
||||
];
|
||||
for (const payload of payloads) {
|
||||
await f.pool.query('DELETE FROM backtest_datasets');
|
||||
await f.insert(hash, payload);
|
||||
await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [
|
||||
saved.id,
|
||||
JSON.stringify(request().config),
|
||||
]);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow();
|
||||
}
|
||||
await f.pool.query('DELETE FROM backtest_datasets');
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow('not found');
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
||||
0
|
||||
);
|
||||
});
|
||||
|
||||
test('concurrent partial definition edits lock, merge and validate one committed definition', async () => {
|
||||
const f = await fixture();
|
||||
await f.insert(hash, { manifest: manifest(), bars: [{}] });
|
||||
const saved = await f.api.createBacktest({ ...request(), config: {} }, { autoStart: false });
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('LOCK TABLE backtest_datasets IN ACCESS EXCLUSIVE MODE');
|
||||
const selected = f.api.updateBacktest(saved.id, { config: request().config }).then(
|
||||
value => ({ value, error: null }),
|
||||
error => ({ value: null, error })
|
||||
);
|
||||
const isWaiting = async (pattern: string) => {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
const result = await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE $2",
|
||||
[f.schema, pattern]
|
||||
);
|
||||
if (result.rowCount) {
|
||||
return true;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
return false;
|
||||
};
|
||||
let catalogWait = false;
|
||||
let definitionWait = false;
|
||||
let changed: typeof selected | undefined;
|
||||
try {
|
||||
catalogWait = await isWaiting('%FROM backtest_datasets%');
|
||||
changed = f.api.updateBacktest(saved.id, { endDate: '2024-01-04T00:00:00.000Z' }).then(
|
||||
value => ({ value, error: null }),
|
||||
error => ({ value: null, error })
|
||||
);
|
||||
definitionWait = await isWaiting('SELECT * FROM backtests WHERE id = $1 FOR UPDATE');
|
||||
} finally {
|
||||
await blocker.query('COMMIT');
|
||||
blocker.release();
|
||||
}
|
||||
const winner = await selected;
|
||||
if (!changed) {
|
||||
throw new Error('Concurrent edit was not started');
|
||||
}
|
||||
const loser = await changed;
|
||||
expect(catalogWait).toBe(true);
|
||||
expect(definitionWait).toBe(true);
|
||||
expect(winner.error).toBeNull();
|
||||
expect(loser.error).toBeInstanceOf(Error);
|
||||
expect(loser.error!.message).toContain('does not match');
|
||||
const retained = await f.api.getBacktest(saved.id);
|
||||
expect(retained!.endDate.toISOString()).toBe(manifest().endDate);
|
||||
expect(retained!.config.datasetHash).toBe(hash);
|
||||
expect((await f.api.createRun({ backtestId: saved.id })).dataset.requestedHash).toBe(hash);
|
||||
});
|
||||
|
||||
test('selected run snapshots commit atomically and same-key retry returns its original receipt before mutable definition validation', async () => {
|
||||
const f = await fixture();
|
||||
await f.insert(hash, { manifest: manifest(), bars: [{}] });
|
||||
const saved = await f.api.createBacktest(request(), { autoStart: false });
|
||||
await f.pool.query(
|
||||
`CREATE FUNCTION reject_dataset_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dataset_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dataset_outbox()`
|
||||
);
|
||||
await expect(f.api.createRun({ backtestId: saved.id })).rejects.toThrow(
|
||||
'injected outbox failure'
|
||||
);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
||||
await f.pool.query('DROP TRIGGER reject_dataset_outbox ON backtest_dispatch');
|
||||
const submission = { principal: 'operator' as const, key: 'dataset-retry' };
|
||||
const first = await f.api.createRun({ backtestId: saved.id }, submission);
|
||||
expect(first.dataset).toEqual({
|
||||
requestedHash: hash,
|
||||
pinnedHash: null,
|
||||
source: 'auto',
|
||||
state: 'requested',
|
||||
});
|
||||
await f.pool.query(
|
||||
'UPDATE backtests SET symbols=\'["OTHER.TEST"]\',config=\'{"datasetHash":"bad"}\' WHERE id=$1',
|
||||
[saved.id]
|
||||
);
|
||||
await f.pool.query('DELETE FROM backtest_datasets');
|
||||
const retried = await f.api.createRun({ backtestId: saved.id }, submission);
|
||||
expect(retried.id).toBe(first.id);
|
||||
expect(retried.dataset).toEqual(first.dataset);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
||||
1
|
||||
);
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: saved.id }, { ...submission, key: 'different' })
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('source_request_freeze_status exposes immutable request and binding independently of run success or later template edits', async () => {
|
||||
const f = await fixture();
|
||||
await f.insert(hash, { manifest: manifest(), bars: [{}] });
|
||||
const saved = await f.api.createBacktest(
|
||||
{ ...request(), config: { dataSource: 'eod' } },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await f.api.createRun({ backtestId: saved.id });
|
||||
expect(run.dataset).toEqual({
|
||||
requestedHash: null,
|
||||
pinnedHash: null,
|
||||
source: 'eod',
|
||||
state: 'requested',
|
||||
});
|
||||
await f.pool.query("UPDATE runs SET status='running' WHERE id=$1", [run.id]);
|
||||
expect((await f.api.getRun(run.id))!.dataset.state).toBe('preparing');
|
||||
await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [run.id]);
|
||||
expect((await f.api.getRun(run.id))!.dataset.state).toBe('unavailable');
|
||||
await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [run.id, hash]);
|
||||
await f.pool.query('UPDATE backtests SET config=\'{"dataSource":"questdb"}\' WHERE id=$1', [
|
||||
saved.id,
|
||||
]);
|
||||
expect(await f.api.getRun(run.id)).toMatchObject({
|
||||
status: 'failed',
|
||||
dataset: { requestedHash: null, pinnedHash: hash, source: 'eod', state: 'pinned' },
|
||||
});
|
||||
await f.pool.query('UPDATE runs SET request_snapshot=NULL WHERE id=$1', [run.id]);
|
||||
expect((await f.api.getRun(run.id))!.dataset).toEqual({
|
||||
requestedHash: null,
|
||||
pinnedHash: hash,
|
||||
source: null,
|
||||
state: 'unknown',
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue