import { describe, expect, test } from 'bun:test'; import { assertReadOnlyBarSpanPipeline, BarSpanIndex, buildBarSpansPipeline, buildEodBarSpansPipeline, buildQmBarSpansPipeline, computeBarSpans, normalizeBarDate, spansOverlap, type BarSpan, type BarSpanAggregateOptions, type BarSpanAggregateReader, type BarSpanSource, type GroupedBarSpanRow, } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; /** Deterministic PRNG so fuzz cases are reproducible (seeded, no Math.random). */ function mulberry32(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function pad(value: number, width: number): string { return String(value).padStart(width, '0'); } function ymdFromUtcDay(day: number): string { const d = new Date(day * 86_400_000); return `${pad(d.getUTCFullYear(), 4)}-${pad(d.getUTCMonth() + 1, 2)}-${pad(d.getUTCDate(), 2)}`; } function utcDay(ymd: string): number { return Math.round(Date.parse(`${ymd}T00:00:00Z`) / 86_400_000); } function rowsReader( rowsByCollection: Record, calls: Array<{ collection: string; pipeline: Record[]; options?: BarSpanAggregateOptions; }> = [] ): BarSpanAggregateReader { return { aggregate>( collectionName: string, pipeline: Record[], options?: BarSpanAggregateOptions ): T[] { calls.push({ collection: collectionName, pipeline, options }); return (rowsByCollection[collectionName] ?? []) as unknown as T[]; }, }; } /** Collects every `$regexMatch.regex` used by the generated date-normalization projection. */ function collectRegexGates(node: unknown, out: string[] = []): string[] { if (node === null || typeof node !== 'object') { return out; } if (Array.isArray(node)) { for (const item of node) { collectRegexGates(item, out); } return out; } for (const [key, val] of Object.entries(node)) { if (key === '$regexMatch') { out.push((val as { regex: string }).regex); } collectRegexGates(val, out); } return out; } describe('normalizeBarDate edge cases', () => { test('offset timestamps that cross a year boundary roll into the correct UTC calendar date', () => { expect(normalizeBarDate('2024-12-31T23:30:00-01:00')).toBe('2025-01-01'); expect(normalizeBarDate('2025-01-01T00:30:00+01:00')).toBe('2024-12-31'); expect(normalizeBarDate('2024-02-28T23:00:00-02:00')).toBe('2024-02-29'); expect(normalizeBarDate('2023-02-28T23:00:00-02:00')).toBe('2023-03-01'); expect(normalizeBarDate('2024-03-01T00:15:00+0030')).toBe('2024-02-29'); }); test('offset timestamps that would leave the 0001..9999 range return null', () => { expect(normalizeBarDate('0001-01-01T00:30:00+01:00')).toBeNull(); expect(normalizeBarDate('9999-12-31T23:00:00-02:00')).toBeNull(); expect(normalizeBarDate('0001-01-01T01:00:00+01:00')).toBe('0001-01-01'); expect(normalizeBarDate(new Date(Date.UTC(10000, 0, 1)))).toBeNull(); const yearZero = new Date(Date.UTC(2000, 0, 1)); yearZero.setUTCFullYear(0); expect(normalizeBarDate(yearZero)).toBeNull(); }); test('rejects lowercase designators, leap seconds, and malformed offsets', () => { for (const input of [ '2024-06-08t12:00:00Z', '2024-06-08T12:00:00z', '2024-06-08T12:00:60Z', '2024-06-08T12:00:00+05:3', '2024-06-08T12:00:00+05:60', '2024-06-08T12:00:00+2400', '2024-06-08T12:00:00.Z', '2024-06-08T12:00:00.1234567890Z', '+2024-06-08', '20240608', ]) { expect(normalizeBarDate(input)).toBeNull(); } }); test('seeded fuzz: timezone-qualified ISO strings agree with the JS Date UTC oracle', () => { const rand = mulberry32(0x43); for (let i = 0; i < 5000; i++) { const day = Math.floor(rand() * 40_000) - 5_000; // ~1956..2079 const ymd = ymdFromUtcDay(day); const hh = pad(Math.floor(rand() * 24), 2); const mm = pad(Math.floor(rand() * 60), 2); const ss = pad(Math.floor(rand() * 60), 2); const ms = pad(Math.floor(rand() * 1000), 3); const offH = Math.floor(rand() * 15); const offM = [0, 15, 30, 45][Math.floor(rand() * 4)] ?? 0; const sign = rand() < 0.5 ? '-' : '+'; const tz = rand() < 0.2 ? 'Z' : `${sign}${pad(offH, 2)}:${pad(offM, 2)}`; const iso = `${ymd}T${hh}:${mm}:${ss}.${ms}${tz}`; const oracle = new Date(iso).toISOString().slice(0, 10); expect(normalizeBarDate(iso)).toBe(oracle); // The no-colon offset form must produce the identical UTC date. expect(normalizeBarDate(iso.replace(/([+-]\d{2}):(\d{2})$/, '$1$2'))).toBe(oracle); } }); }); describe('MongoDB date-shape gate parity with normalizeBarDate', () => { // The generated $project runs these regexes in MongoDB before $dateFromString. If they accept a // shape normalizeBarDate rejects (or vice versa), Mongo-side extrema diverge from the JS fold. const [ymdGate, isoGate] = collectRegexGates(buildEodBarSpansPipeline()); const ymdRe = new RegExp(ymdGate ?? '(?!)'); const isoRe = new RegExp(isoGate ?? '(?!)'); const gateAccepts = (raw: string): boolean => ymdRe.test(raw.trim()) || isoRe.test(raw.trim()); test('eod and qm projections use the same two shape gates', () => { expect(collectRegexGates(buildEodBarSpansPipeline())).toHaveLength(2); expect(collectRegexGates(buildQmBarSpansPipeline())).toEqual([ymdGate ?? '', isoGate ?? '']); expect(collectRegexGates(buildQmBarSpansPipeline(['X']))).toEqual([ ymdGate ?? '', isoGate ?? '', ]); }); test('timezone-less, unpadded, and slash-delimited strings never pass the Mongo gate', () => { for (const raw of [ '2024-06-10T12:00:00', '2024-06-10 12:00:00', '2024-06-10T12:00', '2024-6-9', '2024/06/09', '0000-01-01', '2024-06-10T24:00:00Z', '2024-06-10T12:00:00+24:00', '2024-06-10T12:00:00z', ]) { expect(gateAccepts(raw)).toBe(false); expect(normalizeBarDate(raw)).toBeNull(); } }); test('seeded fuzz: every string normalizeBarDate accepts passes the gate, and gate-only accepts are calendar-invalid', () => { const rand = mulberry32(20261127); const pick = (items: readonly T[]): T => items[Math.floor(rand() * items.length)] as T; let gateOnly = 0; for (let i = 0; i < 20_000; i++) { const year = pick(['0000', '0001', '1999', '2024', '2023', '9999', '199', '20245']); const month = pick(['00', '01', '02', '04', '12', '13', '1', '6']); const day = pick(['00', '01', '28', '29', '30', '31', '32', '9']); const time = pick([ '', 'T12:00:00', 'T23:59:59Z', ' 00:00Z', 'T12:00:00.123456789+05:30', 'T12:00:00-0400', 'T24:00:00Z', 'T12:60:00Z', 'T12:00:00+25:00', 'T12:00:00+05', ]); const raw = `${pick(['', ' '])}${year}-${month}-${day}${time}${pick(['', ' '])}`; const normalized = normalizeBarDate(raw); const accepted = gateAccepts(raw); if (normalized !== null) { expect(accepted).toBe(true); } if (accepted && normalized === null) { // Only calendar rollovers may slip past the regex; $dateFromString rejects them in Mongo. const y = Number(year); const m = Number(month); const d = Number(day); const probe = new Date(Date.UTC(2000, m - 1, d)); probe.setUTCFullYear(y); expect(probe.getUTCMonth() + 1 === m && probe.getUTCDate() === d).toBe(false); gateOnly++; } } expect(gateOnly).toBeGreaterThan(0); }); }); describe('pipeline builder edge cases', () => { test('targeted pipelines copy the id list so later caller mutation cannot widen a batch', () => { const ids = ['A.US', 'B.US']; const pipeline = buildEodBarSpansPipeline(ids); ids.push('C.US'); ids[0] = 'Z.US'; expect(pipeline[0]).toEqual({ $match: { eodSearchCode: { $in: ['A.US', 'B.US'] } } }); }); test('each build returns fresh stage objects', () => { const first = buildQmBarSpansPipeline(); (first[2] as { $group: Record }).$group.barCount = { $sum: 99 }; expect( (buildQmBarSpansPipeline()[2] as { $group: Record }).$group.barCount ).toEqual({ $sum: { $cond: [{ $ne: ['$normalizedDate', null] }, 1, 0], }, }); }); test('stored source IDs with leading/trailing spaces are not merged with trimmed IDs', async () => { const reader: BarSpanAggregateReader = { aggregate>(): T[] { return [ { _id: 'AAPL.US', firstBarDate: '2020-01-02', lastBarDate: '2024-12-31', barCount: 10 }, { _id: ' AAPL.US ', firstBarDate: '2021-01-04', lastBarDate: '2022-12-30', barCount: 5 }, ] as unknown as T[]; }, }; const result = await computeBarSpans(reader, { sources: ['eod'] }); expect(result.index.get('eod', 'AAPL.US')?.barCount).toBe(10); expect(result.index.get('eod', ' AAPL.US ')?.barCount).toBe(5); expect(result.index.sizeForSource('eod')).toBe(2); }); test('dispatcher rejects unknown sources', () => { expect(() => buildBarSpansPipeline('ib' as unknown as BarSpanSource)).toThrow(RangeError); }); test('read-only guard rejects case variants, non-arrays, null stages, and survives cyclic values', () => { expect(() => assertReadOnlyBarSpanPipeline([{ $OUT: 'x' }])).toThrow(/forbidden write stage/); expect(() => assertReadOnlyBarSpanPipeline([{ $match: { a: { $Merge: 1 } } }])).toThrow( /forbidden write stage/ ); expect(() => assertReadOnlyBarSpanPipeline({} as unknown as Record[])).toThrow( TypeError ); expect(() => assertReadOnlyBarSpanPipeline([null as unknown as Record]) ).toThrow(TypeError); expect(() => assertReadOnlyBarSpanPipeline([[] as unknown as Record])).toThrow( TypeError ); const cyclic: Record = { a: 1 }; cyclic.self = cyclic; expect(() => assertReadOnlyBarSpanPipeline([{ $match: cyclic }])).not.toThrow(); }); }); describe('BarSpanIndex merge semantics', () => { test('merge never mutates a span object the caller still holds', () => { const index = new BarSpanIndex(); const original: BarSpan = { source: 'eod', sourceId: 'FB.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 10, }; index.merge(original); index.merge({ ...original, firstBarDate: '2010-01-04', lastBarDate: '2025-01-01', barCount: 5, }); expect(original).toEqual({ source: 'eod', sourceId: 'FB.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 10, }); expect(index.get('eod', 'FB.US')).toEqual({ source: 'eod', sourceId: 'FB.US', firstBarDate: '2010-01-04', lastBarDate: '2025-01-01', barCount: 15, }); }); test('same sourceId under eod and qm stays separate', () => { const index = new BarSpanIndex(); index.merge({ source: 'eod', sourceId: 'VOY', firstBarDate: '2020-01-01', lastBarDate: '2020-12-31', barCount: 1, }); index.merge({ source: 'qm', sourceId: 'VOY', firstBarDate: '2024-01-01', lastBarDate: '2024-12-31', barCount: 2, }); expect(index.get('eod', 'VOY')?.firstBarDate).toBe('2020-01-01'); expect(index.get('qm', 'VOY')?.firstBarDate).toBe('2024-01-01'); expect(index.size).toBe(2); expect([...index.values()].map(s => s.source)).toEqual(['eod', 'qm']); }); test('seeded fuzz: folding duplicate rows is independent of arrival order', async () => { const rand = mulberry32(7); const rows: GroupedBarSpanRow[] = []; const expected = new Map(); for (let i = 0; i < 2000; i++) { const id = `ID${Math.floor(rand() * 50)}`; const start = Math.floor(rand() * 20_000); const end = start + Math.floor(rand() * 3000); const count = 1 + Math.floor(rand() * 500); rows.push({ _id: id, firstBarDate: ymdFromUtcDay(start), lastBarDate: ymdFromUtcDay(end), barCount: count, }); const prev = expected.get(id); expected.set(id, { first: Math.min(prev?.first ?? start, start), last: Math.max(prev?.last ?? end, end), count: (prev?.count ?? 0) + count, }); } const shuffled = [...rows]; for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [shuffled[i], shuffled[j]] = [ shuffled[j] as GroupedBarSpanRow, shuffled[i] as GroupedBarSpanRow, ]; } const forward = await computeBarSpans(rowsReader({ eodPrices: rows }), { sources: ['eod'] }); const reordered = await computeBarSpans(rowsReader({ eodPrices: shuffled }), { sources: ['eod'], }); expect(forward.totalSpans).toBe(expected.size); for (const [id, exp] of expected) { const span = forward.index.get('eod', id); expect(span).toEqual({ source: 'eod', sourceId: id, firstBarDate: ymdFromUtcDay(exp.first), lastBarDate: ymdFromUtcDay(exp.last), barCount: exp.count, }); expect(reordered.index.get('eod', id)).toEqual(span as BarSpan); } }); }); describe('computeBarSpans edge cases', () => { test('targeted qm mode batches $match {qmSearchCode: {$in}} and forwards cursorBatchSize', async () => { const calls: Array<{ collection: string; pipeline: Record[]; options?: BarSpanAggregateOptions; }> = []; const result = await computeBarSpans(rowsReader({}, calls), { sources: ['qm'], batchSize: 3, cursorBatchSize: 250, sourceIdsBySource: { qm: ['VOY:CNX', 'VOY:CC', 'A:TO', 'B:TO', 'C:TO', 'D:TO', 'E:TO'] }, }); expect(calls.map(c => c.collection)).toEqual(['qmPrices', 'qmPrices', 'qmPrices']); expect(calls.map(c => c.pipeline[0])).toEqual([ { $match: { qmSearchCode: { $in: ['VOY:CNX', 'VOY:CC', 'A:TO'] } } }, { $match: { qmSearchCode: { $in: ['B:TO', 'C:TO', 'D:TO'] } } }, { $match: { qmSearchCode: { $in: ['E:TO'] } } }, ]); for (const call of calls) { expect(call.options).toEqual({ allowDiskUse: true, batchSize: 250 }); expect(call.pipeline.some(stage => '$sort' in stage)).toBe(false); } expect(result.bySource.qm?.batchesRun).toBe(3); expect(result.bySource.eod).toBeUndefined(); }); test('a large targeted list issues ceil(n / batchSize) queries, never one per symbol', async () => { const calls: Array<{ collection: string; pipeline: Record[] }> = []; const ids = Array.from({ length: 10_001 }, (_, i) => `S${i}.US`); await computeBarSpans(rowsReader({}, calls), { sources: ['eod'], sourceIdsBySource: { eod: ids }, }); expect(calls).toHaveLength(11); const sizes = calls.map( c => (c.pipeline[0] as { $match: { eodSearchCode: { $in: string[] } } }).$match.eodSearchCode.$in .length ); expect(sizes.slice(0, 10).every(n => n === 1000)).toBe(true); expect(sizes[10]).toBe(1); }); test('ids for an unrequested source are ignored and duplicate sources run once', async () => { const calls: Array<{ collection: string; pipeline: Record[] }> = []; await computeBarSpans(rowsReader({}, calls), { sources: ['eod', 'eod'], sourceIdsBySource: { qm: ['X:TO'] }, }); expect(calls.map(c => c.collection)).toEqual(['eodPrices']); expect(calls[0]?.pipeline[0]).not.toHaveProperty('$match'); }); test('whitespace-only targeted lists run zero queries instead of a full scan', async () => { const calls: Array<{ collection: string; pipeline: Record[] }> = []; const result = await computeBarSpans(rowsReader({}, calls), { sources: ['eod'], sourceIdsBySource: { eod: [' ', '\t'] }, }); expect(calls).toHaveLength(0); expect(result.bySource.eod?.batchesRun).toBe(0); }); test('unknown keys in sourceIdsBySource throw before any query', async () => { const calls: Array<{ collection: string; pipeline: Record[] }> = []; await expect( computeBarSpans(rowsReader({}, calls), { sourceIdsBySource: { ib: ['X'] } as unknown as Partial>, }) ).rejects.toThrow(/Unsupported source in options.sourceIdsBySource/); expect(calls).toHaveLength(0); }); test('per-source stats and combined skip totals add up across eod and qm', async () => { const result = await computeBarSpans( rowsReader({ eodPrices: [ { _id: 'A.US', firstBarDate: '2020-01-01', lastBarDate: '2020-02-01', barCount: 3 }, { _id: null, firstBarDate: '2020-01-01', lastBarDate: '2020-02-01', barCount: 3 }, ], qmPrices: [ { _id: 'A:TO', firstBarDate: '2021-01-01', lastBarDate: '2021-02-01', barCount: 4 }, { _id: 'B:TO', firstBarDate: null, lastBarDate: null, barCount: 2 }, { _id: 'C:TO', firstBarDate: '2021-01-01', lastBarDate: '2021-02-01', barCount: '4' }, ], }) ); expect(result.bySource.eod).toMatchObject({ collection: 'eodPrices', batchesRun: 1, rowsRead: 2, spansIndexed: 1, }); expect(result.bySource.qm).toMatchObject({ collection: 'qmPrices', batchesRun: 1, rowsRead: 3, spansIndexed: 1, }); expect(result.bySource.eod?.skipped).toEqual({ invalidId: 1, invalidDate: 0, invalidCount: 0, total: 1, }); expect(result.bySource.qm?.skipped).toEqual({ invalidId: 0, invalidDate: 1, invalidCount: 1, total: 2, }); expect(result.skipped).toEqual({ invalidId: 1, invalidDate: 1, invalidCount: 1, total: 3 }); expect(result.totalRowsRead).toBe(5); expect(result.totalSpans).toBe(2); }); test('wraps non-iterable results, sync throws, sync iterator failures, and non-Error rejections with context', async () => { const cases: Array<{ reader: BarSpanAggregateReader; source: BarSpanSource; detail: RegExp }> = [ { reader: { aggregate: () => 42 as unknown as never[] }, source: 'eod', detail: /Iterable or AsyncIterable/, }, { reader: { aggregate: () => { throw new Error('sync boom'); }, }, source: 'qm', detail: /sync boom/, }, { reader: { aggregate>(): Iterable { return { *[Symbol.iterator]() { yield { _id: 'A', firstBarDate: '2020-01-01', lastBarDate: '2020-01-02', barCount: 1, } as unknown as T; throw new Error('iterator broke'); }, }; }, }, source: 'eod', detail: /iterator broke/, }, { reader: { aggregate: () => Promise.reject('plain string failure'), }, source: 'qm', detail: /plain string failure/, }, ]; for (const { reader, source, detail } of cases) { const collection = source === 'eod' ? 'eodPrices' : 'qmPrices'; const promise = computeBarSpans(reader, { sources: [source] }); await expect(promise).rejects.toThrow(detail); await expect(computeBarSpans(reader, { sources: [source] })).rejects.toThrow( `source "${source}" (collection "${collection}")` ); } }); test('a failure in the second source names that source, not the first', async () => { const reader: BarSpanAggregateReader = { aggregate>(collection: string): T[] { if (collection === 'qmPrices') { throw new Error('qm down'); } return []; }, }; await expect(computeBarSpans(reader)).rejects.toThrow( 'source "qm" (collection "qmPrices"): qm down' ); }); test('non-array sources and string sourceIds lists are rejected before any query', async () => { const calls: Array<{ collection: string; pipeline: Record[] }> = []; const reader = rowsReader({}, calls); await expect( computeBarSpans(reader, { sources: 'eod' as unknown as BarSpanSource[] }) ).rejects.toThrow(/sources/); await expect( computeBarSpans(reader, { sourceIdsBySource: { eod: 'AAPL.US' as unknown as string[] } }) ).rejects.toThrow(TypeError); await expect(computeBarSpans({} as unknown as BarSpanAggregateReader)).rejects.toThrow( /reader/ ); expect(calls).toHaveLength(0); }); }); describe('spansOverlap invariants', () => { test('containment and huge tolerance overlap; FB reuse only overlaps once tolerance bridges the 938-day gap', () => { expect( spansOverlap( { firstBarDate: '2010-01-01', lastBarDate: '2020-12-31' }, { firstBarDate: '2015-06-01', lastBarDate: '2015-06-01' } ) ).toBe(true); const meta = { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' }; const etf = { firstBarDate: '2025-01-01', lastBarDate: '2025-12-31' }; const gap = utcDay('2025-01-01') - utcDay('2022-06-08'); expect(gap).toBe(938); expect(spansOverlap(meta, etf, { toleranceDays: gap - 1 })).toBe(false); expect(spansOverlap(meta, etf, { toleranceDays: gap })).toBe(true); expect(spansOverlap(meta, etf, { toleranceDays: Number.MAX_SAFE_INTEGER - 10_000_000 })).toBe( true ); }); test('rejects ISO timestamps and missing fields instead of guessing', () => { const valid = { firstBarDate: '2024-01-01', lastBarDate: '2024-01-10' }; expect(() => spansOverlap({ firstBarDate: '2024-01-01T00:00:00Z', lastBarDate: '2024-01-10' }, valid) ).toThrow(RangeError); expect(() => spansOverlap({ firstBarDate: '2024-01-01' } as unknown as typeof valid, valid) ).toThrow(RangeError); expect(() => spansOverlap(null as unknown as typeof valid, valid)).toThrow(TypeError); }); test('seeded fuzz: symmetric and equal to a brute-force UTC day-distance oracle', () => { const rand = mulberry32(0xfb); for (let i = 0; i < 10_000; i++) { const aStart = Math.floor(rand() * 400) + 19_000; const aEnd = aStart + Math.floor(rand() * 30); const bStart = Math.floor(rand() * 400) + 19_000; const bEnd = bStart + Math.floor(rand() * 30); const tolerance = Math.floor(rand() * 5); const a = { firstBarDate: ymdFromUtcDay(aStart), lastBarDate: ymdFromUtcDay(aEnd) }; const b = { firstBarDate: ymdFromUtcDay(bStart), lastBarDate: ymdFromUtcDay(bEnd) }; const gap = Math.max(bStart - aEnd, aStart - bEnd); const expected = gap <= tolerance; expect(spansOverlap(a, b, { toleranceDays: tolerance })).toBe(expected); expect(spansOverlap(b, a, { toleranceDays: tolerance })).toBe(expected); } }); });