stock-bot/test/unit/normalization-bar-spans.test.ts

561 lines
21 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import type { MongoDBClient } from '@stock-bot/services';
import {
assertReadOnlyBarSpanPipeline,
BAR_SPAN_COLLECTIONS,
BarSpanIndex,
buildBarSpansPipeline,
buildEodBarSpansPipeline,
buildQmBarSpansPipeline,
computeBarSpans,
normalizeBarDate,
spansOverlap,
type BarSpanAggregateOptions,
type BarSpanAggregateReader,
type GroupedBarSpanRow,
} from '../../apps/stock/data-pipeline/src/normalization/bar-spans';
// Compile-time structural compatibility check: MongoDBClient must satisfy BarSpanAggregateReader.
const _assertMongoClientAssignable: (client: MongoDBClient) => BarSpanAggregateReader = client =>
client;
void _assertMongoClientAssignable;
const ALLOWED_STAGES = new Set(['$match', '$group', '$project', '$sort']);
function assertPipelineStrictlyReadOnly(pipeline: readonly Record<string, unknown>[]): void {
expect(pipeline.length).toBeGreaterThan(0);
assertReadOnlyBarSpanPipeline(pipeline);
const inspect = (node: unknown): void => {
if (node === null || typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (const item of node) {
inspect(item);
}
return;
}
for (const [key, val] of Object.entries(node)) {
expect(key.toLowerCase()).not.toBe('$out');
expect(key.toLowerCase()).not.toBe('$merge');
inspect(val);
}
};
for (const stage of pipeline) {
const keys = Object.keys(stage);
expect(keys.length).toBeGreaterThan(0);
for (const key of keys) {
expect(ALLOWED_STAGES.has(key)).toBe(true);
}
inspect(stage);
}
}
describe('normalizeBarDate', () => {
test('normalizes Date instances, YYYY-MM-DD strings, and timezone-qualified ISO timestamps to UTC YYYY-MM-DD', () => {
expect(normalizeBarDate('2024-06-08')).toBe('2024-06-08');
expect(normalizeBarDate(' 2024-02-29 ')).toBe('2024-02-29');
expect(normalizeBarDate(new Date('2022-06-08T00:00:00.000Z'))).toBe('2022-06-08');
expect(normalizeBarDate(new Date(Date.UTC(2012, 4, 18, 23, 59, 59)))).toBe('2012-05-18');
expect(normalizeBarDate('2024-06-07T23:30:00-04:00')).toBe('2024-06-08');
expect(normalizeBarDate('2024-06-08T01:30:00+04:00')).toBe('2024-06-07');
expect(normalizeBarDate('2024-06-07T23:30:00.123456-0400')).toBe('2024-06-08');
expect(normalizeBarDate('2024-06-08T12:00:00Z')).toBe('2024-06-08');
expect(normalizeBarDate('2024-06-08 00:00Z')).toBe('2024-06-08');
});
test('rejects calendar rollovers, timezone-less datetimes, invalid Date objects, and non-date values', () => {
const invalidInputs: unknown[] = [
null,
undefined,
'',
' ',
1717804800000,
{},
new Date(Number.NaN),
'2023-02-29',
'2024-02-30',
'2024-04-31',
'2024-13-01',
'2024-00-10',
'0000-01-01',
'2024-6-8',
'2024/06/08',
'2024-06-08T12:00:00',
'2024-06-08T24:00:00Z',
'2024-06-08T12:60:00Z',
'2024-06-08T12:00:00+25:00',
'not-a-date',
];
for (const input of invalidInputs) {
expect(normalizeBarDate(input)).toBeNull();
}
});
});
describe('bar-span pipeline builders and safety guards', () => {
test('generated pipelines for eod and qm (full and targeted) contain only read-only stages and no $out/$merge', () => {
const eodFull = buildEodBarSpansPipeline();
const eodTargeted = buildEodBarSpansPipeline(['AAPL.US', 'FB.US']);
const qmFull = buildQmBarSpansPipeline();
const qmTargeted = buildQmBarSpansPipeline(['AAPL', 'VOY:CNX']);
const viaDispatchEod = buildBarSpansPipeline('eod');
const viaDispatchQm = buildBarSpansPipeline('qm', ['VOY:CC']);
for (const pipeline of [
eodFull,
eodTargeted,
qmFull,
qmTargeted,
viaDispatchEod,
viaDispatchQm,
]) {
assertPipelineStrictlyReadOnly(pipeline);
}
expect(eodFull).toEqual([
{
$group: {
_id: '$eodSearchCode',
firstBarDate: { $min: '$date' },
lastBarDate: { $max: '$date' },
barCount: { $sum: 1 },
},
},
]);
expect(eodTargeted[0]).toEqual({ $match: { eodSearchCode: { $in: ['AAPL.US', 'FB.US'] } } });
expect(qmFull[0]).toEqual({ $sort: { qmSearchCode: 1, date: 1 } });
expect(qmTargeted[0]).toEqual({ $match: { qmSearchCode: { $in: ['AAPL', 'VOY:CNX'] } } });
});
test('assertReadOnlyBarSpanPipeline rejects $out, $merge (top-level and nested), and disallowed stages', () => {
expect(() => assertReadOnlyBarSpanPipeline([{ $out: 'stolen' }])).toThrow(/\$out/);
expect(() => assertReadOnlyBarSpanPipeline([{ $merge: { into: 'target' } }])).toThrow(
/\$merge/
);
expect(() =>
assertReadOnlyBarSpanPipeline([
{ $match: { nested: [{ $merge: { into: 'sneaky' } }] } },
])
).toThrow(/\$merge/);
expect(() =>
assertReadOnlyBarSpanPipeline([
{ $project: { sub: { $out: 'sneaky' } } },
])
).toThrow(/\$out/);
expect(() => assertReadOnlyBarSpanPipeline([{ $lookup: { from: 'other' } }])).toThrow(
/not an allowed read-only stage/
);
expect(() => assertReadOnlyBarSpanPipeline([{}])).toThrow(/empty/);
});
});
describe('computeBarSpans', () => {
test('happy path: aggregates eod and qm spans with Date and ISO string inputs', async () => {
const calls: Array<{
collection: string;
pipeline: Record<string, unknown>[];
options?: BarSpanAggregateOptions;
}> = [];
const reader: BarSpanAggregateReader = {
async aggregate<T extends Record<string, unknown>>(
collectionName: string,
pipeline: Record<string, unknown>[],
options?: BarSpanAggregateOptions
): Promise<T[]> {
calls.push({ collection: collectionName, pipeline, options });
if (collectionName === BAR_SPAN_COLLECTIONS.eod.collection) {
const rows: GroupedBarSpanRow[] = [
{
_id: 'AAPL.US',
firstBarDate: '1980-12-12',
lastBarDate: '2025-11-26',
barCount: 11330,
},
{
_id: 'FB.US',
firstBarDate: new Date('2012-05-18T00:00:00Z'),
lastBarDate: '2022-06-08T23:30:00-04:00',
barCount: 2531,
},
];
return rows as unknown as T[];
}
if (collectionName === BAR_SPAN_COLLECTIONS.qm.collection) {
async function* stream(): AsyncGenerator<T> {
const rows: GroupedBarSpanRow[] = [
{
_id: 'VOY:CNX',
firstBarDate: '2020-01-02',
lastBarDate: new Date('2023-05-01T16:00:00Z'),
barCount: 840,
},
{
_id: 'SINGLE:TO',
firstBarDate: '2024-03-15',
lastBarDate: '2024-03-15',
barCount: 1,
},
];
for (const row of rows) {
yield row as unknown as T;
}
}
return stream();
}
return [];
},
};
const result = await computeBarSpans(reader);
expect(calls).toHaveLength(2);
expect(calls[0]?.collection).toBe('eodPrices');
expect(calls[0]?.options).toEqual({ allowDiskUse: true });
expect(calls[1]?.collection).toBe('qmPrices');
expect(calls[1]?.options).toEqual({ allowDiskUse: true });
expect(result.totalRowsRead).toBe(4);
expect(result.totalSpans).toBe(4);
expect(result.skipped).toEqual({ invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 });
expect(result.index.get('eod', 'AAPL.US')).toEqual({
source: 'eod',
sourceId: 'AAPL.US',
firstBarDate: '1980-12-12',
lastBarDate: '2025-11-26',
barCount: 11330,
});
expect(result.index.get('eod', 'FB.US')).toEqual({
source: 'eod',
sourceId: 'FB.US',
firstBarDate: '2012-05-18',
lastBarDate: '2022-06-09',
barCount: 2531,
});
expect(result.index.get('qm', 'VOY:CNX')).toEqual({
source: 'qm',
sourceId: 'VOY:CNX',
firstBarDate: '2020-01-02',
lastBarDate: '2023-05-01',
barCount: 840,
});
expect(result.index.get('qm', 'SINGLE:TO')).toEqual({
source: 'qm',
sourceId: 'SINGLE:TO',
firstBarDate: '2024-03-15',
lastBarDate: '2024-03-15',
barCount: 1,
});
expect(result.index.get('eod', 'MISSING.US')).toBeUndefined();
expect(result.index.get('qm', 'AAPL.US')).toBeUndefined();
expect(result.index.has('eod', 'MISSING.US')).toBe(false);
expect(result.index.size).toBe(4);
expect(result.index.sizeForSource('eod')).toBe(2);
expect(result.index.sizeForSource('qm')).toBe(2);
expect([...result.index]).toHaveLength(4);
});
test('skips and counts rows with null/blank ids, invalid/inverted dates, and bad barCounts without throwing', async () => {
const reader: BarSpanAggregateReader = {
aggregate<T extends Record<string, unknown>>(): T[] {
const rows: GroupedBarSpanRow[] = [
{ _id: null, firstBarDate: '2024-01-01', lastBarDate: '2024-01-02', barCount: 2 },
{ _id: ' ', firstBarDate: '2024-01-01', lastBarDate: '2024-01-02', barCount: 2 },
{ _id: 12345, firstBarDate: '2024-01-01', lastBarDate: '2024-01-02', barCount: 2 },
{ _id: 'BAD_DATE_1', firstBarDate: null, lastBarDate: '2024-01-02', barCount: 2 },
{ _id: 'BAD_DATE_2', firstBarDate: '2023-02-29', lastBarDate: '2024-01-02', barCount: 2 },
{ _id: 'INVERTED', firstBarDate: '2024-02-01', lastBarDate: '2024-01-01', barCount: 2 },
{ _id: 'ZERO_COUNT', firstBarDate: '2024-01-01', lastBarDate: '2024-01-02', barCount: 0 },
{ _id: 'NEG_COUNT', firstBarDate: '2024-01-01', lastBarDate: '2024-01-02', barCount: -5 },
{
_id: 'FLOAT_COUNT',
firstBarDate: '2024-01-01',
lastBarDate: '2024-01-02',
barCount: 2.5,
},
{ _id: 'GOOD.US', firstBarDate: '2024-01-01', lastBarDate: '2024-01-10', barCount: 7 },
];
return rows as unknown as T[];
},
};
const result = await computeBarSpans(reader, { sources: ['eod'] });
expect(result.totalRowsRead).toBe(10);
expect(result.totalSpans).toBe(1);
expect(result.skipped).toEqual({
invalidId: 3,
invalidDate: 3,
invalidCount: 3,
total: 9,
});
expect(result.bySource.eod?.skipped).toEqual(result.skipped);
expect(result.index.get('eod', 'GOOD.US')?.barCount).toBe(7);
});
test('targeted eod mode batches $in queries at configured batchSize, deduplicates IDs, merges cross-batch duplicates, and runs 0 queries for empty list', async () => {
const batchesSeen: string[][] = [];
const reader: BarSpanAggregateReader = {
aggregate<T extends Record<string, unknown>>(
_collectionName: string,
pipeline: Record<string, unknown>[]
): T[] {
assertPipelineStrictlyReadOnly(pipeline);
const matchStage = pipeline[0] as { $match: { eodSearchCode: { $in: string[] } } };
const batch = matchStage.$match.eodSearchCode.$in;
batchesSeen.push(batch);
// Emit overlapping duplicate ID 'DUP.US' across two batches to verify min/max/sum merge.
if (batchesSeen.length === 1) {
return [
{ _id: 'DUP.US', firstBarDate: '2020-05-01', lastBarDate: '2022-01-01', barCount: 400 },
{ _id: 'A.US', firstBarDate: '2019-01-02', lastBarDate: '2024-12-31', barCount: 1500 },
] as unknown as T[];
}
if (batchesSeen.length === 2) {
return [
{ _id: 'DUP.US', firstBarDate: '2018-01-02', lastBarDate: '2021-06-01', barCount: 250 },
{ _id: 'DUP.US', firstBarDate: '2021-01-01', lastBarDate: '2024-03-15', barCount: 100 },
] as unknown as T[];
}
return [
{ _id: 'E.US', firstBarDate: '2025-01-02', lastBarDate: '2025-01-02', barCount: 1 },
] as unknown as T[];
},
};
const result = await computeBarSpans(reader, {
sources: ['eod', 'qm'],
batchSize: 2,
cursorBatchSize: 500,
sourceIdsBySource: {
eod: ['A.US', ' B.US ', 'A.US', 'C.US', 'D.US', ' ', 'E.US'],
qm: [],
},
});
// 5 unique eod IDs at batchSize 2 => 3 batched queries (never 5 per-symbol queries)
expect(batchesSeen).toEqual([['A.US', 'B.US'], ['C.US', 'D.US'], ['E.US']]);
expect(result.bySource.eod?.batchesRun).toBe(3);
// Empty targeted list for qm must execute 0 queries (never fall back to a full collection scan)
expect(result.bySource.qm?.batchesRun).toBe(0);
expect(result.bySource.qm?.rowsRead).toBe(0);
expect(result.index.get('eod', 'DUP.US')).toEqual({
source: 'eod',
sourceId: 'DUP.US',
firstBarDate: '2018-01-02',
lastBarDate: '2024-03-15',
barCount: 750,
});
});
test('re-throws reader rejection and mid-stream async-iterator failure with source, collection, and cause', async () => {
const rootCause = new Error('socket timeout');
const rejectingReader: BarSpanAggregateReader = {
async aggregate() {
throw rootCause;
},
};
try {
await computeBarSpans(rejectingReader, { sources: ['eod'] });
expect.unreachable('Expected computeBarSpans to reject');
} catch (err) {
expect(err).toBeInstanceOf(Error);
const error = err as Error & { cause?: unknown };
expect(error.message).toContain('eod');
expect(error.message).toContain('eodPrices');
expect(error.message).toContain('socket timeout');
expect(error.cause).toBe(rootCause);
}
const streamCause = new Error('cursor killed');
const failingStreamReader: BarSpanAggregateReader = {
aggregate<T extends Record<string, unknown>>(): AsyncIterable<T> {
return {
async *[Symbol.asyncIterator]() {
yield {
_id: 'OK:TO',
firstBarDate: '2024-01-02',
lastBarDate: '2024-01-03',
barCount: 2,
} as unknown as T;
throw streamCause;
},
};
},
};
try {
await computeBarSpans(failingStreamReader, { sources: ['qm'] });
expect.unreachable('Expected computeBarSpans to reject on stream error');
} catch (err) {
expect(err).toBeInstanceOf(Error);
const error = err as Error & { cause?: unknown };
expect(error.message).toContain('qm');
expect(error.message).toContain('qmPrices');
expect(error.message).toContain('cursor killed');
expect(error.cause).toBe(streamCause);
}
});
test('validates invalid options explicitly before calling reader', async () => {
let called = false;
const reader: BarSpanAggregateReader = {
aggregate<T extends Record<string, unknown>>(): T[] {
called = true;
return [];
},
};
await expect(computeBarSpans(reader, { batchSize: 0 })).rejects.toThrow(/batchSize/);
await expect(computeBarSpans(reader, { batchSize: -1 })).rejects.toThrow(/batchSize/);
await expect(computeBarSpans(reader, { batchSize: 1.5 })).rejects.toThrow(/batchSize/);
await expect(computeBarSpans(reader, { batchSize: Number.NaN })).rejects.toThrow(/batchSize/);
await expect(computeBarSpans(reader, { cursorBatchSize: 0 })).rejects.toThrow(
/cursorBatchSize/
);
await expect(computeBarSpans(reader, { sources: [] })).rejects.toThrow(/sources/);
await expect(
computeBarSpans(reader, { sources: ['invalid' as unknown as 'eod'] })
).rejects.toThrow(/Unsupported bar span source/);
await expect(
computeBarSpans(reader, {
sources: ['eod'],
sourceIdsBySource: { eod: [123 as unknown as string] },
})
).rejects.toThrow(/must be a string/);
await expect(
computeBarSpans(null as unknown as BarSpanAggregateReader)
).rejects.toThrow(/reader/);
expect(called).toBe(false);
});
});
describe('spansOverlap', () => {
test('handles single-bar spans, inclusive boundaries, adjacent spans, toleranceDays, leap years, and FB ticker reuse', () => {
const singleBar = { firstBarDate: '2024-03-15', lastBarDate: '2024-03-15' };
expect(spansOverlap(singleBar, singleBar)).toBe(true);
// Inclusive boundary touch: a.lastBarDate === b.firstBarDate
expect(
spansOverlap(
{ firstBarDate: '2020-01-01', lastBarDate: '2022-06-08' },
{ firstBarDate: '2022-06-08', lastBarDate: '2025-01-01' }
)
).toBe(true);
// Adjacent non-overlapping (1-day gap)
const spanA = { firstBarDate: '2023-02-20', lastBarDate: '2023-02-28' };
const spanB = { firstBarDate: '2023-03-01', lastBarDate: '2023-03-10' };
expect(spansOverlap(spanA, spanB)).toBe(false);
expect(spansOverlap(spanA, spanB, { toleranceDays: 0 })).toBe(false);
expect(spansOverlap(spanA, spanB, { toleranceDays: 1 })).toBe(true);
// Leap year: 2024-02-28 to 2024-03-01 is a 2-day gap (2024-02-29 sits between them)
const leapA = { firstBarDate: '2024-02-20', lastBarDate: '2024-02-28' };
const leapB = { firstBarDate: '2024-03-01', lastBarDate: '2024-03-10' };
expect(spansOverlap(leapA, leapB, { toleranceDays: 1 })).toBe(false);
expect(spansOverlap(leapA, leapB, { toleranceDays: 2 })).toBe(true);
// FB ticker reuse: Meta (2012-05-18..2022-06-08) vs FB ETF (2025-01-01..2025-12-31)
expect(
spansOverlap(
{ firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' },
{ firstBarDate: '2025-01-01', lastBarDate: '2025-12-31' }
)
).toBe(false);
});
test('throws on negative/non-integer/NaN toleranceDays or invalid/inverted span dates', () => {
const valid = { firstBarDate: '2024-01-01', lastBarDate: '2024-01-10' };
expect(() => spansOverlap(valid, valid, { toleranceDays: -1 })).toThrow(RangeError);
expect(() => spansOverlap(valid, valid, { toleranceDays: 1.5 })).toThrow(RangeError);
expect(() => spansOverlap(valid, valid, { toleranceDays: Number.NaN })).toThrow(RangeError);
expect(() => spansOverlap(valid, valid, { toleranceDays: Number.POSITIVE_INFINITY })).toThrow(
RangeError
);
expect(() =>
spansOverlap({ firstBarDate: '2023-02-29', lastBarDate: '2023-03-01' }, valid)
).toThrow(RangeError);
expect(() =>
spansOverlap(valid, { firstBarDate: '2024-05-01', lastBarDate: '2024-04-01' })
).toThrow(RangeError);
});
test('BarSpanIndex returns undefined for missing entries', () => {
const index = new BarSpanIndex();
expect(index.get('eod', 'UNKNOWN.US')).toBeUndefined();
expect(index.get('qm', 'UNKNOWN:TO')).toBeUndefined();
expect(index.size).toBe(0);
});
});
describe('computeBarSpans streaming scale check', () => {
test('folds 1,000,000 synthetic grouped rows via reusable scratch object without materializing an intermediate array', async () => {
const totalRows = 1_000_000;
// Reuse a single mutated object across all yields. If computeBarSpans buffered rows into an
// array before folding, all buffered references would alias the final row and index.size would be 1.
const scratchRow: GroupedBarSpanRow = {
_id: '',
firstBarDate: '2010-01-04',
lastBarDate: '2025-11-26',
barCount: 1,
};
const reader: BarSpanAggregateReader = {
aggregate<T extends Record<string, unknown>>(): Iterable<T> {
return {
*[Symbol.iterator]() {
for (let i = 0; i < totalRows; i++) {
scratchRow._id = `SYM${i}.US`;
scratchRow.firstBarDate = (i & 1) === 0 ? '2010-01-04' : '2015-06-15';
scratchRow.lastBarDate = (i & 1) === 0 ? '2025-11-26' : '2024-12-31';
scratchRow.barCount = (i % 5000) + 1;
yield scratchRow as unknown as T;
}
},
};
},
};
const startMs = performance.now();
const result = await computeBarSpans(reader, { sources: ['eod'] });
const elapsedMs = performance.now() - startMs;
process.stdout.write(
`[bench] computeBarSpans folded ${totalRows.toLocaleString()} rows in ${elapsedMs.toFixed(2)} ms\n`
);
expect(result.totalRowsRead).toBe(totalRows);
expect(result.totalSpans).toBe(totalRows);
expect(result.skipped.total).toBe(0);
expect(result.index.get('eod', 'SYM0.US')).toEqual({
source: 'eod',
sourceId: 'SYM0.US',
firstBarDate: '2010-01-04',
lastBarDate: '2025-11-26',
barCount: 1,
});
expect(result.index.get('eod', 'SYM500001.US')).toEqual({
source: 'eod',
sourceId: 'SYM500001.US',
firstBarDate: '2015-06-15',
lastBarDate: '2024-12-31',
barCount: 2,
});
expect(result.index.get('eod', 'SYM999999.US')).toEqual({
source: 'eod',
sourceId: 'SYM999999.US',
firstBarDate: '2015-06-15',
lastBarDate: '2024-12-31',
barCount: 5000,
});
});
});