feat(research): prepare stored EOD datasets before canonical admission

This commit is contained in:
Boki 2026-10-24 15:26:38 -04:00
parent 366bee810b
commit 0c6aec4dc6
16 changed files with 1897 additions and 61 deletions

View file

@ -5,8 +5,10 @@ import type { Root } from 'react-dom/client';
import type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
CanonicalStoredSourcePreparation,
} from '@stock-bot/stock-config/canonical-research';
import type {
HistoricalDatasetMetadataV2,
StrategyParameterSchema,
StrategyRecord,
StrategyVersionPackage,
@ -15,6 +17,7 @@ import type {
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import type { CreateBacktestRequest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
import { datasetInput } from '../fixtures/historical-v2/dataset';
import { metadata as intradayMetadata, intradayResponse } from '../fixtures/intraday/eod';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT', 'ResizeObserver'] as const;
@ -24,6 +27,7 @@ let router: typeof import('react-router-dom');
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
let DatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation').DatasetPreparation;
let parseDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseDatasetPreparation;
let parseStoredDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseStoredDatasetPreparation;
function confirmWith(value: () => boolean) {
Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value });
}
@ -114,13 +118,13 @@ function upload(value: unknown = datasetInput(), name = 'source.json', read?: Pr
if (read) {
Object.defineProperty(file, 'text', { value: () => read });
}
Object.defineProperty(field('Source dataset JSON'), 'files', {
const label =
field('Dataset input').value === 'stored-eod' ? 'Source metadata JSON' : 'Source dataset JSON';
Object.defineProperty(field(label), 'files', {
configurable: true,
value: [file],
});
field('Source dataset JSON').dispatchEvent(
new browser.Event('change', { bubbles: true }) as unknown as Event
);
field(label).dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
}
async function mount(element: ReactElement) {
root = createRoot(host);
@ -271,7 +275,7 @@ beforeAll(async () => {
({ DatasetPreparation } = await import(
'../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation'
));
({ parseDatasetPreparation } = await import(
({ parseDatasetPreparation, parseStoredDatasetPreparation } = await import(
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
));
});
@ -880,3 +884,445 @@ describe('canonical setup coordination', () => {
expect(button('Save canonical setup').disabled).toBe(false);
});
});
const storedPath = '/api/v2/datasets/canonical/stored-source';
function storedFixture(
metadata: HistoricalDatasetMetadataV2 = intradayMetadata()
): CanonicalStoredSourcePreparation {
const input = {
metadata,
bars: intradayResponse().map((bar, sourceSequence) => ({
seriesId: metadata.series[0]!.id,
timestamp: bar.timestamp * 1000,
sourceSequence,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
})),
};
const normalized = createDatasetV2(input);
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
normalized.manifest;
return {
input: {
...input,
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
},
preparation: {
version: 'canonical-dataset-preparation/v1',
hash: normalized.manifest.hash,
manifest: normalized.manifest,
available: normalized.manifest.eligibility === 'eligible',
reason:
normalized.manifest.eligibility === 'eligible'
? null
: 'Declared coverage is unavailable for execution',
},
};
}
const storedMetadata: HistoricalDatasetMetadataV2 = {
...intradayMetadata(),
universe: {
...intradayMetadata().universe,
selection: 'point-in-time',
asOf: intradayMetadata().bounds.warmupStart,
},
corporateActions: intradayMetadata().corporateActions.map(item => ({
...item,
status: 'action-free',
})),
};
const stored = storedFixture(storedMetadata);
async function storedPreview(value: CanonicalStoredSourcePreparation = stored) {
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(value.input.metadata, 'metadata.json'));
await flush(() => click('Preview dataset'));
await flush(() => reply(request(storedPath), value));
}
describe('stored source response contract', () => {
test('validates the captured complete input without inventing optional VWAP or availability', () => {
const result = parseStoredDatasetPreparation(stored, storedMetadata);
expect(result).toEqual(stored);
expect(result.input.bars.every(bar => !('vwap' in bar) && !('availableAt' in bar))).toBe(true);
});
test('accepts the normalizer collection order while preserving all declared values', () => {
const base = intradayMetadata();
const calendar = base.calendars[0]!;
const metadata: HistoricalDatasetMetadataV2 = {
...base,
calendars: [
{
...calendar,
id: 'z-extra',
startDate: '2024-03-10',
sessions: [
calendar.sessions[0]!,
{
date: '2024-03-10',
open: calendar.sessions[0]!.open - 86400000,
close: calendar.sessions[0]!.close - 86400000,
},
],
},
calendar,
],
corporateActions: base.corporateActions.map(item => ({
...item,
status: 'known-actions',
actions: [
{ effectiveAt: item.start + 1, kind: 'dividend', reference: 'z-later' },
{ effectiveAt: item.start, kind: 'split', reference: 'a-earlier' },
],
})),
};
const result = storedFixture(metadata);
expect(result.input.metadata.calendars[0]!.id).toBe(calendar.id);
expect(parseStoredDatasetPreparation(result, metadata)).toEqual(result);
expect(metadata.calendars[0]!.id).toBe('z-extra');
expect(metadata.corporateActions[0]!.actions[0]!.reference).toBe('z-later');
});
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
const changes: {
name: string;
change: (value: Mutable<CanonicalStoredSourcePreparation>) => unknown;
}[] = [
{ name: 'unknown envelope property', change: v => Object.assign(v, { certified: true }) },
{ name: 'unknown input property', change: v => Object.assign(v.input, { requestId: 'other' }) },
{
name: 'unknown metadata property',
change: v => Object.assign(v.input.metadata, { certified: true }),
},
{
name: 'unknown bar property',
change: v => Object.assign(v.input.bars[0]!, { instrumentId: 'wrong' }),
},
{
name: 'invented availability',
change: v => Object.assign(v.input.bars[0]!, { availableAt: v.input.bars[0]!.timestamp }),
},
{ name: 'wrong preparation hash', change: v => (v.preparation.hash = 'a'.repeat(64)) },
{ name: 'wrong bar count', change: v => v.preparation.manifest.barCount++ },
{ name: 'wrong series identity', change: v => (v.input.bars[0]!.seriesId = 'another-series') },
{ name: 'wrong row ordinal', change: v => (v.input.bars[1]!.sourceSequence = 15) },
{
name: 'duplicate timestamp',
change: v => (v.input.bars[1]!.timestamp = v.input.bars[0]!.timestamp),
},
{
name: 'out-of-range timestamp',
change: v => (v.input.bars[0]!.timestamp = v.input.metadata.bounds.tradeEnd),
},
{ name: 'non-finite price', change: v => (v.input.bars[0]!.open = Infinity) },
{ name: 'malformed VWAP', change: v => (v.input.bars[0]!.vwap = -1) },
{ name: 'empty bars', change: v => (v.input.bars = []) },
{
name: 'changed source revision',
change: v => (v.input.metadata.series[0]!.source.revision = 'unexpected revision'),
},
{
name: 'changed manifest revision',
change: v => (v.preparation.manifest.calendars[0]!.revision = 'changed-calendar'),
},
{
name: 'changed source provider',
change: v => (v.input.metadata.series[0]!.source.provider = 'questdb'),
},
{
name: 'unsupported daily interval',
change: v => (v.input.metadata.series[0]!.interval = '1d'),
},
{
name: 'unsupported adjusted prices',
change: v => (v.input.metadata.series[0]!.adjustment = 'provider-adjusted'),
},
{
name: 'unsupported explicit availability',
change: v => (v.input.metadata.series[0]!.availability = 'explicit'),
},
];
for (const { name, change } of changes) {
test(`rejects ${name}`, () => {
const value = structuredClone(stored) as Mutable<CanonicalStoredSourcePreparation>;
change(value);
expect(() => parseStoredDatasetPreparation(value, storedMetadata)).toThrow();
});
}
test('rejects a valid response bound to different caller metadata', () => {
expect(() =>
parseStoredDatasetPreparation(stored, {
...storedMetadata,
bounds: { ...storedMetadata.bounds, tradeStart: storedMetadata.bounds.tradeStart + 1 },
})
).toThrow();
});
});
describe('stored source panel', () => {
test('defaults to the existing export mode and selecting stored mode performs no IO', async () => {
await mountPanel();
expect(field('Dataset input').value).toBe('export');
await flush(() => edit('Dataset input', 'stored-eod'));
expect(field('Source metadata JSON')).toBeDefined();
expect(host.textContent).toContain('No source metadata selected.');
expect(host.textContent).toContain('not a vendor sequence');
expect(host.textContent).toContain('not independently certified');
expect(requests).toHaveLength(0);
expect(button('Preview dataset').disabled).toBe(true);
});
test('stored preview sends only declared metadata, displays snapshot and retains returned full input without requery', async () => {
await mountPanel();
await storedPreview();
expect(requests.filter(item => item.path === storedPath)).toHaveLength(1);
expect(requests.find(item => item.path === storedPath)!.body).toEqual({
metadata: stored.input.metadata,
});
expect(host.textContent).toContain('Stored source: EOD');
expect(host.textContent).toContain('FIXTURE.TEST / 5m');
expect(host.textContent).toContain('2024-03-11T13:30:00.000Z');
expect(host.textContent).toContain('2024-03-11T20:00:00.000Z');
expect(host.textContent).toContain('Availability: interval-end-assumption');
await flush(() => {
click('Retain dataset');
click('Retain dataset');
});
const first = request(retainPath);
expect(first.body).toEqual({ input: stored.input, expectedHash: stored.preparation.hash });
await flush(() => fail(first));
expect(field('Dataset input').disabled).toBe(true);
expect(field('Source metadata JSON').disabled).toBe(true);
await flush(() => {
edit('Dataset input', 'export');
upload({ replacement: true });
});
expect(field('Dataset input').value).toBe('stored-eod');
expect(host.textContent).toContain('Selected metadata: metadata.json');
await flush(() => click('Retry retaining same dataset'));
expect(request(retainPath).body).toEqual(first.body);
expect(requests.filter(item => item.path === storedPath)).toHaveLength(1);
expect(requests.filter(item => item.path === previewPath)).toHaveLength(0);
await flush(() => reply(request(retainPath), { preparation: stored.preparation }));
expect(retained).toEqual([{ hash: stored.preparation.hash, available: true }]);
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
});
test('same-event retain then mode change cannot discard or retarget the captured snapshot', async () => {
await mountPanel();
await storedPreview();
await flush(() => {
click('Retain dataset');
edit('Dataset input', 'export');
click('Clear source preparation');
});
expect(request(retainPath).body).toEqual({
input: stored.input,
expectedHash: stored.preparation.hash,
});
expect(field('Dataset input').value).toBe('stored-eod');
await flush(() => fail(request(retainPath)));
expect(button('Retry retaining same dataset').disabled).toBe(false);
confirmWith(() => false);
await flush(() => click('Clear source preparation'));
expect(field('Dataset input').disabled).toBe(true);
confirmWith(() => true);
await flush(() => click('Clear source preparation'));
await flush(() => edit('Dataset input', 'export'));
expect(field('Dataset input').value).toBe('export');
expect(host.textContent).toContain('No source export selected.');
});
test('same-event mode change invalidates old retain and preview handlers', async () => {
await mountPanel();
await storedPreview();
await flush(() => {
edit('Dataset input', 'export');
click('Retain dataset');
click('Preview dataset');
});
expect(requests.filter(item => item.path === retainPath)).toHaveLength(0);
expect(requests.filter(item => item.path === previewPath)).toHaveLength(0);
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
});
test('mode switching fences a late stored response and a late export response', async () => {
await mountPanel();
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(storedMetadata));
await flush(() => click('Preview dataset'));
const oldStored = request(storedPath);
await flush(() => edit('Dataset input', 'export'));
expect(oldStored.signal?.aborted).toBe(true);
await flush(() => reply(oldStored, stored));
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
await flush(() => upload());
await flush(() => click('Preview dataset'));
const oldExport = request(previewPath);
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => reply(oldExport, { preparation }));
expect(host.textContent).toContain('No source metadata selected.');
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
});
test('mode switching fences a late file read', async () => {
await mountPanel();
const read = deferred<string>();
await flush(() => upload({}, 'old-export.json', read.promise));
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => read.resolve(JSON.stringify(datasetInput())));
expect(host.textContent).toContain('No source metadata selected.');
expect(button('Preview dataset').disabled).toBe(true);
});
test('file replacement fences the previous stored read without discarding the new file', async () => {
await mountPanel();
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(storedMetadata));
await flush(() => click('Preview dataset'));
const old = request(storedPath);
const next = {
...storedMetadata,
universe: { ...storedMetadata.universe, revision: 'next declaration' },
};
await flush(() => upload(next, 'next.json'));
await flush(() => reply(old, stored));
expect(host.textContent).toContain('Selected metadata: next.json');
expect(button('Retain dataset').disabled).toBe(true);
await flush(() => click('Preview dataset'));
expect(request(storedPath).body).toEqual({ metadata: next });
});
test('explicit fresh preview replaces materialized data only after its response', async () => {
await mountPanel();
await storedPreview();
await flush(() => click('Preview dataset'));
expect(button('Retain dataset').disabled).toBe(true);
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
const input = {
...stored.input,
bars: stored.input.bars.map(bar => ({ ...bar, volume: bar.volume + 1 })),
};
const nextDataset = createDatasetV2(input);
const next = {
input,
preparation: {
...stored.preparation,
hash: nextDataset.manifest.hash,
manifest: nextDataset.manifest,
},
};
await flush(() => reply(request(storedPath), next));
await flush(() => click('Retain dataset'));
expect(request(retainPath).body).toEqual({
input: next.input,
expectedHash: next.preparation.hash,
});
expect(requests.filter(item => item.path === storedPath)).toHaveLength(2);
});
for (const [status, message] of [
[400, 'Unsupported metadata'],
[404, 'No stored bars'],
[503, 'EOD store unavailable'],
[500, 'Stored source unavailable'],
] as const) {
test(`stored ${status} exposes repair or retry without retention`, async () => {
await mountPanel();
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(storedMetadata));
await flush(() => click('Preview dataset'));
await flush(() => reply(request(storedPath), { error: message }, status));
expect(host.textContent).toContain(message);
expect(button('Preview dataset').disabled).toBe(false);
expect(button('Retain dataset').disabled).toBe(true);
expect(field('Source metadata JSON').disabled).toBe(false);
expect(retained).toHaveLength(0);
});
}
test('malformed stored success fails closed and keeps the metadata draft available for retry', async () => {
await mountPanel();
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(storedMetadata));
await flush(() => click('Preview dataset'));
await flush(() =>
reply(request(storedPath), {
input: { metadata: storedMetadata, bars: [] },
preparation: stored.preparation,
})
);
expect(host.textContent).toContain('stored source response could not be verified');
expect(host.textContent).toContain('Selected metadata: source.json');
expect(button('Retain dataset').disabled).toBe(true);
expect(button('Preview dataset').disabled).toBe(false);
});
test('stored exploratory evidence remains visible and retainable without canonical selection', async () => {
await mountPanel();
const exploratory = storedFixture();
await storedPreview(exploratory);
expect(host.textContent).toContain('Unavailable for canonical setup');
expect(host.textContent).toContain('Universe: unknown');
await flush(() => click('Retain dataset'));
await flush(() => reply(request(retainPath), { preparation: exploratory.preparation }));
expect(retained).toEqual([{ hash: exploratory.preparation.hash, available: false }]);
expect(states.at(-1)).toEqual({ busy: false, blocking: true });
});
test('unmount ignores stored materialization that completes after an aborted request', async () => {
await mountPanel();
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(storedMetadata));
await flush(() => click('Preview dataset'));
const old = request(storedPath);
await flush(() => root!.unmount());
root = undefined;
await flush(() => reply(old, stored));
expect(old.signal?.aborted).toBe(true);
expect(retained).toHaveLength(0);
expect(states.at(-1)).toEqual({ busy: false, blocking: false });
});
test('parent saves are synchronously blocked while stored source is pending; drafts remain intact', async () => {
let saves = 0;
await readySetup(async () => {
saves++;
});
await flush(() => {
edit('Backtest name', 'Stored draft');
edit('Fee rate', '0.02');
edit('Dataset input', 'stored-eod');
});
await flush(() => {
upload(storedMetadata);
host
.querySelector('form')!
.dispatchEvent(
new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event
);
});
expect(saves).toBe(0);
expect(button('Save canonical setup').disabled).toBe(true);
await flush(() => click('Preview dataset'));
await flush(() => reply(request(storedPath), stored));
expect(field('Backtest name').value).toBe('Stored draft');
expect(field('Fee rate').value).toBe('0.02');
expect(field('Canonical dataset').value).toBe(entry.hash);
await flush(() => click('Retain dataset'));
await flush(() => reply(request(retainPath), { preparation: stored.preparation }));
expect(field('Canonical dataset').value).toBe(stored.preparation.hash);
expect(saves).toBe(0);
expect(field('Fee rate').value).toBe('0.02');
});
test('authoritative parent reset fences late stored response and restores export mode', async () => {
const onSave = async () => {};
await readySetup(onSave);
await flush(() => edit('Dataset input', 'stored-eod'));
await flush(() => upload(storedMetadata));
await flush(() => click('Preview dataset'));
const old = request(storedPath);
await flush(() =>
root!.render(
createElement(
router.MemoryRouter,
null,
createElement(CanonicalSetup, { backtest: { ...definition, name: 'Reset' }, onSave })
)
)
);
await flush(() => reply(old, stored));
expect(field('Dataset input').value).toBe('export');
expect(field('Backtest name').value).toBe('Reset');
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
});
});