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();
});
});

View file

@ -0,0 +1,472 @@
import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { createHttpSecurity } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import type { IServiceContainer, MongoDBClient, QuestDBClient } from '@stock-bot/services';
import { parseFinancialDecimal, type HistoricalDatasetMetadataV2 } from '@stock-bot/types';
import {
NativeReplaySession,
prepareReplayLoad,
runReplayConformance,
} from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
import {
StorageService,
type HistoricalBar,
} from '../../apps/stock/orchestrator/src/services/StorageService';
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service';
import { prepareStoredDataset } from '../../apps/stock/web-api/src/services/stored-dataset-preparation';
import { nativeReplayFixture } from '../fixtures/native-replay';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('stored-source-test');
const token = 'stored-source-admin-fixture-not-a-real-secret';
type Mutable<T> = { -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K] };
type Row = {
symbol: string;
exchange: string;
eodSearchCode: string;
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
};
function at<T>(values: readonly T[], index = 0): T {
const value = values[index];
if (value === undefined) {
throw new Error('Missing fixture row');
}
return value;
}
function source(interval: '1m' | '5m' | '1h' = '1m') {
const f = nativeReplayFixture(3),
duration = { '1m': 60000, '5m': 300000, '1h': 3600000 }[interval];
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
f.dataset.manifest;
const metadata = structuredClone({
calendars,
series,
executionSeries,
bounds,
universe,
corporateActions,
}) as Mutable<HistoricalDatasetMetadataV2>;
const declared = at(metadata.series);
declared.interval = interval;
declared.source = { provider: 'eod', revision: 'operator-declared-source-v1' };
declared.availability = 'interval-end-assumption';
metadata.bounds.tradeStart = f.start + duration;
metadata.bounds.tradeEnd = f.start + 3 * duration;
at(metadata.corporateActions).end = metadata.bounds.tradeEnd;
const rows: Row[] = f.dataset.bars.map((bar, index) => ({
symbol: 'X0',
exchange: 'US',
eodSearchCode: 'X0.US',
timestamp: (f.start + index * duration) / 1000,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
}));
return { metadata, rows, f, duration };
}
function fixture(
find: (
collection: string,
filter: Record<string, unknown>,
options: Record<string, unknown>
) => Promise<Row[]> = async () => source().rows,
mongoAvailable = true
) {
const query = mock(async () => {
throw new Error('Preparation must not reach PostgreSQL');
});
const read = mock(find);
const mongodb = mongoAvailable ? ({ find: read } as unknown as MongoDBClient) : undefined;
const questdb = {
query: mock(async () => {
throw new Error('Unexpected provider fallback');
}),
} as unknown as QuestDBClient;
const container = {
logger,
mongodb,
questdb,
postgres: { query },
} as unknown as IServiceContainer;
const app = new Hono();
createHttpSecurity({
adminToken: token,
serviceToken: 'stored-source-service-fixture-not-a-real-secret',
readToken: 'stored-source-read-fixture-not-a-real-secret',
environment: 'test',
browserSessions: true,
}).mount(app);
app.route('/', createDatasetRoutes(container));
const request = (body: unknown, signal?: AbortSignal) =>
app.request('/api/v2/datasets/canonical/stored-source', {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
});
return {
request,
app,
read,
query,
questdb,
storage: new StorageService(container, mongodb, null, questdb),
container,
};
}
describe('stored EOD preparation', () => {
test('all supported intraday intervals use the actual strict EOD adapter once, exact UTC query bounds and unchanged raw observations', async () => {
for (const interval of ['1m', '5m', '1h'] as const) {
const input = source(interval);
const f = fixture(async () => [...input.rows].reverse());
const reply = await f.request({ metadata: input.metadata });
expect(reply.status).toBe(200);
expect(reply.headers.get('Cache-Control')).toBe('no-store');
const body = await reply.json();
expect(f.read).toHaveBeenCalledTimes(1);
expect(f.read.mock.calls[0]).toEqual([
{ '1m': 'eodIntraday1M', '5m': 'eodIntraday5M', '1h': 'eodIntraday1H' }[interval],
{
eodSearchCode: 'X0.US',
timestamp: {
$gte: input.metadata.bounds.warmupStart / 1000,
$lt: input.metadata.bounds.tradeEnd / 1000,
},
},
{
sort: { timestamp: 1 },
projection: {
symbol: 1,
exchange: 1,
eodSearchCode: 1,
timestamp: 1,
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
},
},
]);
expect(body.input.metadata).toEqual(input.metadata);
expect(body.input.bars.map((bar: { sourceSequence: number }) => bar.sourceSequence)).toEqual([
0, 1, 2,
]);
expect(body.input.bars.map((bar: { timestamp: number }) => bar.timestamp)).toEqual(
input.rows.map(row => row.timestamp * 1000)
);
expect(
body.input.bars.every(
(bar: Record<string, unknown>) =>
!Object.hasOwn(bar, 'vwap') && !Object.hasOwn(bar, 'availableAt')
)
).toBe(true);
expect(body.preparation).toEqual(previewDatasetPreparation({ input: body.input }));
const normalized = createDatasetV2(body.input);
expect(
normalized.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)
).toBe(true);
expect(normalized.manifest.parentDatasetHash).toBeNull();
expect(f.query).not.toHaveBeenCalled();
expect(f.questdb.query).not.toHaveBeenCalled();
}
});
test('complete metadata and supported scope reject before every provider read', async () => {
const f = fixture();
const bodies: unknown[] = [
null,
{},
{ metadata: {} },
{ metadata: source().metadata, extra: true },
];
const changes: Array<(metadata: Mutable<HistoricalDatasetMetadataV2>) => void> = [
metadata => {
at(metadata.series).source.provider = 'auto';
},
metadata => {
at(metadata.series).source.provider = 'questdb';
},
metadata => {
at(metadata.series).source.revision = '';
},
metadata => {
at(metadata.series).interval = '15m';
},
metadata => {
at(metadata.series).interval = '1d';
at(metadata.series).timestamp = 'session-date';
},
metadata => {
at(metadata.series).adjustment = 'provider-adjusted';
},
metadata => {
at(metadata.series).timestamp = 'interval-end';
},
metadata => {
at(metadata.series).availability = 'explicit';
},
metadata => {
metadata.corporateActions = [];
},
metadata => {
at(metadata.calendars).timeZone = 'private-invalid-timezone';
},
metadata => {
metadata.bounds.tradeStart = metadata.bounds.tradeEnd;
},
metadata => {
metadata.series.push({ ...at(metadata.series), id: 'X1.US:1m', instrumentId: 'X1.US' });
metadata.executionSeries.push({ instrumentId: 'X1.US', seriesId: 'X1.US:1m' });
metadata.universe.instrumentIds.push('X1.US');
metadata.corporateActions.push({ ...at(metadata.corporateActions), instrumentId: 'X1.US' });
},
];
for (const change of changes) {
const { metadata } = source();
change(metadata);
bodies.push({ metadata });
}
for (const body of bodies) {
const reply = await f.request(body);
expect(reply.status).toBe(400);
expect(reply.headers.get('Cache-Control')).toBe('no-store');
expect(await reply.text()).not.toContain('private-invalid-timezone');
}
expect(f.read).not.toHaveBeenCalled();
expect(f.query).not.toHaveBeenCalled();
expect(f.questdb.query).not.toHaveBeenCalled();
});
test('empty, unavailable, corrupt and transport failure cases stay distinct without fallback or private errors', async () => {
const body = { metadata: source().metadata };
const cases: Array<[ReturnType<typeof fixture>, number]> = [
[fixture(async () => []), 404],
[fixture(undefined, false), 503],
[
fixture(async () => {
throw new Error('private database connection details');
}),
500,
],
[
fixture(async () =>
source().rows.map((row, index) => (index === 0 ? { ...row, high: 0 } : row))
),
500,
],
[fixture(async () => source().rows.map(row => ({ ...row, exchange: 'WRONG' }))), 500],
[fixture(async () => [...source().rows, at(source().rows)]), 500],
];
for (const [f, status] of cases) {
const reply = await f.request(body);
expect(reply.status).toBe(status);
expect(reply.headers.get('Cache-Control')).toBe('no-store');
expect(await reply.text()).not.toContain('private database connection details');
expect(f.query).not.toHaveBeenCalled();
expect(f.questdb.query).not.toHaveBeenCalled();
}
});
test('valid unavailable declarations remain inspectable; partial intervals and declared session mismatches fail422', async () => {
const input = source();
input.metadata.universe.selection = 'unknown';
input.metadata.universe.asOf = null;
const reply = await fixture().request({ metadata: input.metadata });
expect(reply.status).toBe(200);
expect((await reply.json()).preparation).toMatchObject({
available: false,
manifest: { eligibility: 'exploratory' },
});
const partial = source();
partial.metadata.bounds.tradeEnd -= 30000;
const partialReply = await fixture().request({ metadata: partial.metadata });
expect(partialReply.status).toBe(422);
const wrongSession = source();
at(at(wrongSession.metadata.calendars).sessions).open += 30000;
const sessionReply = await fixture().request({ metadata: wrongSession.metadata });
expect(sessionReply.status).toBe(422);
expect(await sessionReply.text()).toContain('declared complete dataset metadata');
});
test('metadata is detached and deeply frozen before await; later caller/store mutations cannot alter returned captured bytes', async () => {
const initial = source(),
expectedMetadata = structuredClone(initial.metadata);
let release: (() => void) | undefined;
const gate = new Promise<void>(resolve => {
release = resolve;
});
const f = fixture(async () => {
await gate;
return initial.rows;
});
const promise = prepareStoredDataset(
{ metadata: initial.metadata },
f.storage,
new AbortController().signal
);
expect(f.read).toHaveBeenCalledTimes(1);
at(initial.metadata.series).source.revision = 'later source revision';
initial.metadata.bounds.tradeEnd += initial.duration;
if (!release) {
throw new Error('Missing fixture barrier');
}
release();
const prepared = await promise;
expect(prepared.input.metadata).toEqual(expectedMetadata);
expect(Object.isFrozen(prepared)).toBe(true);
expect(Object.isFrozen(prepared.input.metadata.calendars[0]?.sessions)).toBe(true);
expect(Object.isFrozen(prepared.input.bars[0])).toBe(true);
at(initial.rows).close = 10.5;
expect(prepared.input.bars[0]?.close).toBe(11);
expect(prepared.preparation).toEqual(previewDatasetPreparation({ input: prepared.input }));
});
test('initial and late cancellation return499 even when underlying Mongo finishes; cancelled calls write nothing', async () => {
const initial = new AbortController();
initial.abort(new Error('private abort reason'));
const f = fixture();
const early = await f.request({ metadata: source().metadata }, initial.signal);
expect(early.status).toBe(499);
expect(early.headers.get('Cache-Control')).toBe('no-store');
expect(f.read).not.toHaveBeenCalled();
const controller = new AbortController();
let release: (() => void) | undefined;
const gate = new Promise<void>(resolve => {
release = resolve;
});
let entered: (() => void) | undefined;
const started = new Promise<void>(resolve => {
entered = resolve;
});
const slow = fixture(async () => {
entered?.();
await gate;
return source().rows;
});
const pending = slow.request({ metadata: source().metadata }, controller.signal);
await started;
controller.abort(new Error('private abort reason'));
if (!release) {
throw new Error('Missing fixture barrier');
}
release();
const late = await pending;
expect(late.status).toBe(499);
expect(late.headers.get('Cache-Control')).toBe('no-store');
expect(await late.text()).not.toContain('private abort reason');
expect(slow.read).toHaveBeenCalledTimes(1);
expect(slow.query).not.toHaveBeenCalled();
});
test('the focused adapter independently refuses wrong source, symbol, interpolation and out-of-range rows', async () => {
const input = source();
const f = fixture();
const baseline = await f.storage.getHistoricalBars(
'X0.US',
new Date(input.metadata.bounds.warmupStart),
new Date(input.metadata.bounds.tradeEnd),
'1m',
{ adjustment: 'raw', timestamp: 'utc-instant' },
undefined,
'eod'
);
const changes: Array<(row: HistoricalBar) => HistoricalBar> = [
row => ({ ...row, source: 'questdb' }),
row => ({ ...row, symbol: 'WRONG.US' }),
row => ({ ...row, interpolated: true }),
row => ({ ...row, timestamp: new Date(input.metadata.bounds.tradeEnd) }),
];
for (const change of changes) {
await expect(
prepareStoredDataset(
{ metadata: input.metadata },
{ getHistoricalBars: async () => [change(at(baseline))] },
new AbortController().signal
)
).rejects.toThrow('inconsistent bar identity or range');
}
});
test('actual stored adapter output preserves native next-open costs/equity and never reveals observations before interval end', async () => {
const input = source(),
f = fixture(async () => input.rows);
const captured = await prepareStoredDataset(
{ metadata: input.metadata },
f.storage,
new AbortController().signal
);
const dataset = createDatasetV2(captured.input);
let decisions = 0;
const { result } = runReplayConformance(
new NativeReplaySession(prepareReplayLoad(dataset, input.f.config)),
(_owner, context, observations) => {
decisions++;
expect(
observations.every(
bar => bar.available_at === bar.interval_end && bar.available_at <= context.barrier.at
)
).toBe(true);
return context.barrier.at === input.f.start + input.f.minute
? {
mode: 'target',
targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }],
}
: { mode: 'target', targets: [] };
}
);
expect(decisions).toBe(2);
expect(String(result.view.portfolio.cash)).toBe('9975.76000000');
expect(String(result.view.equity)).toBe('10005.76000000');
expect<unknown>(result.view.portfolio.fees).toEqual([{ ownerId: 'A', amount: '0.24000000' }]);
});
test('mounted security denies read-token writes and untrusted browser origins', async () => {
const f = fixture();
const payload = JSON.stringify({ metadata: source().metadata });
const denied = await f.app.request('/api/v2/datasets/canonical/stored-source', {
method: 'POST',
headers: {
Authorization: 'Bearer stored-source-read-fixture-not-a-real-secret',
'Content-Type': 'application/json',
},
body: payload,
});
expect(denied.status).toBe(403);
const login = await f.app.request('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: 'http://localhost' },
body: JSON.stringify({ token }),
});
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
if (!cookie) {
throw new Error('Missing authenticated session');
}
const browser = (origin?: string) =>
f.app.request('/api/v2/datasets/canonical/stored-source', {
method: 'POST',
headers: {
Cookie: cookie,
'Content-Type': 'application/json',
...(origin ? { Origin: origin } : {}),
},
body: payload,
});
expect((await browser()).status).toBe(403);
expect((await browser('https://foreign.invalid')).status).toBe(403);
expect(f.read).not.toHaveBeenCalled();
expect((await browser('http://localhost')).status).toBe(200);
expect(f.read).toHaveBeenCalledTimes(1);
});
});