diff --git a/apps/stock/data-pipeline/src/normalization/bar-spans.ts b/apps/stock/data-pipeline/src/normalization/bar-spans.ts new file mode 100644 index 00000000..e34b078d --- /dev/null +++ b/apps/stock/data-pipeline/src/normalization/bar-spans.ts @@ -0,0 +1,746 @@ +export type BarSpanSource = 'eod' | 'qm'; + +export interface BarSpanCollectionSpec { + readonly source: BarSpanSource; + readonly collection: string; + readonly idField: string; + readonly dateField: string; +} + +export const BAR_SPAN_COLLECTIONS: Readonly> = { + eod: { + source: 'eod', + collection: 'eodPrices', + idField: 'eodSearchCode', + dateField: 'date', + }, + qm: { + source: 'qm', + collection: 'qmPrices', + idField: 'qmSearchCode', + dateField: 'date', + }, +}; + +export interface SpanDateRange { + readonly firstBarDate: string; + readonly lastBarDate: string; +} + +export interface BarSpan extends SpanDateRange { + readonly source: BarSpanSource; + readonly sourceId: string; + readonly barCount: number; +} + +export interface BarSpanSkipCounts { + invalidId: number; + invalidDate: number; + invalidCount: number; + total: number; +} + +export interface BarSpanSourceStats { + source: BarSpanSource; + collection: string; + batchesRun: number; + rowsRead: number; + spansIndexed: number; + skipped: BarSpanSkipCounts; +} + +export interface BarSpanAggregateOptions { + allowDiskUse?: boolean; + batchSize?: number; +} + +export interface BarSpanAggregateReader { + aggregate = Record>( + collectionName: string, + pipeline: Record[], + options?: BarSpanAggregateOptions + ): Promise | AsyncIterable> | Iterable | AsyncIterable; +} + +export interface ComputeBarSpansOptions { + sources?: readonly BarSpanSource[]; + sourceIdsBySource?: Partial>; + batchSize?: number; + cursorBatchSize?: number; +} + +export interface ComputeBarSpansResult { + index: BarSpanIndex; + bySource: Partial>; + skipped: BarSpanSkipCounts; + totalRowsRead: number; + totalSpans: number; +} + +export interface SpansOverlapOptions { + toleranceDays?: number; +} + +export interface GroupedBarSpanRow extends Record { + _id?: unknown; + firstBarDate?: unknown; + lastBarDate?: unknown; + barCount?: unknown; +} + +const DEFAULT_SOURCES: readonly BarSpanSource[] = ['eod', 'qm']; +const DEFAULT_BATCH_SIZE = 1000; + +const ALLOWED_STAGE_KEYS = new Set(['$match', '$group', '$project', '$sort']); +const FORBIDDEN_WRITE_STAGES = new Set(['$out', '$merge']); + +const CODE_0 = 48; +const CODE_9 = 57; +const CODE_DASH = 45; + +const ISO_DATETIME_TZ_RE = + /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})$/; + +function isBarSpanSource(value: unknown): value is BarSpanSource { + return value === 'eod' || value === 'qm'; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function daysInMonth(year: number, month: number): number { + switch (month) { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + return 31; + case 4: + case 6: + case 9: + case 11: + return 30; + case 2: + return isLeapYear(year) ? 29 : 28; + default: + return 0; + } +} + +/** + * Proleptic Gregorian calendar date to days since 1970-01-01 (Howard Hinnant's algorithm). + * Pure integer math: no Date allocation, immune to local timezone and DST. + */ +function daysFromCivil(year: number, month: number, day: number): number { + const y = month <= 2 ? year - 1 : year; + const era = Math.floor(y / 400); + const yoe = y - era * 400; + const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1; + const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy; + return era * 146097 + doe - 719468; +} + +/** Inverse of `daysFromCivil`: days since 1970-01-01 to proleptic Gregorian (year, month, day). */ +function civilFromDays(daysSinceEpoch: number): { year: number; month: number; day: number } { + const shifted = daysSinceEpoch + 719468; + const era = Math.floor(shifted / 146097); + const doe = shifted - era * 146097; + const yoe = Math.floor( + (doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365 + ); + const y = yoe + era * 400; + const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100)); + const mp = Math.floor((5 * doy + 2) / 153); + const day = doy - Math.floor((153 * mp + 2) / 5) + 1; + const month = mp + (mp < 10 ? 3 : -9); + const year = y + (month <= 2 ? 1 : 0); + return { year, month, day }; +} + +function formatUtcYmd(year: number, month: number, day: number): string { + const y = String(year).padStart(4, '0'); + const m = month < 10 ? '0' + String(month) : String(month); + const d = day < 10 ? '0' + String(day) : String(day); + return `${y}-${m}-${d}`; +} + +function parseAsciiDigit(str: string, index: number): number { + const code = str.charCodeAt(index); + return code >= CODE_0 && code <= CODE_9 ? code - CODE_0 : -1; +} + +function parseYmdComponents(str: string): { year: number; month: number; day: number } | null { + if (str.length !== 10 || str.charCodeAt(4) !== CODE_DASH || str.charCodeAt(7) !== CODE_DASH) { + return null; + } + const y0 = parseAsciiDigit(str, 0); + const y1 = parseAsciiDigit(str, 1); + const y2 = parseAsciiDigit(str, 2); + const y3 = parseAsciiDigit(str, 3); + const m0 = parseAsciiDigit(str, 5); + const m1 = parseAsciiDigit(str, 6); + const d0 = parseAsciiDigit(str, 8); + const d1 = parseAsciiDigit(str, 9); + if ((y0 | y1 | y2 | y3 | m0 | m1 | d0 | d1) < 0) { + return null; + } + const year = y0 * 1000 + y1 * 100 + y2 * 10 + y3; + const month = m0 * 10 + m1; + const day = d0 * 10 + d1; + if (year < 1 || year > 9999 || month < 1 || month > 12) { + return null; + } + if (day < 1 || day > daysInMonth(year, month)) { + return null; + } + return { year, month, day }; +} + +function parseUtcDayNumber(ymd: string): number | null { + if (typeof ymd !== 'string') { + return null; + } + const parsed = parseYmdComponents(ymd); + if (parsed === null) { + return null; + } + return daysFromCivil(parsed.year, parsed.month, parsed.day); +} + +/** + * Normalizes a bar date value into a UTC calendar `YYYY-MM-DD` string. + * Accepts: + * - `Date` instances with a finite timestamp and UTC year in `1..9999` + * - Exact `YYYY-MM-DD` calendar strings (validated with strict leap-year rules) + * - ISO-8601 timestamp strings with an explicit timezone (`Z` or `[+-]HH:MM` / `[+-]HHMM`) + * Returns `null` for missing, malformed, timezone-less datetime, or calendar-invalid inputs. + */ +export function normalizeBarDate(value: unknown): string | null { + if (value instanceof Date) { + const ts = value.getTime(); + if (!Number.isFinite(ts)) { + return null; + } + const year = value.getUTCFullYear(); + if (year < 1 || year > 9999) { + return null; + } + return formatUtcYmd(year, value.getUTCMonth() + 1, value.getUTCDate()); + } + + if (typeof value !== 'string') { + return null; + } + + const trimmed = value.trim(); + if (trimmed.length === 10) { + return parseYmdComponents(trimmed) !== null ? trimmed : null; + } + + const match = ISO_DATETIME_TZ_RE.exec(trimmed); + if (match === null) { + return null; + } + + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hour = Number(match[4]); + const minute = Number(match[5]); + const second = match[6] !== undefined ? Number(match[6]) : 0; + const tz = match[8]; + if (tz === undefined) { + return null; + } + + if ( + year < 1 || + year > 9999 || + month < 1 || + month > 12 || + day < 1 || + day > daysInMonth(year, month) || + hour > 23 || + minute > 59 || + second > 59 + ) { + return null; + } + + let offsetMinutes = 0; + if (tz !== 'Z') { + const sign = tz.charCodeAt(0) === CODE_DASH ? -1 : 1; + const tzDigits = tz.length === 6 ? tz.slice(1, 3) + tz.slice(4, 6) : tz.slice(1, 5); + const tzHour = Number(tzDigits.slice(0, 2)); + const tzMinute = Number(tzDigits.slice(2, 4)); + if (tzHour > 23 || tzMinute > 59) { + return null; + } + offsetMinutes = sign * (tzHour * 60 + tzMinute); + } + + const totalUtcMinutes = hour * 60 + minute - offsetMinutes; + const dayShift = Math.floor(totalUtcMinutes / 1440); + const utcDate = civilFromDays(daysFromCivil(year, month, day) + dayShift); + if (utcDate.year < 1 || utcDate.year > 9999) { + return null; + } + return formatUtcYmd(utcDate.year, utcDate.month, utcDate.day); +} + +function scanForForbiddenWriteStages(node: unknown, seen: WeakSet): void { + if (node === null || typeof node !== 'object') { + return; + } + if (seen.has(node)) { + return; + } + seen.add(node); + + if (Array.isArray(node)) { + for (let i = 0; i < node.length; i++) { + scanForForbiddenWriteStages(node[i], seen); + } + return; + } + + for (const [key, val] of Object.entries(node)) { + if (FORBIDDEN_WRITE_STAGES.has(key.toLowerCase())) { + throw new Error(`Bar span pipeline contains forbidden write stage "${key}"`); + } + scanForForbiddenWriteStages(val, seen); + } +} + +/** + * Verifies that an aggregation pipeline contains only read-only bar-span stages + * (`$match`, `$group`, `$project`, `$sort`) and never contains `$out` or `$merge` + * at top level or nested inside sub-pipelines. + */ +export function assertReadOnlyBarSpanPipeline(pipeline: readonly Record[]): void { + if (!Array.isArray(pipeline)) { + throw new TypeError('Bar span pipeline must be an array of stage objects'); + } + const seen = new WeakSet(); + for (let i = 0; i < pipeline.length; i++) { + const stage = pipeline[i]; + if (stage === null || typeof stage !== 'object' || Array.isArray(stage)) { + throw new TypeError(`Bar span pipeline stage at index ${i} must be a plain object`); + } + const keys = Object.keys(stage); + if (keys.length === 0) { + throw new Error(`Bar span pipeline stage at index ${i} is empty`); + } + for (const key of keys) { + if (FORBIDDEN_WRITE_STAGES.has(key.toLowerCase())) { + throw new Error(`Bar span pipeline contains forbidden write stage "${key}"`); + } + if (!ALLOWED_STAGE_KEYS.has(key)) { + throw new Error( + `Bar span pipeline stage "${key}" at index ${i} is not an allowed read-only stage` + ); + } + } + scanForForbiddenWriteStages(stage, seen); + } +} + +/** + * Builds the read-only aggregation pipeline for `eodPrices`. + * - Full mode (`sourceIds === undefined`): single-pass `$group` by `eodSearchCode` (run with `allowDiskUse: true`). + * - Targeted mode (`sourceIds` provided): `$match` on `eodSearchCode: { $in: [...] }` followed by `$group`. + */ +export function buildEodBarSpansPipeline(sourceIds?: readonly string[]): Record[] { + const groupStage: Record = { + $group: { + _id: '$eodSearchCode', + firstBarDate: { $min: '$date' }, + lastBarDate: { $max: '$date' }, + barCount: { $sum: 1 }, + }, + }; + const pipeline: Record[] = + sourceIds !== undefined + ? [{ $match: { eodSearchCode: { $in: [...sourceIds] } } }, groupStage] + : [groupStage]; + assertReadOnlyBarSpanPipeline(pipeline); + return pipeline; +} + +/** + * Builds the read-only aggregation pipeline for `qmPrices`. + * - Full mode (`sourceIds === undefined`): `$sort` on `{ qmSearchCode: 1, date: 1 }` to leverage + * the compound index, followed by `$group` by `qmSearchCode`. + * - Targeted mode (`sourceIds` provided): `$match` on `qmSearchCode: { $in: [...] }` followed by `$group`. + */ +export function buildQmBarSpansPipeline(sourceIds?: readonly string[]): Record[] { + const groupStage: Record = { + $group: { + _id: '$qmSearchCode', + firstBarDate: { $min: '$date' }, + lastBarDate: { $max: '$date' }, + barCount: { $sum: 1 }, + }, + }; + const pipeline: Record[] = + sourceIds !== undefined + ? [{ $match: { qmSearchCode: { $in: [...sourceIds] } } }, groupStage] + : [{ $sort: { qmSearchCode: 1, date: 1 } }, groupStage]; + assertReadOnlyBarSpanPipeline(pipeline); + return pipeline; +} + +/** Dispatches to the per-source read-only bar-span pipeline builder. */ +export function buildBarSpansPipeline( + source: BarSpanSource, + sourceIds?: readonly string[] +): Record[] { + if (source === 'eod') { + return buildEodBarSpansPipeline(sourceIds); + } + if (source === 'qm') { + return buildQmBarSpansPipeline(sourceIds); + } + throw new RangeError(`Unsupported bar span source: "${String(source)}"`); +} + +/** + * In-memory lookup of observed `[firstBarDate, lastBarDate]` spans keyed by `(source, sourceId)`. + * Uses per-source `Map`s to avoid composite key string allocations on large symbol sets. + */ +export class BarSpanIndex { + private readonly bySource: Readonly>> = { + eod: new Map(), + qm: new Map(), + }; + + /** Inserts a span or merges it into an existing `(source, sourceId)` entry. */ + merge(span: BarSpan): void { + const map = this.bySource[span.source]; + const existing = map.get(span.sourceId); + if (existing === undefined) { + map.set(span.sourceId, span); + return; + } + const firstBarDate = + span.firstBarDate < existing.firstBarDate ? span.firstBarDate : existing.firstBarDate; + const lastBarDate = + span.lastBarDate > existing.lastBarDate ? span.lastBarDate : existing.lastBarDate; + map.set(span.sourceId, { + source: existing.source, + sourceId: existing.sourceId, + firstBarDate, + lastBarDate, + barCount: existing.barCount + span.barCount, + }); + } + + /** Returns the observed span for `(source, sourceId)`, or `undefined` when absent. */ + get(source: BarSpanSource, sourceId: string): BarSpan | undefined { + return this.bySource[source]?.get(sourceId); + } + + has(source: BarSpanSource, sourceId: string): boolean { + return this.bySource[source]?.has(sourceId) ?? false; + } + + get size(): number { + return this.bySource.eod.size + this.bySource.qm.size; + } + + sizeForSource(source: BarSpanSource): number { + return this.bySource[source]?.size ?? 0; + } + + *values(): IterableIterator { + yield* this.bySource.eod.values(); + yield* this.bySource.qm.values(); + } + + [Symbol.iterator](): IterableIterator { + return this.values(); + } +} + +function createEmptySkipCounts(): BarSpanSkipCounts { + return { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 }; +} + +function isSyncIterable(value: unknown): value is Iterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.iterator] === 'function' + ); +} + +function isAsyncIterable(value: unknown): value is AsyncIterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.asyncIterator] === 'function' + ); +} + +function validatePositiveSafeInt(value: number, name: string): void { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`); + } +} + +function normalizeRequestedSourceIds(source: BarSpanSource, rawIds: readonly string[]): string[] { + if (!Array.isArray(rawIds)) { + throw new TypeError(`sourceIdsBySource.${source} must be an array of strings`); + } + const seen = new Set(); + const deduped: string[] = []; + for (let i = 0; i < rawIds.length; i++) { + const raw = rawIds[i]; + if (typeof raw !== 'string') { + throw new TypeError( + `sourceIdsBySource.${source}[${i}] must be a string, received ${typeof raw}` + ); + } + const trimmed = raw.trim(); + if (trimmed.length === 0 || seen.has(trimmed)) { + continue; + } + seen.add(trimmed); + deduped.push(trimmed); + } + return deduped; +} + +function foldGroupedRow( + source: BarSpanSource, + row: unknown, + index: BarSpanIndex, + sourceSkipped: BarSpanSkipCounts, + totalSkipped: BarSpanSkipCounts +): void { + if (row === null || typeof row !== 'object') { + sourceSkipped.invalidId++; + sourceSkipped.total++; + totalSkipped.invalidId++; + totalSkipped.total++; + return; + } + + const record = row as GroupedBarSpanRow; + if (typeof record._id !== 'string') { + sourceSkipped.invalidId++; + sourceSkipped.total++; + totalSkipped.invalidId++; + totalSkipped.total++; + return; + } + + const sourceId = record._id.trim(); + if (sourceId.length === 0) { + sourceSkipped.invalidId++; + sourceSkipped.total++; + totalSkipped.invalidId++; + totalSkipped.total++; + return; + } + + const firstBarDate = normalizeBarDate(record.firstBarDate); + const lastBarDate = normalizeBarDate(record.lastBarDate); + if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) { + sourceSkipped.invalidDate++; + sourceSkipped.total++; + totalSkipped.invalidDate++; + totalSkipped.total++; + return; + } + + const barCount = record.barCount; + if (typeof barCount !== 'number' || !Number.isSafeInteger(barCount) || barCount <= 0) { + sourceSkipped.invalidCount++; + sourceSkipped.total++; + totalSkipped.invalidCount++; + totalSkipped.total++; + return; + } + + index.merge({ + source, + sourceId, + firstBarDate, + lastBarDate, + barCount, + }); +} + +/** + * Streams grouped `[firstBarDate, lastBarDate]` spans from an injected read-only MongoDB reader + * into a `BarSpanIndex` without buffering raw price documents or intermediate row arrays. + */ +export async function computeBarSpans( + reader: BarSpanAggregateReader, + options: ComputeBarSpansOptions = {} +): Promise { + if (reader === null || typeof reader !== 'object' || typeof reader.aggregate !== 'function') { + throw new TypeError('reader must implement aggregate(collectionName, pipeline, options)'); + } + + const rawSources = options.sources ?? DEFAULT_SOURCES; + if (!Array.isArray(rawSources) || rawSources.length === 0) { + throw new RangeError('options.sources must be a non-empty array of supported sources'); + } + + const sources: BarSpanSource[] = []; + const seenSources = new Set(); + for (const source of rawSources) { + if (!isBarSpanSource(source)) { + throw new RangeError(`Unsupported bar span source: "${String(source)}"`); + } + if (!seenSources.has(source)) { + seenSources.add(source); + sources.push(source); + } + } + + const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE; + validatePositiveSafeInt(batchSize, 'options.batchSize'); + + if (options.cursorBatchSize !== undefined) { + validatePositiveSafeInt(options.cursorBatchSize, 'options.cursorBatchSize'); + } + + const preparedSourceIds: Partial> = {}; + if (options.sourceIdsBySource !== undefined) { + for (const key of Object.keys(options.sourceIdsBySource)) { + if (!isBarSpanSource(key)) { + throw new RangeError(`Unsupported source in options.sourceIdsBySource: "${key}"`); + } + const list = options.sourceIdsBySource[key]; + if (list !== undefined) { + preparedSourceIds[key] = normalizeRequestedSourceIds(key, list); + } + } + } + + const aggOptions: BarSpanAggregateOptions = + options.cursorBatchSize !== undefined + ? { allowDiskUse: true, batchSize: options.cursorBatchSize } + : { allowDiskUse: true }; + + const index = new BarSpanIndex(); + const bySource: Partial> = {}; + const totalSkipped = createEmptySkipCounts(); + let totalRowsRead = 0; + + for (const source of sources) { + const spec = BAR_SPAN_COLLECTIONS[source]; + const sourceSkipped = createEmptySkipCounts(); + let batchesRun = 0; + let sourceRowsRead = 0; + + const targetIds = preparedSourceIds[source]; + const pipelines: Record[][] = []; + if (targetIds === undefined) { + pipelines.push(buildBarSpansPipeline(source)); + } else if (targetIds.length > 0) { + for (let offset = 0; offset < targetIds.length; offset += batchSize) { + pipelines.push(buildBarSpansPipeline(source, targetIds.slice(offset, offset + batchSize))); + } + } + + for (const pipeline of pipelines) { + batchesRun++; + try { + const rows = await reader.aggregate( + spec.collection, + pipeline, + aggOptions + ); + if (isSyncIterable(rows)) { + for (const row of rows) { + sourceRowsRead++; + totalRowsRead++; + foldGroupedRow(source, row, index, sourceSkipped, totalSkipped); + } + } else if (isAsyncIterable(rows)) { + for await (const row of rows) { + sourceRowsRead++; + totalRowsRead++; + foldGroupedRow(source, row, index, sourceSkipped, totalSkipped); + } + } else { + throw new TypeError('reader.aggregate() must return an Iterable or AsyncIterable'); + } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new Error( + `Failed to compute bar spans for source "${source}" (collection "${spec.collection}"): ${detail}`, + { cause: error } + ); + } + } + + bySource[source] = { + source, + collection: spec.collection, + batchesRun, + rowsRead: sourceRowsRead, + spansIndexed: index.sizeForSource(source), + skipped: sourceSkipped, + }; + } + + return { + index, + bySource, + skipped: totalSkipped, + totalRowsRead, + totalSpans: index.size, + }; +} + +/** + * Checks whether two observed `[firstBarDate, lastBarDate]` ranges overlap inclusively, + * optionally allowing a non-negative integer `toleranceDays` gap in UTC calendar days. + */ +export function spansOverlap( + a: SpanDateRange, + b: SpanDateRange, + options: SpansOverlapOptions = {} +): boolean { + const toleranceDays = options.toleranceDays ?? 0; + if ( + typeof toleranceDays !== 'number' || + !Number.isSafeInteger(toleranceDays) || + toleranceDays < 0 + ) { + throw new RangeError( + `options.toleranceDays must be a non-negative safe integer, received ${String(toleranceDays)}` + ); + } + + if (a === null || typeof a !== 'object' || b === null || typeof b !== 'object') { + throw new TypeError('spansOverlap requires two valid span objects'); + } + + const aStart = parseUtcDayNumber(a.firstBarDate); + const aEnd = parseUtcDayNumber(a.lastBarDate); + if (aStart === null || aEnd === null || aStart > aEnd) { + throw new RangeError( + `Invalid first span date range: [${String(a.firstBarDate)}, ${String(a.lastBarDate)}]` + ); + } + + const bStart = parseUtcDayNumber(b.firstBarDate); + const bEnd = parseUtcDayNumber(b.lastBarDate); + if (bStart === null || bEnd === null || bStart > bEnd) { + throw new RangeError( + `Invalid second span date range: [${String(b.firstBarDate)}, ${String(b.lastBarDate)}]` + ); + } + + return aStart <= bEnd + toleranceDays && bStart <= aEnd + toleranceDays; +} diff --git a/test/unit/normalization-bar-spans.test.ts b/test/unit/normalization-bar-spans.test.ts new file mode 100644 index 00000000..0b160c40 --- /dev/null +++ b/test/unit/normalization-bar-spans.test.ts @@ -0,0 +1,561 @@ +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).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[]; + options?: BarSpanAggregateOptions; + }> = []; + + const reader: BarSpanAggregateReader = { + async aggregate>( + collectionName: string, + pipeline: Record[], + options?: BarSpanAggregateOptions + ): Promise { + 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) + 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, + }); + }); +});