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[]): 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).toHaveLength(2); expect(eodFull[0]).toHaveProperty('$project'); expect(eodFull[1]).toEqual({ $group: { _id: '$sourceId', firstBarDate: { $min: '$normalizedDate' }, lastBarDate: { $max: '$normalizedDate' }, barCount: { $sum: { $cond: [{ $ne: ['$normalizedDate', null] }, 1, 0], }, }, }, }); expect(eodTargeted).toHaveLength(3); expect(eodTargeted[0]).toEqual({ $match: { eodSearchCode: { $in: ['AAPL.US', 'FB.US'] } } }); expect(eodTargeted[1]).toHaveProperty('$project'); expect(eodTargeted[2]).toEqual(eodFull[1]); expect(qmFull).toHaveLength(3); expect(qmFull[0]).toEqual({ $sort: { qmSearchCode: 1, date: 1 } }); expect(qmFull[1]).toHaveProperty('$project'); expect(qmFull[2]).toEqual(eodFull[1]); expect(qmTargeted).toHaveLength(3); expect(qmTargeted[0]).toEqual({ $match: { qmSearchCode: { $in: ['AAPL', 'VOY:CNX'] } } }); expect(qmTargeted[1]).toHaveProperty('$project'); expect(qmTargeted[2]).toEqual(eodFull[1]); }); test('regression: normalizes mixed BSON Dates/strings and rejects timezone-less or malformed dates before $min/$max', async () => { // MongoDB BSON comparison order: strings (rank 2) sort BEFORE Dates (rank 9). // https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/ const bsonTypeRank = (val: unknown): number => { if (val === null || val === undefined) {return 0;} if (typeof val === 'number') {return 1;} if (typeof val === 'string') {return 2;} if (val instanceof Date) {return 9;} return 10; }; const compareBson = (a: unknown, b: unknown): number => { const rankDiff = bsonTypeRank(a) - bsonTypeRank(b); if (rankDiff !== 0) {return rankDiff;} if (typeof a === 'string' && typeof b === 'string') { return a < b ? -1 : a > b ? 1 : 0; } if (a instanceof Date && b instanceof Date) { return a.getTime() - b.getTime(); } if (typeof a === 'number' && typeof b === 'number') { return a - b; } return 0; }; // Simulates MongoDB 7.0 `$dateFromString` faithfully — crucially, WITHOUT `format`, // MongoDB 7.0 accepts timezone-less ISO timestamps (treating them as UTC) and unpadded // dates, so only the pipeline's `$regexMatch` gate can reject them. const simulateMongoDateFromString = (raw: string, format?: string): Date | null => { if (format === '%Y-%m-%d') { const m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(raw); if (!m) {return null;} const year = Number(m[1]); const month = Number(m[2]); const day = Number(m[3]); const d = new Date(Date.UTC(year, month - 1, day)); if ( d.getUTCFullYear() !== year || d.getUTCMonth() + 1 !== month || d.getUTCDate() !== day ) { return null; } return d; } // MongoDB 7.0 default ISO-8601 parser accepts timezone-less datetimes as UTC. const isoMatch = /^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})?)?$/.exec( raw ); if (!isoMatch) {return null;} const year = Number(isoMatch[1]); const month = Number(isoMatch[2]); const day = Number(isoMatch[3]); const hour = isoMatch[4] !== undefined ? Number(isoMatch[4]) : 0; const minute = isoMatch[5] !== undefined ? Number(isoMatch[5]) : 0; const second = isoMatch[6] !== undefined ? Number(isoMatch[6]) : 0; const tz = isoMatch[8]; if (hour > 23 || minute > 59 || second > 59) {return null;} const checkDate = new Date(Date.UTC(year, month - 1, day)); if ( checkDate.getUTCFullYear() !== year || checkDate.getUTCMonth() + 1 !== month || checkDate.getUTCDate() !== day ) { return null; } let offsetMs = 0; if (tz !== undefined && tz !== 'Z') { const sign = tz[0] === '-' ? -1 : 1; const digits = tz.replace(/[^0-9]/g, ''); const tzH = Number(digits.slice(0, 2)); const tzM = Number(digits.slice(2, 4)); if (tzH > 23 || tzM > 59) {return null;} offsetMs = sign * (tzH * 60 + tzM) * 60_000; } return new Date(Date.UTC(year, month - 1, day, hour, minute, second) - offsetMs); }; const evalExpr = ( expr: unknown, doc: Record, vars: Record = {} ): unknown => { if (typeof expr === 'string') { if (expr.startsWith('$$')) { return vars[expr.slice(2)]; } if (expr.startsWith('$')) { return doc[expr.slice(1)]; } return expr; } if (expr === null || typeof expr !== 'object' || Array.isArray(expr)) { return expr; } const obj = expr as Record; if ('$type' in obj) { const val = evalExpr(obj.$type, doc, vars); if (val === null) {return 'null';} if (val === undefined) {return 'missing';} if (val instanceof Date) {return 'date';} if (typeof val === 'string') {return 'string';} if (typeof val === 'number') {return 'double';} return 'object'; } if ('$eq' in obj) { const [left, right] = obj.$eq as [unknown, unknown]; return evalExpr(left, doc, vars) === evalExpr(right, doc, vars); } if ('$ne' in obj) { const [left, right] = obj.$ne as [unknown, unknown]; return evalExpr(left, doc, vars) !== evalExpr(right, doc, vars); } if ('$gte' in obj) { const [left, right] = obj.$gte as [unknown, unknown]; return (evalExpr(left, doc, vars) as number) >= (evalExpr(right, doc, vars) as number); } if ('$lte' in obj) { const [left, right] = obj.$lte as [unknown, unknown]; return (evalExpr(left, doc, vars) as number) <= (evalExpr(right, doc, vars) as number); } if ('$and' in obj) { const items = obj.$and as unknown[]; for (const item of items) { if (!evalExpr(item, doc, vars)) {return false;} } return true; } if ('$cond' in obj) { if (Array.isArray(obj.$cond)) { const [condExpr, thenExpr, elseExpr] = obj.$cond as [unknown, unknown, unknown]; return evalExpr(condExpr, doc, vars) ? evalExpr(thenExpr, doc, vars) : evalExpr(elseExpr, doc, vars); } const cfg = obj.$cond as { if: unknown; then: unknown; else: unknown }; return evalExpr(cfg.if, doc, vars) ? evalExpr(cfg.then, doc, vars) : evalExpr(cfg.else, doc, vars); } if ('$let' in obj) { const cfg = obj.$let as { vars: Record; in: unknown }; const nextVars: Record = { ...vars }; for (const [k, v] of Object.entries(cfg.vars)) { nextVars[k] = evalExpr(v, doc, vars); } return evalExpr(cfg.in, doc, nextVars); } if ('$trim' in obj) { const cfg = obj.$trim as { input: unknown }; const val = evalExpr(cfg.input, doc, vars); return typeof val === 'string' ? val.trim() : null; } if ('$regexMatch' in obj) { const cfg = obj.$regexMatch as { input: unknown; regex: string; options?: string }; const val = evalExpr(cfg.input, doc, vars); if (typeof val !== 'string') {return false;} return new RegExp(cfg.regex, cfg.options ?? '').test(val); } if ('$year' in obj) { const cfg = obj.$year as { date: unknown; timezone?: string }; const val = evalExpr(cfg.date, doc, vars); if (val === null || val === undefined) {return null;} if (!(val instanceof Date) || !Number.isFinite(val.getTime())) {return null;} expect(cfg.timezone).toBe('UTC'); return val.getUTCFullYear(); } if ('$switch' in obj) { const cfg = obj.$switch as { branches: Array<{ case: unknown; then: unknown }>; default: unknown; }; for (const branch of cfg.branches) { if (evalExpr(branch.case, doc, vars) === true) { return evalExpr(branch.then, doc, vars); } } return evalExpr(cfg.default, doc, vars); } if ('$dateFromString' in obj) { const cfg = obj.$dateFromString as { dateString: unknown; format?: string; onError?: unknown; onNull?: unknown; }; const raw = evalExpr(cfg.dateString, doc, vars); if (raw === null || raw === undefined) { return cfg.onNull ?? null; } if (typeof raw !== 'string') { return cfg.onError ?? null; } const parsed = simulateMongoDateFromString(raw, cfg.format); return parsed ?? cfg.onError ?? null; } if ('$dateToString' in obj) { const cfg = obj.$dateToString as { format: string; timezone?: string; date: unknown; onNull?: unknown; }; const raw = evalExpr(cfg.date, doc, vars); if (raw === null || raw === undefined) { return cfg.onNull ?? null; } if (!(raw instanceof Date) || !Number.isFinite(raw.getTime())) { return null; } expect(cfg.format).toBe('%Y-%m-%d'); expect(cfg.timezone).toBe('UTC'); const y = String(raw.getUTCFullYear()).padStart(4, '0'); const m = String(raw.getUTCMonth() + 1).padStart(2, '0'); const d = String(raw.getUTCDate()).padStart(2, '0'); return `${y}-${m}-${d}`; } throw new Error(`Unsupported test aggregation expression: ${JSON.stringify(obj)}`); }; const runPipeline = ( rawDocs: Record[], pipeline: Record[] ): Record[] => { let docs = rawDocs.map(d => ({ ...d })); for (const stage of pipeline) { if ('$match' in stage) { const cond = stage.$match as Record; docs = docs.filter(doc => Object.entries(cond).every(([field, pred]) => Array.isArray(pred.$in) ? pred.$in.includes(doc[field]) : doc[field] === pred ) ); } else if ('$sort' in stage) { const sortSpec = Object.entries(stage.$sort as Record); docs = [...docs].sort((a, b) => { for (const [field, dir] of sortSpec) { const cmp = compareBson(a[field], b[field]); if (cmp !== 0) {return cmp * dir;} } return 0; }); } else if ('$project' in stage) { const proj = stage.$project as Record; docs = docs.map(doc => { const out: Record = {}; for (const [key, spec] of Object.entries(proj)) { if (key === '_id' && spec === 0) {continue;} out[key] = evalExpr(spec, doc); } return out; }); } else if ('$group' in stage) { const groupSpec = stage.$group as Record; const groups = new Map[]>(); for (const doc of docs) { const key = evalExpr(groupSpec._id, doc); const bucket = groups.get(key); if (bucket) { bucket.push(doc); } else { groups.set(key, [doc]); } } const grouped: Record[] = []; for (const [key, bucket] of groups.entries()) { const out: Record = { _id: key }; for (const [field, acc] of Object.entries(groupSpec)) { if (field === '_id') {continue;} const accObj = acc as Record; if ('$min' in accObj) { let minVal: unknown = null; for (const doc of bucket) { const val = evalExpr(accObj.$min, doc); if (val === null || val === undefined) {continue;} if (minVal === null || compareBson(val, minVal) < 0) { minVal = val; } } out[field] = minVal; } else if ('$max' in accObj) { let maxVal: unknown = null; for (const doc of bucket) { const val = evalExpr(accObj.$max, doc); if (val === null || val === undefined) {continue;} if (maxVal === null || compareBson(val, maxVal) > 0) { maxVal = val; } } out[field] = maxVal; } else if ('$sum' in accObj) { let total = 0; for (const doc of bucket) { const val = evalExpr(accObj.$sum, doc); if (typeof val === 'number') { total += val; } } out[field] = total; } } grouped.push(out); } docs = grouped; } } return docs; }; const rawEodDocs: Record[] = [ // Mixed BSON Date (older) + string (newer): raw BSON ordering would invert min/max! { eodSearchCode: 'MIXED.US', date: new Date('2024-06-07T00:00:00.000Z') }, { eodSearchCode: 'MIXED.US', date: '2024-06-10' }, { eodSearchCode: 'MIXED.US', date: '2024-06-07T23:30:00-04:00' }, // 2024-06-08 UTC // Timezone-less timestamp would become a false max extremum if unvalidated `$dateFromString` ran. { eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-06-03' }, { eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-06-07' }, { eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-06-10T12:00:00' }, { eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2023-02-29' }, { eodSearchCode: 'TZLESS_EXTREMUM.US', date: '2024-6-9' }, // All-invalid dates (including timezone-less only) must yield null bounds and be skipped. { eodSearchCode: 'ALL_BAD.US', date: 'not-a-date' }, { eodSearchCode: 'ALL_BAD.US', date: null }, ]; const rawQmDocs: Record[] = [ { qmSearchCode: 'MIXED:TO', date: new Date('2024-06-07T00:00:00.000Z') }, { qmSearchCode: 'MIXED:TO', date: '2024-06-10' }, // QuoteMedia listing with valid bars through June 7 and a timezone-less row on June 10: // must NOT extend to June 10 or create a false overlap with a listing starting June 10. { qmSearchCode: 'QM_OLD:TO', date: '2024-06-03' }, { qmSearchCode: 'QM_OLD:TO', date: '2024-06-07' }, { qmSearchCode: 'QM_OLD:TO', date: '2024-06-10T12:00:00' }, // Listing whose only bar is a timezone-less timestamp must be skipped as invalidDate. { qmSearchCode: 'QM_TZLESS_ONLY:TO', date: '2024-06-10T12:00:00' }, ]; const reader: BarSpanAggregateReader = { aggregate>( collectionName: string, pipeline: Record[] ): T[] { assertPipelineStrictlyReadOnly(pipeline); const docs = collectionName === BAR_SPAN_COLLECTIONS.eod.collection ? rawEodDocs : rawQmDocs; return runPipeline(docs, pipeline) as unknown as T[]; }, }; const result = await computeBarSpans(reader, { sources: ['eod', 'qm'] }); expect(result.index.get('eod', 'MIXED.US')).toEqual({ source: 'eod', sourceId: 'MIXED.US', firstBarDate: '2024-06-07', lastBarDate: '2024-06-10', barCount: 3, }); expect(result.index.get('eod', 'TZLESS_EXTREMUM.US')).toEqual({ source: 'eod', sourceId: 'TZLESS_EXTREMUM.US', firstBarDate: '2024-06-03', lastBarDate: '2024-06-07', barCount: 2, }); expect(result.index.get('qm', 'MIXED:TO')).toEqual({ source: 'qm', sourceId: 'MIXED:TO', firstBarDate: '2024-06-07', lastBarDate: '2024-06-10', barCount: 2, }); const qmOld = result.index.get('qm', 'QM_OLD:TO'); expect(qmOld).toEqual({ source: 'qm', sourceId: 'QM_OLD:TO', firstBarDate: '2024-06-03', lastBarDate: '2024-06-07', barCount: 2, }); // Must not falsely overlap a different listing starting June 10. expect( spansOverlap(qmOld!, { firstBarDate: '2024-06-10', lastBarDate: '2024-06-20' }) ).toBe(false); expect(result.index.get('eod', 'ALL_BAD.US')).toBeUndefined(); expect(result.index.get('qm', 'QM_TZLESS_ONLY:TO')).toBeUndefined(); expect(result.skipped).toEqual({ invalidId: 0, invalidDate: 2, invalidCount: 0, total: 2, }); }); 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[]; options?: BarSpanAggregateOptions; }> = []; const reader: BarSpanAggregateReader = { async aggregate>( collectionName: string, pipeline: Record[], options?: BarSpanAggregateOptions ): Promise | AsyncIterable> { 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 { 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[] { 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>( _collectionName: string, pipeline: Record[] ): 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) // Exact source IDs (including surrounding spaces) are preserved so stored IDs can be targeted. 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>(): AsyncIterable { 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[] { 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>(): Iterable { 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, }); }); });