feat(research): select and reuse frozen datasets in workbench

This commit is contained in:
Boki 2026-10-23 18:13:37 -04:00
parent 6a67ae8683
commit b106c1ca85
29 changed files with 2295 additions and 426 deletions

View file

@ -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);

View 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');
});

View 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');
});
});

View file

@ -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]!]);