feat(research): inspect scoped stored market data (RP01)

This commit is contained in:
Boki 2026-10-27 00:25:19 -04:00
parent b4ac6460ef
commit 5bfaf37d08
12 changed files with 1592 additions and 3 deletions

View file

@ -2341,6 +2341,133 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
}
});
test('stored_source_inspection_browser_keeps_utc_scope_and_research_state_unchanged', async () => {
const f = await fixture();
try {
await f.login();
const { id, dataset } = await createCanonicalInBrowser(f, 'Stored source inspection');
const rows = dataset.bars.map((bar, index) => ({
eodSearchCode: 'X0.US',
symbol: 'X0',
exchange: 'US',
timestamp: bar.intervalStart / 1000,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: index === 0 ? -1 : bar.volume,
}));
f.setStoredEodBars('eodIntraday1M', rows);
const first = Math.min(...rows.map(row => row.timestamp)) * 1000;
const last = Math.max(...rows.map(row => row.timestamp)) * 1000;
const coverageRequests: URL[] = [];
// Mongo aggregation has separate real-server coverage. This response fixture
// drives the browser picker; the following inspection uses the real HTTP API.
await f.page.route(/\/api\/v2\/datasets\/stored-eod\/coverage(?:\?.*)?$/, route => {
coverageRequests.push(new URL(route.request().url()));
return route.fulfill({
json: {
version: 'stored-eod-coverage/v1',
observedAt: first,
query: { instrumentId: 'X0.US', interval: '1m' },
series: [
{
instrumentId: 'X0.US',
interval: '1m',
rowCount: rows.length,
firstTimestamp: first,
lastTimestamp: last,
invalidTimestampRows: 0,
},
],
},
});
});
const template = await f.request(`/api/v2/backtests/${id}`);
const templateWrites: string[] = [];
f.page.on('request', request => {
if (
request.method() === 'PUT' &&
new URL(request.url()).pathname === `/api/v2/backtests/${id}`
) {
templateWrites.push(request.url());
}
});
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM backtest_datasets) AS datasets,
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
).rows[0];
const before = await counts();
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod');
const inspector = f.page.getByRole('region', { name: 'Stored source inspection', exact: true });
await inspector.waitFor();
expect(coverageRequests).toHaveLength(0);
await inspector.getByLabel('Inspect instrument', { exact: true }).fill('X0.US');
await inspector.getByLabel('Inspect timeframe', { exact: true }).selectOption('1m');
await inspector.getByLabel('Inspect instrument', { exact: true }).press('Enter');
expect(coverageRequests).toHaveLength(0);
await inspector.getByRole('button', { name: 'Load selected coverage', exact: true }).click();
await inspector.getByRole('button', { name: 'Use coverage dates', exact: true }).waitFor();
expect(coverageRequests).toHaveLength(1);
expect(Object.fromEntries(coverageRequests[0]!.searchParams)).toEqual({
instrumentId: 'X0.US',
interval: '1m',
});
expect(await inspector.getByLabel('Inspect start UTC', { exact: true }).inputValue()).toBe('');
expect(await inspector.getByLabel('Inspect end UTC', { exact: true }).inputValue()).toBe('');
await inspector.getByRole('button', { name: 'Use coverage dates', exact: true }).click();
expect(await inspector.getByLabel('Inspect instrument', { exact: true }).inputValue()).toBe(
'X0.US'
);
expect(await inspector.getByLabel('Inspect timeframe', { exact: true }).inputValue()).toBe(
'1m'
);
const inspecting = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/datasets/stored-eod/inspect')
);
await inspector.getByRole('button', { name: 'Inspect source window', exact: true }).click();
const response = await inspecting;
expect(response.status()).toBe(200);
expect(response.request().postDataJSON()).toEqual({
instrumentId: 'X0.US',
interval: '1m',
start: first,
end: last + 60000,
});
const inspected = await response.json();
expect(inspected.invalidRows).toBe(1);
expect(inspected.rowCount).toBe(rows.length);
await inspector.getByText('Invalid volume: 1 rows', { exact: true }).waitFor();
await visible(f.page, /No rows were changed or excluded/);
expect(
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).isDisabled()
).toBe(true);
expect(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()).toBe(
dataset.manifest.hash
);
expect(await counts()).toEqual(before);
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(template);
expect(templateWrites).toEqual([]);
expect(f.storedSourceReads).toEqual([
{
collection: 'eodIntraday1M',
filter: {
eodSearchCode: 'X0.US',
timestamp: { $gte: first / 1000, $lt: (last + 60000) / 1000 },
},
},
]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_reopen', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());

View file

@ -0,0 +1,295 @@
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement } from 'react';
import type { Root } from 'react-dom/client';
import type {
StoredSourceCoverage,
StoredSourceInspection,
} from '@stock-bot/stock-config/stored-source';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
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 Inspector: typeof import('../../apps/stock/web-app/src/features/backtest/components/StoredSourceInspector').StoredSourceInspector;
let root: Root | undefined;
let host: HTMLDivElement;
const start = Date.parse('2024-10-01T13:30:00Z');
const coverage: StoredSourceCoverage = {
version: 'stored-eod-coverage/v1',
observedAt: start,
query: { instrumentId: 'AAPL.US', interval: '5m' },
series: [
{
instrumentId: 'AAPL.US',
interval: '5m',
rowCount: 78,
firstTimestamp: start,
lastTimestamp: start + 385 * 60000,
invalidTimestampRows: 0,
},
],
};
const result: StoredSourceInspection = {
version: 'stored-eod-inspection/v1',
observedAt: start,
query: { instrumentId: 'AAPL.US', interval: '5m', start, end: start + 390 * 60000 },
rowCount: 78,
invalidRows: 1,
nullVolumeRows: 1,
duplicateRows: 0,
firstTimestamp: start,
lastTimestamp: start + 385 * 60000,
days: [{ date: '2024-10-01', rowCount: 78, invalidRows: 1 }],
issues: [{ code: 'null-volume', rowCount: 1, timestamps: [start] }],
};
interface Pending {
path: string;
search: string;
init: RequestInit | undefined;
resolve: (response: Response) => void;
reject: (error: Error) => void;
}
const requests: Pending[] = [];
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'));
({ StoredSourceInspector: Inspector } = await import(
'../../apps/stock/web-app/src/features/backtest/components/StoredSourceInspector'
));
});
beforeEach(() => {
requests.length = 0;
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((resolve, reject) =>
requests.push({
path: new URL(String(url)).pathname,
search: new URL(String(url)).search,
init,
resolve,
reject,
})
)) as unknown as typeof browser.fetch;
});
async function flush(fn: () => void = () => {}) {
await act(async () => {
fn();
await Promise.resolve();
});
}
afterEach(async () => {
if (root) {
await flush(() => root!.unmount());
}
root = undefined;
host.remove();
});
afterAll(async () => {
await browser.happyDOM.close();
for (const key of keys) {
const value = originals.get(key);
if (value) {
Object.defineProperty(globalThis, key, value);
} else {
Reflect.deleteProperty(globalThis, key);
}
}
});
function button(label: string) {
const found = [...host.querySelectorAll('button')].find(value => value.textContent === label);
if (!found) {
throw new Error(`Missing ${label}`);
}
return found;
}
function edit(label: string, value: string) {
const input = host.querySelector(`[aria-label="${label}"]`) as HTMLInputElement;
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
input,
value
);
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
}
async function mount(disabled = false) {
root = createRoot(host);
await flush(() => root!.render(createElement(Inspector, { disabled })));
}
async function choose() {
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Load selected coverage').click());
await flush(() => requests.at(-1)!.resolve(Response.json(coverage)));
await flush(() => button('Use coverage dates').click());
}
test('coverage selects an explicit UTC window and inspection displays quality without writing or retaining', async () => {
await mount();
expect(requests).toHaveLength(0);
await flush(() => edit('Inspect instrument', 'AAPL.US'));
expect(requests).toHaveLength(0);
await flush(() => button('Load selected coverage').click());
expect(host.textContent).toContain('Loading stored coverage');
expect(requests[0]!.search).toBe('?instrumentId=AAPL.US&interval=5m');
await flush(() => requests[0]!.resolve(Response.json(coverage)));
expect(host.textContent).toContain('78');
await flush(() => button('Use coverage dates').click());
await flush(() => button('Inspect source window').click());
const request = requests[1]!;
expect(request.path).toBe('/api/v2/datasets/stored-eod/inspect');
expect(JSON.parse(String(request.init?.body))).toEqual(result.query);
expect(request.init?.credentials).toBe('include');
await flush(() => request.resolve(Response.json(result)));
expect(host.textContent).toContain('1 missing/null volumes');
expect(host.textContent).toContain('No rows were changed or excluded');
expect(host.textContent).toContain('2024-10-01T13:30:00.000Z');
expect(requests.every(value => value.path.includes('/stored-eod/'))).toBe(true);
});
test('editing or cancelling invalidates late inspection replies and never displays a different window', async () => {
await mount();
await choose();
await flush(() => button('Inspect source window').click());
const old = requests.at(-1)!;
await flush(() => edit('Inspect instrument', 'MSFT.US'));
expect(old.init?.signal?.aborted).toBe(true);
expect(host.textContent).not.toContain('Stored bar coverage (UTC)');
await flush(() => old.resolve(Response.json(result)));
expect(host.querySelector('[aria-label="Source inspection result"]')).toBeNull();
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Inspect source window').click());
const cancelled = requests.at(-1)!;
await flush(() => button('Cancel inspection').click());
expect(cancelled.init?.signal?.aborted).toBe(true);
await flush(() => cancelled.resolve(Response.json(result)));
expect(host.querySelector('[aria-label="Source inspection result"]')).toBeNull();
await flush(() => button('Inspect source window').click());
const wrong = requests.at(-1)!;
await flush(() =>
wrong.resolve(Response.json({ ...result, query: { ...result.query, instrumentId: 'MSFT.US' } }))
);
expect(host.querySelector('[role="alert"]')?.textContent).toContain(
'differs from the selected window'
);
});
test('empty/error states are visible and retry is explicit; unmount aborts outstanding work', async () => {
await mount();
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Load selected coverage').click());
await flush(() => requests.at(-1)!.resolve(Response.json({ ...coverage, series: [] })));
expect(host.textContent).toContain('No stored bars found for AAPL.US 5m');
await flush(() => button('Load selected coverage').click());
await flush(() =>
requests.at(-1)!.resolve(Response.json({ error: 'Store offline' }, { status: 503 }))
);
expect(host.querySelector('[role="alert"]')?.textContent).toBe('Store offline');
expect(requests).toHaveLength(2);
await choose();
await flush(() => button('Inspect source window').click());
await flush(() =>
requests.at(-1)!.resolve(
Response.json({
...result,
rowCount: 0,
invalidRows: 0,
nullVolumeRows: 0,
duplicateRows: 0,
firstTimestamp: null,
lastTimestamp: null,
days: [],
issues: [],
})
)
);
expect(host.textContent).toContain('No stored bars in this window');
await flush(() => button('Load selected coverage').click());
const pending = requests.at(-1)!;
await flush(() => root!.unmount());
root = undefined;
expect(pending.init?.signal?.aborted).toBe(true);
});
test('disabled preparation cannot start diagnostics', async () => {
await mount(true);
expect(button('Load selected coverage').disabled).toBe(true);
expect(button('Inspect source window').disabled).toBe(true);
await flush(() => button('Load selected coverage').click());
expect(requests).toHaveLength(0);
});
test('coverage scope changes fence stale replies and mismatched coverage is rejected', async () => {
await mount();
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Load selected coverage').click());
const stale = requests.at(-1)!;
await flush(() => edit('Inspect instrument', 'MSFT.US'));
expect(stale.init?.signal?.aborted).toBe(true);
await flush(() => stale.resolve(Response.json(coverage)));
expect(host.textContent).not.toContain('Stored bar coverage (UTC)');
await flush(() => button('Load selected coverage').click());
await flush(() => requests.at(-1)!.resolve(Response.json(coverage)));
expect(host.querySelector('[role="alert"]')?.textContent).toContain(
'differs from the selected instrument and timeframe'
);
expect(host.textContent).not.toContain('Stored bar coverage (UTC)');
});
test('diagnostic edits and Enter do not dirty or submit the containing canonical setup form', async () => {
let changes = 0;
let submissions = 0;
root = createRoot(host);
await flush(() =>
root!.render(
createElement(
'form',
{
onChange: () => {
changes++;
},
onSubmit: (event: { preventDefault(): void }) => {
event.preventDefault();
submissions++;
},
},
createElement(Inspector, { disabled: false })
)
)
);
await flush(() => edit('Inspect instrument', 'AAPL.US'));
expect(changes).toBe(0);
const input = host.querySelector('[aria-label="Inspect instrument"]')!;
const enter = new browser.KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true,
});
await flush(() => {
input.dispatchEvent(enter as unknown as Event);
});
expect(enter.defaultPrevented).toBe(true);
expect(submissions).toBe(0);
expect(requests).toHaveLength(0);
const buttonEnter = new browser.KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true,
});
await flush(() => {
button('Load selected coverage').dispatchEvent(buttonEnter as unknown as Event);
});
expect(buttonEnter.defaultPrevented).toBe(false);
const selectEnter = new browser.KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true,
});
await flush(() => {
host
.querySelector('[aria-label="Inspect timeframe"]')!
.dispatchEvent(selectEnter as unknown as Event);
});
expect(selectEnter.defaultPrevented).toBe(false);
});

View file

@ -0,0 +1,240 @@
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 } from '@stock-bot/services';
import {
storedSourceCoverageSchema,
storedSourceInspectionSchema,
} from '@stock-bot/stock-config/stored-source';
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
import {
inspectStoredSource,
storedSourceCoverage,
} from '../../apps/stock/web-api/src/services/stored-source-inspection';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('source-inspection-test');
const start = Date.parse('2024-10-01T13:30:00Z');
const selection = { instrumentId: 'AAPL.US', interval: '5m' } as const;
const coveragePath = 'coverage?instrumentId=AAPL.US&interval=5m';
const query = { ...selection, start, end: start + 900000 };
const row = {
eodSearchCode: 'AAPL.US',
symbol: 'AAPL',
exchange: 'US',
timestamp: start / 1000,
open: 10,
high: 12,
low: 9,
close: 11,
volume: 100,
};
function fixture(rows: Record<string, unknown>[] = [row]) {
const find = mock(async () => structuredClone(rows));
const aggregate = mock(async (collection: string, _pipeline: Record<string, unknown>[]) =>
collection === 'eodIntraday5M'
? [
{
_id: null,
rowCount: 4,
firstTimestamp: start / 1000,
lastTimestamp: start / 1000 + 600,
invalidTimestampRows: 1,
},
]
: []
);
const database = mock(async () => {
throw new Error('No PostgreSQL writes or reads allowed');
});
const store = { find, aggregate } as unknown as MongoDBClient;
const app = new Hono();
createHttpSecurity({
adminToken: 'source-admin-fixture-not-a-real-secret',
serviceToken: 'source-service-fixture-not-a-real-secret',
readToken: 'source-read-fixture-not-a-real-secret',
environment: 'test',
browserSessions: true,
}).mount(app);
app.route(
'/',
createDatasetRoutes({
logger,
mongodb: store,
postgres: { query: database },
} as unknown as IServiceContainer)
);
const request = (
path: string,
body?: unknown,
token: string | null = 'source-admin-fixture-not-a-real-secret',
signal?: AbortSignal
) =>
app.request(`/api/v2/datasets/stored-eod/${path}`, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
'Content-Type': 'application/json',
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
signal,
});
return { store, app, find, aggregate, database, request };
}
describe('stored EOD source discovery and diagnostics', () => {
test('coverage reads only the explicitly selected instrument and collection with an indexable first match', async () => {
const f = fixture();
const response = await f.request(coveragePath);
expect(response.status).toBe(200);
expect(response.headers.get('Cache-Control')).toBe('no-store');
const value = storedSourceCoverageSchema.parse(await response.json());
expect(value.series).toEqual([
{
instrumentId: 'AAPL.US',
interval: '5m',
rowCount: 4,
firstTimestamp: start,
lastTimestamp: start + 600000,
invalidTimestampRows: 1,
},
]);
expect(value.query).toEqual(selection);
expect(f.aggregate).toHaveBeenCalledTimes(1);
expect(f.aggregate.mock.calls[0]?.[0]).toBe('eodIntraday5M');
expect(f.aggregate.mock.calls[0]?.[1]?.[0]).toEqual({ $match: { eodSearchCode: 'AAPL.US' } });
expect(f.find).not.toHaveBeenCalled();
expect(f.database).not.toHaveBeenCalled();
});
test('coverage requires an exact selection before any store access and preserves an empty selected series', async () => {
const f = fixture();
for (const path of [
'coverage',
'coverage?instrumentId=AAPL.US',
'coverage?instrumentId=AAPL&interval=5m',
'coverage?instrumentId=AAPL.US&interval=15m',
'coverage?instrumentId=AAPL.US&interval=5m&all=true',
]) {
expect((await f.request(path)).status).toBe(400);
}
expect(f.aggregate).not.toHaveBeenCalled();
f.aggregate.mockImplementation(async () => []);
expect(await (await f.request(coveragePath)).json()).toMatchObject({
query: selection,
series: [],
});
expect(f.aggregate).toHaveBeenCalledTimes(1);
expect(f.database).not.toHaveBeenCalled();
});
test('field problems, identity and duplicate rows remain visible without altering source prices', async () => {
const rows = [
row,
{ ...row, volume: null },
{ ...row, timestamp: start / 1000 + 300, close: 100 },
{ ...row, timestamp: start / 1000 + 600, exchange: 'OTHER', volume: -1 },
{ ...row, timestamp: 'not-an-instant' },
{ ...row, timestamp: query.end / 1000 },
];
const before = structuredClone(rows);
const f = fixture(rows);
const response = await f.request('inspect', query);
expect(response.status).toBe(200);
const value = storedSourceInspectionSchema.parse(await response.json());
expect(value).toMatchObject({
query,
rowCount: 6,
invalidRows: 6,
nullVolumeRows: 1,
duplicateRows: 1,
firstTimestamp: start,
lastTimestamp: query.end,
});
expect(value.issues.map(issue => issue.code)).toEqual([
'null-volume',
'invalid-prices',
'identity-mismatch',
'invalid-volume',
'invalid-timestamp',
'outside-range',
'duplicate-timestamp',
]);
expect(value.issues.find(issue => issue.code === 'duplicate-timestamp')).toMatchObject({
rowCount: 2,
timestamps: [start, start],
});
expect(value.days).toEqual([{ date: '2024-10-01', rowCount: 5, invalidRows: 5 }]);
expect(rows).toEqual(before);
expect(f.database).not.toHaveBeenCalled();
expect(f.find.mock.calls[0]?.slice(0, 2)).toMatchObject([
'eodIntraday5M',
{ eodSearchCode: 'AAPL.US', timestamp: { $gte: start / 1000, $lt: query.end / 1000 } },
]);
});
test('invalid queries reject before any store access; supported empty windows are explicit', async () => {
const f = fixture([]);
for (const invalid of [
{ ...query, end: start },
{ ...query, interval: '15m' },
{ ...query, instrumentId: 'AAPL' },
{ ...query, start: 1.5 },
{ ...query, extra: true },
]) {
expect((await f.request('inspect', invalid)).status).toBe(400);
}
expect(f.find).not.toHaveBeenCalled();
const empty = await f.request('inspect', query);
expect(await empty.json()).toMatchObject({
rowCount: 0,
invalidRows: 0,
firstTimestamp: null,
lastTimestamp: null,
days: [],
issues: [],
});
});
test('ordinary authentication roles remain enforced and source failures are sanitized', async () => {
const f = fixture();
expect((await f.request(coveragePath, undefined, null)).status).toBe(401);
expect(
(await f.request(coveragePath, undefined, 'source-read-fixture-not-a-real-secret')).status
).toBe(200);
expect(
(await f.request('inspect', query, 'source-read-fixture-not-a-real-secret')).status
).toBe(403);
expect(f.find).not.toHaveBeenCalled();
f.find.mockImplementation(async () => {
throw new Error('private transport detail');
});
const failure = await f.request('inspect', query);
expect(failure.status).toBe(500);
expect(await failure.json()).toEqual({ error: 'Stored source inspection unavailable' });
});
test('absent storage is unavailable and cancellation fences queries and returned data', async () => {
const abort = new AbortController();
abort.abort(new Error('cancelled'));
const f = fixture();
await expect(inspectStoredSource(f.store, query, abort.signal)).rejects.toThrow('cancelled');
await expect(storedSourceCoverage(f.store, selection, abort.signal)).rejects.toThrow(
'cancelled'
);
expect(f.find).not.toHaveBeenCalled();
expect(f.aggregate).not.toHaveBeenCalled();
await expect(
inspectStoredSource(null, query, new AbortController().signal)
).rejects.toMatchObject({ status: 503 });
const during = new AbortController();
f.find.mockImplementation(async () => {
during.abort(new Error('during query'));
return [row];
});
await expect(inspectStoredSource(f.store, query, during.signal)).rejects.toThrow(
'during query'
);
const httpAbort = new AbortController();
f.find.mockImplementation(async () => {
httpAbort.abort();
return [row];
});
expect((await f.request('inspect', query, undefined, httpAbort.signal)).status).toBe(499);
});
});

View file

@ -0,0 +1,91 @@
/** Read-only aggregation regression; no collections, source records or credentials are written. */
import { describe, expect, test } from 'bun:test';
import { Decimal128, Double, Int32, Long, MongoClient } from 'mongodb';
import type { MongoDBClient } from '@stock-bot/services';
import { storedSourceCoverage } from '../../apps/stock/web-api/src/services/stored-source-inspection';
const url = process.env.SOURCE_TEST_MONGODB_URL;
describe.skipIf(!url)('stored source BSON timestamp coverage on MongoDB', () => {
test('coverage agrees with the strict JS reader for real BSON types and time bounds', async () => {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Explicit stock_bot_safety MongoDB test URL required');
}
const client = new MongoClient(url, { serverSelectionTimeoutMS: 5000 });
try {
await client.connect();
const good = [new Int32(1727789400), new Double(1727789700), Long.fromNumber(1727790000)];
const bad = [
Decimal128.fromString('1727789400'),
null,
'1727789400',
new Double(1727789400.5),
new Double(-1),
Long.fromString('8640000000001'),
new Double(NaN),
new Double(Infinity),
];
// A collection-free $documents source runs the exact production aggregation on
// actual BSON values. The adapter seam substitutes only where records originate.
const store: Pick<MongoDBClient, 'aggregate' | 'find'> = {
aggregate: async <T extends Record<string, unknown>>(
collection: string,
pipeline: Record<string, unknown>[]
) => {
const docs =
collection === 'eodIntraday5M'
? [
...good.map(timestamp => ({ eodSearchCode: 'VALID.US', timestamp })),
...bad.map(timestamp => ({ eodSearchCode: 'INVALID.US', timestamp })),
]
: [];
return client
.db()
.aggregate<T>([{ $documents: docs }, ...pipeline])
.toArray();
},
find: async () => {
throw new Error('Coverage must not query source rows');
},
};
const signal = new AbortController().signal;
const invalid = await storedSourceCoverage(
store,
{ instrumentId: 'INVALID.US', interval: '5m' },
signal
);
expect(invalid.series).toEqual([
{
instrumentId: 'INVALID.US',
interval: '5m',
rowCount: bad.length,
firstTimestamp: null,
lastTimestamp: null,
invalidTimestampRows: bad.length,
},
]);
const valid = await storedSourceCoverage(
store,
{ instrumentId: 'VALID.US', interval: '5m' },
signal
);
expect(valid.series).toEqual([
{
instrumentId: 'VALID.US',
interval: '5m',
rowCount: good.length,
firstTimestamp: 1727789400000,
lastTimestamp: 1727790000000,
invalidTimestampRows: 0,
},
]);
const empty = await storedSourceCoverage(
store,
{ instrumentId: 'MISSING.US', interval: '5m' },
signal
);
expect(empty.series).toEqual([]);
} finally {
await client.close();
}
});
});