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
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');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue