fix(research): reuse older and known-hash datasets (RP05)
This commit is contained in:
parent
5319bd1bb2
commit
6d549542a9
5 changed files with 680 additions and 51 deletions
|
|
@ -29,6 +29,7 @@ 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 backtestApiV2: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').backtestApiV2;
|
||||
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
|
||||
let CanonicalResults: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalResults').CanonicalResults;
|
||||
let RunsListWithMetrics: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics').RunsListWithMetrics;
|
||||
|
|
@ -49,6 +50,8 @@ function deferred<T>() {
|
|||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
search: string;
|
||||
signal: AbortSignal | null | undefined;
|
||||
method: string;
|
||||
body: unknown;
|
||||
headers: Headers;
|
||||
|
|
@ -230,6 +233,9 @@ beforeAll(async () => {
|
|||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ backtestApiV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
|
||||
));
|
||||
({ CanonicalSetup } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup'
|
||||
));
|
||||
|
|
@ -260,6 +266,8 @@ beforeEach(() => {
|
|||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(url)).pathname,
|
||||
search: new URL(String(url)).search,
|
||||
signal: init?.signal,
|
||||
method: init?.method ?? 'GET',
|
||||
headers: new Headers(init?.headers),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
|
|
@ -874,6 +882,7 @@ describe('canonical research workbench', () => {
|
|||
)
|
||||
);
|
||||
await selected();
|
||||
await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] }));
|
||||
await flush(() =>
|
||||
reply(stale, {
|
||||
parameters: { fastPeriod: 3, slowPeriod: 15 },
|
||||
|
|
@ -893,6 +902,7 @@ describe('canonical research workbench', () => {
|
|||
)
|
||||
);
|
||||
await selected();
|
||||
await flush(() => reply(request('/api/v2/datasets/canonical'), { datasets: [entry] }));
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
await flush(() => edit('Canonical dataset', hash));
|
||||
|
|
@ -1064,3 +1074,307 @@ describe('canonical research workbench', () => {
|
|||
});
|
||||
}
|
||||
});
|
||||
|
||||
const catalogPath = '/api/v2/datasets/canonical';
|
||||
function catalogEntry(
|
||||
index: number,
|
||||
extra: Partial<CanonicalDatasetCatalogEntry> = {}
|
||||
): CanonicalDatasetCatalogEntry {
|
||||
const identity = index.toString(16).padStart(64, '0');
|
||||
return {
|
||||
...entry,
|
||||
hash: identity,
|
||||
manifest: { ...entry.manifest!, hash: identity },
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
async function setupCatalog(entries: CanonicalDatasetCatalogEntry[]) {
|
||||
const saves: CreateBacktestRequest[] = [];
|
||||
await mount(
|
||||
createElement(CanonicalSetup, {
|
||||
backtest: definition,
|
||||
onSave: async value => {
|
||||
saves.push(value);
|
||||
},
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
await validateSelected();
|
||||
await flush(() => reply(request(catalogPath), { datasets: entries }));
|
||||
return saves;
|
||||
}
|
||||
async function useKnownHash(value: string) {
|
||||
await flush(() => edit('Retained dataset hash', value));
|
||||
await flush(() => click('Use dataset hash'));
|
||||
}
|
||||
function optionHashes() {
|
||||
return [...(field('Canonical dataset') as HTMLSelectElement).options]
|
||||
.map(option => option.value)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
describe('retained canonical dataset reuse', () => {
|
||||
test('loads beyond fifty, retries the same failed offset, deduplicates overlaps and saves exact verified bounds', async () => {
|
||||
const entries = Array.from({ length: 53 }, (_, index) => catalogEntry(index + 1));
|
||||
const saves = await setupCatalog(entries.slice(0, 50));
|
||||
await flush(() => edit('Canonical dataset', entries[0]!.hash));
|
||||
await flush(() =>
|
||||
reply(request(`${catalogPath}/${entries[0]!.hash}`), { dataset: entries[0] })
|
||||
);
|
||||
await flush(() => {
|
||||
click('Load more canonical datasets');
|
||||
click('Load more canonical datasets');
|
||||
});
|
||||
const next = request(catalogPath);
|
||||
expect(next.search).toBe('?limit=50&offset=50');
|
||||
expect(requests.filter(item => item.path === catalogPath && !item.settled)).toHaveLength(1);
|
||||
await flush(() => fail(next));
|
||||
expect(optionHashes()).toHaveLength(50);
|
||||
expect(field('Canonical dataset').value).toBe(entries[0]!.hash);
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => click('Retry canonical datasets'));
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=50');
|
||||
await flush(() => reply(request(catalogPath), { datasets: entries.slice(49) }));
|
||||
expect(optionHashes()).toHaveLength(53);
|
||||
expect(new Set(optionHashes()).size).toBe(53);
|
||||
expect(
|
||||
[...host.querySelectorAll('button')].some(
|
||||
item => item.textContent === 'Load more canonical datasets'
|
||||
)
|
||||
).toBe(false);
|
||||
const chosen = entries[52]!;
|
||||
await flush(() => edit('Canonical dataset', chosen.hash));
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
await flush(() => click('Save canonical setup'));
|
||||
expect(saves).toHaveLength(1);
|
||||
expect(saves[0]!.config?.datasetHash).toBe(chosen.hash);
|
||||
expect(saves[0]!.startDate).toBe(new Date(chosen.manifest!.bounds.tradeStart).toISOString());
|
||||
expect(saves[0]!.endDate).toBe(new Date(chosen.manifest!.bounds.tradeEnd).toISOString());
|
||||
expect(requests.some(item => item.method === 'POST' && item.path.endsWith('/runs'))).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('explicit known-hash lookup accepts converted lineage; typing and Enter never fetch or submit', async () => {
|
||||
const chosen = catalogEntry(100);
|
||||
chosen.manifest = { ...chosen.manifest!, parentDatasetHash: 'e'.repeat(64) };
|
||||
const saves = await setupCatalog([]);
|
||||
const before = requests.length;
|
||||
await flush(() => edit('Retained dataset hash', chosen.hash));
|
||||
const enter = new browser.KeyboardEvent('keydown', {
|
||||
key: 'Enter',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await flush(() => {
|
||||
field('Retained dataset hash').dispatchEvent(enter as unknown as Event);
|
||||
});
|
||||
expect(enter.defaultPrevented).toBe(true);
|
||||
expect(requests).toHaveLength(before);
|
||||
expect(saves).toEqual([]);
|
||||
expect(host.textContent).not.toContain('Unsaved canonical setup');
|
||||
await flush(() => click('Use dataset hash'));
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
expect(field('Canonical dataset').value).toBe(chosen.hash);
|
||||
expect(optionHashes()).toEqual([chosen.hash]);
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => click('Save canonical setup'));
|
||||
expect(saves[0]!.config?.datasetHash).toBe(chosen.hash);
|
||||
});
|
||||
|
||||
test('malformed hash never fetches and invalid, missing, unavailable or wrong detail cannot authorize saving', async () => {
|
||||
const chosen = catalogEntry(100);
|
||||
const saves = await setupCatalog([chosen]);
|
||||
for (const invalid of ['', 'not-a-hash', 'A'.repeat(64)]) {
|
||||
const before = requests.length;
|
||||
await useKnownHash(invalid);
|
||||
expect(requests).toHaveLength(before);
|
||||
expect(host.textContent).toContain('64 lowercase hexadecimal');
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
}
|
||||
const replies = [
|
||||
{ body: { error: 'Dataset not found' }, status: 404 },
|
||||
{
|
||||
body: {
|
||||
dataset: { ...chosen, available: false, manifest: null, reason: 'Stored bytes invalid' },
|
||||
},
|
||||
status: 200,
|
||||
},
|
||||
{ body: { dataset: catalogEntry(101) }, status: 200 },
|
||||
{ body: { dataset: { ...chosen, available: true, manifest: null } }, status: 200 },
|
||||
{
|
||||
body: { dataset: { ...chosen, manifest: { ...chosen.manifest, executionSeries: null } } },
|
||||
status: 200,
|
||||
},
|
||||
{ body: { wrongEnvelope: chosen }, status: 200 },
|
||||
];
|
||||
for (const item of replies) {
|
||||
await useKnownHash(chosen.hash);
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), item.body, item.status));
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(host.textContent).not.toContain('The selected hash is retained');
|
||||
}
|
||||
await useKnownHash(chosen.hash);
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => edit('Retained dataset hash', 'bad'));
|
||||
await flush(() => {
|
||||
click('Use dataset hash');
|
||||
click('Save canonical setup');
|
||||
});
|
||||
expect(saves).toEqual([]);
|
||||
});
|
||||
|
||||
test('late lookups, refresh and unmount cannot replace the current verified hash or authorize a same-event save', async () => {
|
||||
const a = catalogEntry(100),
|
||||
b = catalogEntry(101);
|
||||
const saves = await setupCatalog([]);
|
||||
await useKnownHash(a.hash);
|
||||
const stale = request(`${catalogPath}/${a.hash}`);
|
||||
await useKnownHash(b.hash);
|
||||
expect(stale.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(request(`${catalogPath}/${b.hash}`), { dataset: b }));
|
||||
await flush(() => reply(stale, { dataset: a }));
|
||||
expect(field('Canonical dataset').value).toBe(b.hash);
|
||||
await flush(() => {
|
||||
click('Refresh canonical datasets');
|
||||
click('Save canonical setup');
|
||||
});
|
||||
expect(saves).toEqual([]);
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
expect(field('Canonical dataset').value).toBe(b.hash);
|
||||
await flush(() => reply(request(catalogPath), { datasets: [] }));
|
||||
await flush(() => reply(request(`${catalogPath}/${b.hash}`), { dataset: b }));
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await useKnownHash(a.hash);
|
||||
const pending = request(`${catalogPath}/${a.hash}`);
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
expect(pending.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(pending, { dataset: a }));
|
||||
expect(saves).toEqual([]);
|
||||
});
|
||||
|
||||
test('refresh fences old pages, resets pagination and preserves an off-page selection', async () => {
|
||||
const entries = Array.from({ length: 51 }, (_, index) => catalogEntry(index + 1));
|
||||
await setupCatalog(entries.slice(0, 50));
|
||||
const chosen = entries[0]!;
|
||||
await flush(() => edit('Canonical dataset', chosen.hash));
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
const old = request(catalogPath);
|
||||
await flush(() => click('Refresh canonical datasets'));
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(old, { datasets: entries.slice(50) }));
|
||||
expect(optionHashes()).toEqual([chosen.hash]);
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=0');
|
||||
await flush(() => reply(request(catalogPath), { datasets: entries.slice(1, 51) }));
|
||||
await flush(() => reply(request(`${catalogPath}/${chosen.hash}`), { dataset: chosen }));
|
||||
expect(field('Canonical dataset').value).toBe(chosen.hash);
|
||||
expect(optionHashes()).toHaveLength(51);
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=50');
|
||||
});
|
||||
|
||||
test('malformed catalog is recoverable; valid unavailable entries remain visible and disabled', async () => {
|
||||
await setupCatalog([]);
|
||||
for (const malformed of [
|
||||
{ datasets: null },
|
||||
{ datasets: [null] },
|
||||
{ datasets: [{ ...entry, manifest: {} }] },
|
||||
{ entries: [] },
|
||||
]) {
|
||||
await flush(() => click('Refresh canonical datasets'));
|
||||
await flush(() => reply(request(catalogPath), malformed));
|
||||
expect(host.textContent).toContain('catalog response could not be verified');
|
||||
expect(button('Save canonical setup').disabled).toBe(true);
|
||||
}
|
||||
await flush(() => click('Retry canonical datasets'));
|
||||
const unavailable = {
|
||||
...catalogEntry(99),
|
||||
available: false,
|
||||
manifest: null,
|
||||
reason: 'Retained payload cannot be validated',
|
||||
};
|
||||
await flush(() => reply(request(catalogPath), { datasets: [unavailable] }));
|
||||
const option = [...(field('Canonical dataset') as HTMLSelectElement).options].find(
|
||||
item => item.value === unavailable.hash
|
||||
)!;
|
||||
expect(option.disabled).toBe(true);
|
||||
expect(option.textContent).toContain(unavailable.reason);
|
||||
expect(host.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
|
||||
test('retention refresh fences an old page and selects newly retained bytes without duplicate choices', async () => {
|
||||
const entries = Array.from({ length: 50 }, (_, index) => catalogEntry(index + 1));
|
||||
await setupCatalog(entries);
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
const old = request(catalogPath);
|
||||
const retained = nativeReplayFixture(4).dataset;
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
retained.manifest;
|
||||
const input = {
|
||||
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
||||
bars: retained.bars.map(bar => ({
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart,
|
||||
availableAt: bar.availableAt,
|
||||
sourceSequence: bar.sourceSequence,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
})),
|
||||
};
|
||||
const file = field('Source dataset JSON');
|
||||
Object.defineProperty(file, 'files', {
|
||||
configurable: true,
|
||||
value: [{ name: 'new.json', text: async () => JSON.stringify(input) }],
|
||||
});
|
||||
await flush(() =>
|
||||
file.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event)
|
||||
);
|
||||
await flush(() => click('Preview dataset'));
|
||||
const preparation = {
|
||||
version: 'canonical-dataset-preparation/v1',
|
||||
hash: retained.manifest.hash,
|
||||
manifest: retained.manifest,
|
||||
available: true,
|
||||
reason: null,
|
||||
};
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/datasets/canonical/preview', 'POST'), { preparation })
|
||||
);
|
||||
await flush(() => click('Retain dataset'));
|
||||
await flush(() => reply(request('/api/v2/datasets/canonical/retain', 'POST'), { preparation }));
|
||||
expect(old.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(old, { datasets: [catalogEntry(51)] }));
|
||||
const fresh = {
|
||||
hash: retained.manifest.hash,
|
||||
manifest: retained.manifest,
|
||||
available: true,
|
||||
reason: null,
|
||||
createdAt: entry.createdAt,
|
||||
};
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=0');
|
||||
await flush(() => reply(request(catalogPath), { datasets: [fresh, ...entries.slice(0, 49)] }));
|
||||
await flush(() => reply(request(`${catalogPath}/${fresh.hash}`), { dataset: fresh }));
|
||||
expect(field('Canonical dataset').value).toBe(fresh.hash);
|
||||
expect(optionHashes()).toHaveLength(50);
|
||||
expect(new Set(optionHashes()).size).toBe(50);
|
||||
expect(button('Save canonical setup').disabled).toBe(false);
|
||||
await flush(() => click('Load more canonical datasets'));
|
||||
expect(request(catalogPath).search).toBe('?limit=50&offset=50');
|
||||
});
|
||||
|
||||
test('transport rejects malformed page arguments and exact-hash requests before network access', async () => {
|
||||
const before = requests.length;
|
||||
await expect(backtestApiV2.listCanonicalDatasets(0, 0)).rejects.toThrow('pagination');
|
||||
await expect(backtestApiV2.listCanonicalDatasets(50, -1)).rejects.toThrow('pagination');
|
||||
await expect(backtestApiV2.canonicalDataset('bad')).rejects.toThrow('64 lowercase hexadecimal');
|
||||
expect(requests).toHaveLength(before);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue