stock-bot/test/integration/stored-dataset-preparation.test.ts

472 lines
17 KiB
TypeScript

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