diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 0d31cee1..a1998de5 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -64,6 +64,21 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto - **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside inclusive `[1 - 0.02, 1 + 0.02]`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`. - **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload. +## Pass 4a Sample-Close & USD/CAD Reader (`sample-closes.ts`) +`apps/stock/data-pipeline/src/security-master/sample-closes.ts` provides the read-only MongoDB reader (`buildSampleCloseFilter`, `readSampleCloses`) that streams cross-sectional sample closes from `eodPrices`, `qmPrices`, and `CAD.FOREX` into `SampleCloseRecord[]` and `FxRateByDateRecord[]` for `crossCheckPrices`: + +- **Date storage finding & `$in` type:** Both `eodPrices` (`apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts`) and `qmPrices` (`apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts`) persist `date` as an exact `YYYY-MM-DD` string (`qmPrices` stores the BSON `Date` separately in `dateTime`), aligning with `BAR_SPAN_COLLECTIONS` in `src/normalization/bar-spans.ts` and `design/DATA-CONTRACTS.md`. `buildSampleCloseFilter` therefore emits date-first `{ date: { $in: string[] } }` filters (sorted `YYYY-MM-DD` strings) so queries use `{ date: 1, eodSearchCode: 1 }` and `{ qmSearchCode: 1, date: 1 }`. On decode, both `Date` instances and string dates are normalized to UTC `YYYY-MM-DD` via `normalizeBarDate`; if any legacy rows stored BSON `Date` directly in `date`, they would not match a string `$in`, so row counts should be checked on the first live Pass 4 run. +- **Read-only streaming, raw prices, and FX isolation:** Uses `ReadOnlySourceSymbolReader` (rejecting non-read-only readers before any `find` and rejecting buffered array results with `TypeError`), closes cursors in `finally` on success and error, projects only `_id: 0`, id, `date`, and raw `close` (`eodPrices` / `CAD.FOREX`) or raw `unadjustedclose` (`qmPrices` — never `close` or `adjustedclose`), strips `CAD.FOREX` from equity reads so FX never leaks into `closes`, preserves untrimmed non-blank IDs (T-49), chunks large ID sets (`idChunkSize`, default `10,000`), skips empty sources (`findsRun: 0`), and reconciles `docsRead === emitted + skippedTotal` per source. +- **Local synthetic benchmark (zero MongoDB):** Run the headless 500,025-doc streaming benchmark with: + +```bash +bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts +``` + +- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** + - Workload: `500,025` synthetic docs (`25` sample dates × `20,000` IDs split `10,000` `eodPrices` + `10,000` `qmPrices`, plus `25` `CAD.FOREX` FX docs). + - Observed throughput: `2,627,752 docs/s` (`190.3 ms` elapsed, `25.36 MiB` heap delta). + ## Security Master Persistence (`persistSecurityMaster`) `apps/stock/data-pipeline/src/security-master/persist.ts` persists in-memory Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 (`delisting-chains`) results into the `master` track PostgreSQL tables inside a single transaction guarded by `pg_advisory_xact_lock(0x534d5053, hashtext(current_schema()))`: diff --git a/apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts b/apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts new file mode 100644 index 00000000..b2428c16 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts @@ -0,0 +1,187 @@ +/** + * Reproducible headless benchmark for Pass 4a `readSampleCloses`. + * Streams 500,025 synthetic documents (25 sample dates × 20,000 IDs split across + * eodPrices + qmPrices, plus 25 CAD.FOREX FX documents) through an in-memory + * async-generator fake reader with zero MongoDB or network dependencies. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts + */ + +import { + FX_USD_CAD_SOURCE_ID, + readSampleCloses, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SampleCloseSourceReadStats, +} from '../src/security-master/sample-closes'; + +const SAMPLE_DATE_COUNT = 25; +const EOD_ID_COUNT = 10_000; +const QM_ID_COUNT = 10_000; + +function buildSampleDates(count: number): string[] { + const dates: string[] = []; + let year = 2024; + let month = 1; + let day = 2; + while (dates.length < count) { + dates.push( + `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}` + ); + day += 14; + if (day > 28) { + day -= 28; + month += 1; + if (month > 12) { + month = 1; + year += 1; + } + } + } + return dates; +} + +function buildIds(prefix: string, suffix: string, count: number): string[] { + const ids = new Array(count); + for (let i = 0; i < count; i++) { + ids[i] = `${prefix}${String(i).padStart(5, '0')}${suffix}`; + } + return ids; +} + +function assertStatsReconcile(label: string, stats: SampleCloseSourceReadStats): void { + const skipSum = + stats.skipped.missingId + + stats.skipped.unrequestedId + + stats.skipped.invalidDate + + stats.skipped.unrequestedDate + + stats.skipped.invalidClose; + if (stats.skippedTotal !== skipSum || stats.docsRead !== stats.emitted + stats.skippedTotal) { + throw new Error( + `Stats reconciliation failed for ${label}: docsRead=${stats.docsRead}, emitted=${stats.emitted}, skippedTotal=${stats.skippedTotal}, skipSum=${skipSum}` + ); + } +} + +function createStreamingBenchmarkReader( + sampleDates: readonly string[], + eodIds: readonly string[], + qmIds: readonly string[] +): ReadOnlySourceSymbolReader { + return { + isReadOnly(): boolean { + return true; + }, + find = Record>( + collectionName: string, + filter?: Record + ): ReadOnlySourceSymbolCursor { + const idFilter = + collectionName === 'eodPrices' + ? ((filter?.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) + : ((filter?.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []); + + const isFxCall = + collectionName === 'eodPrices' && + idFilter.length === 1 && + idFilter[0] === FX_USD_CAD_SOURCE_ID; + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + if (isFxCall) { + for (let d = 0; d < sampleDates.length; d++) { + yield { + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date: sampleDates[d], + close: 1.34 + (d % 7) * 0.005, + } as unknown as T; + } + return; + } + + if (collectionName === 'eodPrices') { + const ids = idFilter.length > 0 ? idFilter : eodIds; + for (let d = 0; d < sampleDates.length; d++) { + const date = sampleDates[d]; + for (let i = 0; i < ids.length; i++) { + yield { + eodSearchCode: ids[i], + date, + close: 10 + ((i + d) % 250) + 0.25, + } as unknown as T; + } + } + return; + } + + if (collectionName === 'qmPrices') { + const ids = idFilter.length > 0 ? idFilter : qmIds; + for (let d = 0; d < sampleDates.length; d++) { + const date = sampleDates[d]; + for (let i = 0; i < ids.length; i++) { + yield { + qmSearchCode: ids[i], + date, + unadjustedclose: 10 + ((i + d) % 250) + 0.25, + } as unknown as T; + } + } + } + }, + async close(): Promise { + // No-op for in-memory benchmark cursor. + }, + }; + }, + }; +} + +async function main(): Promise { + const sampleDates = buildSampleDates(SAMPLE_DATE_COUNT); + const eodIds = buildIds('EOD', '.US', EOD_ID_COUNT); + const qmIds = buildIds('QM', '', QM_ID_COUNT); + const reader = createStreamingBenchmarkReader(sampleDates, eodIds, qmIds); + + if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { + Bun.gc(true); + } + const heapBefore = process.memoryUsage().heapUsed; + const startedAt = performance.now(); + + const result = await readSampleCloses(reader, { + sampleDates, + sourceIdsBySource: { eod: eodIds, qm: qmIds }, + batchSize: 5_000, + }); + + const elapsedMs = performance.now() - startedAt; + const heapAfter = process.memoryUsage().heapUsed; + const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); + + assertStatsReconcile('eod', result.stats.eod); + assertStatsReconcile('qm', result.stats.qm); + assertStatsReconcile('fx', result.stats.fx); + + const totalDocsRead = + result.stats.eod.docsRead + result.stats.qm.docsRead + result.stats.fx.docsRead; + const expectedEquityDocs = SAMPLE_DATE_COUNT * (EOD_ID_COUNT + QM_ID_COUNT); + if (result.closes.length !== expectedEquityDocs || result.fxRates.length !== SAMPLE_DATE_COUNT) { + throw new Error( + `Unexpected emitted counts: closes=${result.closes.length} (expected ${expectedEquityDocs}), fxRates=${result.fxRates.length} (expected ${SAMPLE_DATE_COUNT})` + ); + } + + const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000)); + const lines = [ + 'Pass 4a sample-closes benchmark (in-memory async cursor, zero MongoDB)', + ` Workload: ${totalDocsRead.toLocaleString('en-US')} docs (${SAMPLE_DATE_COUNT} dates x ${(EOD_ID_COUNT + QM_ID_COUNT).toLocaleString('en-US')} ids + ${SAMPLE_DATE_COUNT} FX)`, + ` Emitted: ${result.closes.length.toLocaleString('en-US')} closes, ${result.fxRates.length.toLocaleString('en-US')} fxRates`, + ` Elapsed: ${elapsedMs.toFixed(1)} ms`, + ` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`, + ` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`, + ]; + process.stdout.write(`${lines.join('\n')}\n`); +} + +await main(); diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 7fd47256..0d6c305a 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -229,6 +229,24 @@ export { type SecurityMasterPostgresHandle, } from './run-security-master'; +export { + buildSampleCloseFilter, + DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE, + EOD_SAMPLE_CLOSES_PROJECTION, + FX_USD_CAD_SOURCE_ID, + MAX_SAMPLE_DATES, + QM_SAMPLE_CLOSES_PROJECTION, + readSampleCloses, + type ReadSampleClosesOptions, + type ReadSampleClosesResult, + type ReadSampleClosesStats, + type SampleCloseSkipCounts, + type SampleCloseSkipReason, + type SampleCloseSource, + type SampleCloseSourceIdsBySource, + type SampleCloseSourceReadStats, +} from './sample-closes'; + export { buildSecurityTypeByIsin, buildSecurityTypeByIsinForStageA, diff --git a/apps/stock/data-pipeline/src/security-master/sample-closes.ts b/apps/stock/data-pipeline/src/security-master/sample-closes.ts new file mode 100644 index 00000000..bd44423b --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/sample-closes.ts @@ -0,0 +1,506 @@ +import { + BAR_SPAN_COLLECTIONS, + normalizeBarDate, + type BarSpanSource, +} from '../normalization/bar-spans'; +import { compareAscii } from './exchange-pass1'; +import type { FxRateByDateRecord, SampleCloseRecord } from './price-cross-check'; +import type { + ReadOnlySourceSymbolCursor, + ReadOnlySourceSymbolReader, + SourceSymbolFindOptions, +} from './source-symbol-readers'; + +export type SampleCloseSource = BarSpanSource; + +export const MAX_SAMPLE_DATES = 64; +export const DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE = 10_000; +export const FX_USD_CAD_SOURCE_ID = 'CAD.FOREX'; + +export const EOD_SAMPLE_CLOSES_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + [BAR_SPAN_COLLECTIONS.eod.idField]: 1, + [BAR_SPAN_COLLECTIONS.eod.dateField]: 1, + close: 1, +}); + +export const QM_SAMPLE_CLOSES_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + [BAR_SPAN_COLLECTIONS.qm.idField]: 1, + [BAR_SPAN_COLLECTIONS.qm.dateField]: 1, + unadjustedclose: 1, +}); + +export interface SampleCloseSourceIdsBySource { + readonly eod: readonly string[]; + readonly qm: readonly string[]; +} + +export interface ReadSampleClosesOptions { + readonly sampleDates: readonly string[]; + readonly sourceIdsBySource: SampleCloseSourceIdsBySource; + readonly includeFx?: boolean; + readonly batchSize?: number; + readonly idChunkSize?: number; +} + +export interface SampleCloseSkipCounts { + missingId: number; + unrequestedId: number; + invalidDate: number; + unrequestedDate: number; + invalidClose: number; +} + +export type SampleCloseSkipReason = keyof SampleCloseSkipCounts; + +export interface SampleCloseSourceReadStats { + collection: string; + findsRun: number; + docsRead: number; + emitted: number; + skippedTotal: number; + skipped: SampleCloseSkipCounts; +} + +export interface ReadSampleClosesStats { + eod: SampleCloseSourceReadStats; + qm: SampleCloseSourceReadStats; + fx: SampleCloseSourceReadStats; +} + +export interface ReadSampleClosesResult { + sampleDates: string[]; + closes: SampleCloseRecord[]; + fxRates: FxRateByDateRecord[]; + stats: ReadSampleClosesStats; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +function isSampleCloseSource(value: unknown): value is SampleCloseSource { + return value === 'eod' || value === 'qm'; +} + +function isPlainRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +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: unknown, name: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`); + } + return value; +} + +function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { + if ( + reader === null || + reader === undefined || + typeof reader !== 'object' || + typeof reader.isReadOnly !== 'function' || + typeof reader.find !== 'function' || + reader.isReadOnly() !== true + ) { + throw new Error( + 'Sample close reader requires a read-only MongoDB reader (isReadOnly() must be true)' + ); + } +} + +/** + * Validates, deduplicates, and ASCII-sorts exact Gregorian `YYYY-MM-DD` sample dates. + * Rejects empty lists, malformed/padded/rollover dates, and lists exceeding `MAX_SAMPLE_DATES`. + */ +function normalizeSampleDates(sampleDates: readonly string[]): string[] { + if (!Array.isArray(sampleDates)) { + throw new RangeError('sampleDates must be a non-empty array of YYYY-MM-DD strings'); + } + if (sampleDates.length === 0) { + throw new RangeError('sampleDates must not be empty'); + } + + const unique = new Set(); + for (let i = 0; i < sampleDates.length; i++) { + const raw = sampleDates[i]; + if ( + typeof raw !== 'string' || + !EXACT_YMD_PATTERN.test(raw) || + normalizeBarDate(raw) !== raw + ) { + throw new RangeError( + `sampleDates[${i}] must be a valid exact YYYY-MM-DD date, received ${JSON.stringify(raw)}` + ); + } + unique.add(raw); + } + + if (unique.size > MAX_SAMPLE_DATES) { + throw new RangeError( + `sampleDates exceeds maximum allowed count of ${MAX_SAMPLE_DATES} (received ${unique.size})` + ); + } + + return Array.from(unique).sort(compareAscii); +} + +/** + * Validates, deduplicates, and ASCII-sorts requested source IDs without trimming non-blank strings + * (T-49). Whitespace-only entries are dropped; `CAD.FOREX` is excluded when `excludeFx` is true. + */ +function normalizeRequestedIds( + rawIds: readonly string[], + fieldName: string, + options?: { readonly excludeFx?: boolean } +): string[] { + if (!Array.isArray(rawIds)) { + throw new TypeError(`${fieldName} must be an array of strings`); + } + + const excludeFx = options?.excludeFx === true; + const unique = new Set(); + for (let i = 0; i < rawIds.length; i++) { + const raw = rawIds[i]; + if (typeof raw !== 'string') { + throw new TypeError(`${fieldName}[${i}] must be a string, received ${typeof raw}`); + } + if (raw.trim().length === 0) { + continue; + } + if (excludeFx && raw === FX_USD_CAD_SOURCE_ID) { + continue; + } + unique.add(raw); + } + + return Array.from(unique).sort(compareAscii); +} + +function createEmptySkipCounts(): SampleCloseSkipCounts { + return { + missingId: 0, + unrequestedId: 0, + invalidDate: 0, + unrequestedDate: 0, + invalidClose: 0, + }; +} + +function createSourceStats(collection: string): SampleCloseSourceReadStats { + return { + collection, + findsRun: 0, + docsRead: 0, + emitted: 0, + skippedTotal: 0, + skipped: createEmptySkipCounts(), + }; +} + +function recordSkip(stats: SampleCloseSourceReadStats, reason: SampleCloseSkipReason): void { + stats.skipped[reason] += 1; + stats.skippedTotal += 1; +} + +function wrapCollectionReadError(collectionName: string, error: unknown): Error { + const detail = error instanceof Error ? error.message : String(error); + const message = detail.includes(collectionName) + ? detail + : `Failed reading collection "${collectionName}": ${detail}`; + return new Error(message, { cause: error }); +} + +async function streamSampleCloseFind( + reader: ReadOnlySourceSymbolReader, + collectionName: string, + filter: Record, + findOptions: SourceSymbolFindOptions, + onDoc: (doc: unknown) => void +): Promise { + assertReadOnlyReader(reader); + let cursor: ReadOnlySourceSymbolCursor> | null = null; + let primaryError: unknown = undefined; + let hasPrimaryError = false; + + try { + const rawCursor = await reader.find>( + collectionName, + filter, + findOptions + ); + if (Array.isArray(rawCursor) || !isAsyncIterable>(rawCursor)) { + throw new TypeError( + `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)` + ); + } + cursor = rawCursor as ReadOnlySourceSymbolCursor>; + for await (const doc of cursor) { + onDoc(doc); + } + } catch (error) { + primaryError = error; + hasPrimaryError = true; + } finally { + if (cursor !== null && typeof cursor.close === 'function') { + try { + await cursor.close(); + } catch (closeError) { + if (!hasPrimaryError) { + primaryError = closeError; + hasPrimaryError = true; + } + } + } + } + + if (hasPrimaryError) { + if (primaryError instanceof TypeError) { + throw primaryError; + } + throw wrapCollectionReadError(collectionName, primaryError); + } +} + +function compareSampleCloses(a: SampleCloseRecord, b: SampleCloseRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.date, b.date) || + a.close - b.close + ); +} + +function compareFxRates(a: FxRateByDateRecord, b: FxRateByDateRecord): number { + return compareAscii(a.date, b.date) || a.usdCad - b.usdCad; +} + +/** + * Builds a plain date-first MongoDB `find` filter for Pass 4 sample-close queries: + * `{ date: { $in: [...] } }`, optionally AND-ed with `{ eodSearchCode | qmSearchCode: { $in: [...] } }`. + * + * Both `eodPrices` (`price-storage.ts`) and `qmPrices` (`prices.action.ts`) store `date` + * as a `YYYY-MM-DD` string, so `$in` emits sorted `YYYY-MM-DD` strings. + */ +export function buildSampleCloseFilter( + source: SampleCloseSource, + sampleDates: readonly string[], + sourceIds?: readonly string[] +): Record { + if (!isSampleCloseSource(source)) { + throw new RangeError(`Unsupported sample close source: "${String(source)}"`); + } + + const normalizedDates = normalizeSampleDates(sampleDates); + const spec = BAR_SPAN_COLLECTIONS[source]; + const filter: Record = { + [spec.dateField]: { $in: normalizedDates }, + }; + + if (sourceIds !== undefined) { + const normalizedIds = normalizeRequestedIds(sourceIds, 'sourceIds'); + filter[spec.idField] = { $in: normalizedIds }; + } + + return filter; +} + +/** + * Streams read-only Pass 4 sample closes from `eodPrices` (raw `close`), `qmPrices` + * (raw `unadjustedclose`), and USD/CAD FX rates from `eodPrices` (`CAD.FOREX`) using + * date-first `{ date: { $in: sampleDates } }` filters over `ReadOnlySourceSymbolReader`. + */ +export async function readSampleCloses( + reader: ReadOnlySourceSymbolReader, + options: ReadSampleClosesOptions +): Promise { + assertReadOnlyReader(reader); + + if (options === null || typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + if (options.sourceIdsBySource === null || typeof options.sourceIdsBySource !== 'object') { + throw new TypeError('options.sourceIdsBySource must be an object'); + } + + const sampleDates = normalizeSampleDates(options.sampleDates); + const sampleDateSet = new Set(sampleDates); + + const eodIds = normalizeRequestedIds(options.sourceIdsBySource.eod, 'sourceIdsBySource.eod', { + excludeFx: true, + }); + const qmIds = normalizeRequestedIds(options.sourceIdsBySource.qm, 'sourceIdsBySource.qm'); + + const includeFx = options.includeFx ?? true; + if (typeof includeFx !== 'boolean') { + throw new TypeError('options.includeFx must be a boolean'); + } + + const batchSize = + options.batchSize !== undefined + ? validatePositiveSafeInt(options.batchSize, 'options.batchSize') + : undefined; + const idChunkSize = + options.idChunkSize !== undefined + ? validatePositiveSafeInt(options.idChunkSize, 'options.idChunkSize') + : DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE; + + const eodFindOptions: SourceSymbolFindOptions = + batchSize !== undefined + ? { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, batchSize } + : { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION } }; + const qmFindOptions: SourceSymbolFindOptions = + batchSize !== undefined + ? { projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, batchSize } + : { projection: { ...QM_SAMPLE_CLOSES_PROJECTION } }; + + const stats: ReadSampleClosesStats = { + eod: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection), + qm: createSourceStats(BAR_SPAN_COLLECTIONS.qm.collection), + fx: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection), + }; + + const closes: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + + const readEquitySource = async ( + source: SampleCloseSource, + ids: readonly string[], + findOptions: SourceSymbolFindOptions + ): Promise => { + if (ids.length === 0) { + return; + } + + const spec = BAR_SPAN_COLLECTIONS[source]; + const closeField = source === 'eod' ? 'close' : 'unadjustedclose'; + const sourceStats = stats[source]; + + for (let offset = 0; offset < ids.length; offset += idChunkSize) { + const chunkIds = ids.slice(offset, offset + idChunkSize); + const chunkIdSet = new Set(chunkIds); + const filter = buildSampleCloseFilter(source, sampleDates, chunkIds); + sourceStats.findsRun += 1; + + await streamSampleCloseFind(reader, spec.collection, filter, findOptions, doc => { + sourceStats.docsRead += 1; + + if (!isPlainRecord(doc)) { + recordSkip(sourceStats, 'missingId'); + return; + } + + const rawId = doc[spec.idField]; + if (typeof rawId !== 'string' || rawId.trim().length === 0) { + recordSkip(sourceStats, 'missingId'); + return; + } + + if (!chunkIdSet.has(rawId)) { + recordSkip(sourceStats, 'unrequestedId'); + return; + } + + const rawDate = doc[spec.dateField]; + const normalizedDate = + typeof rawDate === 'string' && sampleDateSet.has(rawDate) + ? rawDate + : normalizeBarDate(rawDate); + if (normalizedDate === null) { + recordSkip(sourceStats, 'invalidDate'); + return; + } + if (!sampleDateSet.has(normalizedDate)) { + recordSkip(sourceStats, 'unrequestedDate'); + return; + } + + const rawClose = doc[closeField]; + if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) { + recordSkip(sourceStats, 'invalidClose'); + return; + } + + closes.push({ + source, + sourceId: rawId, + date: normalizedDate, + close: rawClose, + }); + sourceStats.emitted += 1; + }); + } + }; + + await readEquitySource('eod', eodIds, eodFindOptions); + await readEquitySource('qm', qmIds, qmFindOptions); + + if (includeFx) { + const eodSpec = BAR_SPAN_COLLECTIONS.eod; + const fxFilter = buildSampleCloseFilter('eod', sampleDates, [FX_USD_CAD_SOURCE_ID]); + stats.fx.findsRun += 1; + + await streamSampleCloseFind(reader, eodSpec.collection, fxFilter, eodFindOptions, doc => { + stats.fx.docsRead += 1; + + if (!isPlainRecord(doc)) { + recordSkip(stats.fx, 'missingId'); + return; + } + + const rawId = doc[eodSpec.idField]; + if (typeof rawId !== 'string' || rawId.trim().length === 0) { + recordSkip(stats.fx, 'missingId'); + return; + } + + if (rawId !== FX_USD_CAD_SOURCE_ID) { + recordSkip(stats.fx, 'unrequestedId'); + return; + } + + const rawDate = doc[eodSpec.dateField]; + const normalizedDate = + typeof rawDate === 'string' && sampleDateSet.has(rawDate) + ? rawDate + : normalizeBarDate(rawDate); + if (normalizedDate === null) { + recordSkip(stats.fx, 'invalidDate'); + return; + } + if (!sampleDateSet.has(normalizedDate)) { + recordSkip(stats.fx, 'unrequestedDate'); + return; + } + + const rawClose = doc.close; + if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) { + recordSkip(stats.fx, 'invalidClose'); + return; + } + + fxRates.push({ + date: normalizedDate, + usdCad: rawClose, + }); + stats.fx.emitted += 1; + }); + } + + closes.sort(compareSampleCloses); + fxRates.sort(compareFxRates); + + return { + sampleDates, + closes, + fxRates, + stats, + }; +} diff --git a/apps/stock/data-pipeline/test/sample-closes.test.ts b/apps/stock/data-pipeline/test/sample-closes.test.ts new file mode 100644 index 00000000..6cf5c45e --- /dev/null +++ b/apps/stock/data-pipeline/test/sample-closes.test.ts @@ -0,0 +1,753 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { + buildSampleCloseFilter, + crossCheckPrices, + DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE, + EOD_SAMPLE_CLOSES_PROJECTION, + FX_USD_CAD_SOURCE_ID, + MAX_SAMPLE_DATES, + QM_SAMPLE_CLOSES_PROJECTION, + readSampleCloses, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SampleCloseSourceReadStats, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +interface RecordedFindCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +interface FakeReaderOptions { + readOnly?: boolean; + applyFilter?: boolean; + applyProjection?: boolean; + failOnCallIndex?: number; + failAfterDocs?: number; + failMessage?: string; + failCloseOnCallIndex?: number; +} + +interface FakeReaderHandle { + reader: ReadOnlySourceSymbolReader; + calls: RecordedFindCall[]; + closedCount: () => number; +} + +function matchesSimpleFilter( + doc: unknown, + filter: Record | undefined +): boolean { + if (filter === undefined) { + return true; + } + if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) { + return false; + } + const record = doc as Record; + for (const [key, condition] of Object.entries(filter)) { + if ( + condition !== null && + typeof condition === 'object' && + !Array.isArray(condition) && + '$in' in condition + ) { + const allowed = (condition as { $in: unknown[] }).$in; + if (!allowed.includes(record[key])) { + return false; + } + } else if (record[key] !== condition) { + return false; + } + } + return true; +} + +function projectDoc( + doc: unknown, + projection: Record | undefined +): Record { + if (projection === undefined || doc === null || typeof doc !== 'object' || Array.isArray(doc)) { + return doc as Record; + } + const record = doc as Record; + const projected: Record = {}; + for (const [key, include] of Object.entries(projection)) { + if (include === 1 && key in record) { + projected[key] = record[key]; + } + } + return projected; +} + +function createFakeReader( + docsByCollection: Record, + options: FakeReaderOptions = {} +): FakeReaderHandle { + const calls: RecordedFindCall[] = []; + let closed = 0; + + const reader: ReadOnlySourceSymbolReader = { + isReadOnly(): boolean { + return options.readOnly ?? true; + }, + find = Record>( + collectionName: string, + filter?: Record, + findOptions?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + const callIndex = calls.length; + calls.push({ collectionName, filter, options: findOptions }); + + const rawDocs = docsByCollection[collectionName] ?? []; + const shouldFail = options.failOnCallIndex === callIndex; + const failAfter = options.failAfterDocs ?? 0; + const failMessage = options.failMessage ?? 'simulated cursor read failure'; + const shouldFailClose = options.failCloseOnCallIndex === callIndex; + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + let yielded = 0; + for (let i = 0; i < rawDocs.length; i++) { + const rawDoc = rawDocs[i]; + if (options.applyFilter && !matchesSimpleFilter(rawDoc, filter)) { + continue; + } + if (shouldFail && yielded >= failAfter) { + throw new Error(failMessage); + } + const out = options.applyProjection + ? projectDoc(rawDoc, findOptions?.projection) + : rawDoc; + yielded += 1; + yield out as T; + } + if (shouldFail && yielded >= failAfter) { + throw new Error(failMessage); + } + }, + async close(): Promise { + closed += 1; + if (shouldFailClose) { + throw new Error('simulated cursor close failure'); + } + }, + }; + }, + }; + + return { + reader, + calls, + closedCount: () => closed, + }; +} + +function assertStatsReconcile(stats: SampleCloseSourceReadStats): void { + const skipSum = + stats.skipped.missingId + + stats.skipped.unrequestedId + + stats.skipped.invalidDate + + stats.skipped.unrequestedDate + + stats.skipped.invalidClose; + expect(stats.skippedTotal).toBe(skipSum); + expect(stats.docsRead).toBe(stats.emitted + stats.skippedTotal); +} + +function makeSampleDates(count: number): string[] { + const dates: string[] = []; + let year = 2024; + let month = 1; + let day = 1; + while (dates.length < count) { + dates.push( + `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}` + ); + day += 1; + if (day > 28) { + day = 1; + month += 1; + if (month > 12) { + month = 1; + year += 1; + } + } + } + return dates; +} + +describe('Pass 4a sample-closes reader', () => { + test('sample-closes.ts has zero runtime DB, FS, or network imports', () => { + const srcPath = resolve(import.meta.dir, '../src/security-master/sample-closes.ts'); + const source = readFileSync(srcPath, 'utf8'); + const importLines = source + .split('\n') + .filter(line => /^\s*import\b/.test(line) && !/^\s*import\s+type\b/.test(line)); + + for (const line of importLines) { + expect(line).not.toContain('mongodb'); + expect(line).not.toContain('postgres'); + expect(line).not.toContain('node:fs'); + expect(line).not.toContain('node:net'); + expect(line).not.toContain('node:http'); + expect(line).not.toContain('node:https'); + } + expect(source).toContain('BAR_SPAN_COLLECTIONS'); + expect(source).not.toContain("collection: 'eodPrices'"); + expect(source).not.toContain("collection: 'qmPrices'"); + }); + + test('buildSampleCloseFilter emits date-first filters and preserves explicit empty id lists', () => { + const dates = ['2024-06-14', '2024-01-05', '2024-06-14']; + const eodFilter = buildSampleCloseFilter('eod', dates, ['MSFT.US', 'AAPL.US', 'AAPL.US']); + expect(Object.keys(eodFilter)).toEqual(['date', 'eodSearchCode']); + expect(eodFilter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + eodSearchCode: { $in: ['AAPL.US', 'MSFT.US'] }, + }); + + const qmFilter = buildSampleCloseFilter('qm', dates, ['AAPL']); + expect(Object.keys(qmFilter)).toEqual(['date', 'qmSearchCode']); + expect(qmFilter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + qmSearchCode: { $in: ['AAPL'] }, + }); + + const dateOnlyFilter = buildSampleCloseFilter('eod', dates); + expect(Object.keys(dateOnlyFilter)).toEqual(['date']); + + const explicitEmptyFilter = buildSampleCloseFilter('qm', dates, []); + expect(Object.keys(explicitEmptyFilter)).toEqual(['date', 'qmSearchCode']); + expect(explicitEmptyFilter.qmSearchCode).toEqual({ $in: [] }); + }); + + test('passes date-first filter, strict projections, and batchSize to fake reader', async () => { + const fake = createFakeReader( + { + eodPrices: [ + { + eodSearchCode: 'AAPL.US', + date: '2024-01-05', + close: 181.18, + adjustedClose: 180.5, + volume: 999999, + }, + { + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date: '2024-01-05', + close: 1.3365, + }, + ], + qmPrices: [ + { + qmSearchCode: 'AAPL', + date: '2024-01-05', + close: 999.99, + adjustedclose: 180.5, + unadjustedclose: 181.18, + }, + ], + }, + { applyFilter: true, applyProjection: true } + ); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-06-14', '2024-01-05'], + sourceIdsBySource: { + eod: ['AAPL.US'], + qm: ['AAPL'], + }, + batchSize: 2500, + }); + + expect(fake.calls).toHaveLength(3); + + // 1. eodPrices equity call + expect(fake.calls[0]?.collectionName).toBe('eodPrices'); + expect(Object.keys(fake.calls[0]?.filter ?? {})).toEqual(['date', 'eodSearchCode']); + expect(fake.calls[0]?.filter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + eodSearchCode: { $in: ['AAPL.US'] }, + }); + expect(fake.calls[0]?.options).toEqual({ + projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, + batchSize: 2500, + }); + + // 2. qmPrices equity call + expect(fake.calls[1]?.collectionName).toBe('qmPrices'); + expect(Object.keys(fake.calls[1]?.filter ?? {})).toEqual(['date', 'qmSearchCode']); + expect(fake.calls[1]?.filter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + qmSearchCode: { $in: ['AAPL'] }, + }); + expect(fake.calls[1]?.options).toEqual({ + projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, + batchSize: 2500, + }); + expect(fake.calls[1]?.options?.projection).toEqual({ + _id: 0, + qmSearchCode: 1, + date: 1, + unadjustedclose: 1, + }); + + // 3. FX call on eodPrices for CAD.FOREX + expect(fake.calls[2]?.collectionName).toBe('eodPrices'); + expect(Object.keys(fake.calls[2]?.filter ?? {})).toEqual(['date', 'eodSearchCode']); + expect(fake.calls[2]?.filter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + eodSearchCode: { $in: [FX_USD_CAD_SOURCE_ID] }, + }); + expect(fake.calls[2]?.options).toEqual({ + projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, + batchSize: 2500, + }); + + expect(fake.closedCount()).toBe(3); + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-05', close: 181.18 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-05', close: 181.18 }, + ]); + expect(result.fxRates).toEqual([{ date: '2024-01-05', usdCad: 1.3365 }]); + assertStatsReconcile(result.stats.eod); + assertStatsReconcile(result.stats.qm); + assertStatsReconcile(result.stats.fx); + }); + + test('uses raw close for eod, unadjustedclose for qm, and isolates CAD.FOREX exclusively to fxRates', async () => { + const fake = createFakeReader({ + eodPrices: [ + { eodSearchCode: 'NVDA.US', date: '2024-05-01', close: 830.41, adjustedClose: 83.04 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-05-01', close: 1.3742 }, + ], + qmPrices: [ + { + qmSearchCode: 'NVDA', + date: '2024-05-01', + close: 83.04, + adjustedclose: 83.04, + unadjustedclose: 830.41, + }, + ], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-05-01'], + sourceIdsBySource: { + // Explicitly request CAD.FOREX in eod to prove it is stripped from equity reads. + eod: ['NVDA.US', FX_USD_CAD_SOURCE_ID], + qm: ['NVDA'], + }, + }); + + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'NVDA.US', date: '2024-05-01', close: 830.41 }, + { source: 'qm', sourceId: 'NVDA', date: '2024-05-01', close: 830.41 }, + ]); + expect(result.closes.some(row => row.sourceId === FX_USD_CAD_SOURCE_ID)).toBe(false); + expect(result.fxRates).toEqual([{ date: '2024-05-01', usdCad: 1.3742 }]); + + // During the eod equity scan, the unfiltered fake reader also yielded CAD.FOREX, + // which must be skipped as unrequestedId rather than emitted into closes. + expect(result.stats.eod.docsRead).toBe(2); + expect(result.stats.eod.emitted).toBe(1); + expect(result.stats.eod.skipped.unrequestedId).toBe(1); + assertStatsReconcile(result.stats.eod); + assertStatsReconcile(result.stats.qm); + assertStatsReconcile(result.stats.fx); + }); + + test('normalizes Date and string dates to UTC YYYY-MM-DD and reconciles all skip reasons', async () => { + const fake = createFakeReader({ + eodPrices: [ + // Valid: exact string, Date UTC midnight, Date non-midnight UTC, ISO offset crossing into 2024-01-03 UTC + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }, + { eodSearchCode: 'AAPL.US', date: new Date('2024-01-03T00:00:00Z'), close: 184.25 }, + { eodSearchCode: 'AAPL.US', date: new Date('2024-01-04T21:30:00Z'), close: 181.91 }, + { eodSearchCode: 'MSFT.US', date: '2024-01-02T22:00:00-05:00', close: 370.6 }, + // missingId (null doc, non-string id, blank id) + null, + { eodSearchCode: 123, date: '2024-01-02', close: 10 }, + { eodSearchCode: ' ', date: '2024-01-02', close: 10 }, + // unrequestedId + { eodSearchCode: 'OTHER.US', date: '2024-01-02', close: 50 }, + // invalidDate (bad string, invalid Date, timezone-less timestamp) + { eodSearchCode: 'AAPL.US', date: '2023-02-29', close: 100 }, + { eodSearchCode: 'AAPL.US', date: new Date('invalid'), close: 100 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02T16:00:00', close: 100 }, + // unrequestedDate (valid date outside sampleDates) + { eodSearchCode: 'AAPL.US', date: '2024-01-05', close: 181.18 }, + { eodSearchCode: 'AAPL.US', date: new Date('2024-01-06T00:00:00Z'), close: 181.18 }, + // invalidClose (NaN, Infinity, -Infinity, 0, negative, string) + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.NaN }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.POSITIVE_INFINITY }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.NEGATIVE_INFINITY }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: -12.5 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: '185.64' }, + ], + qmPrices: [], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-01-02', '2024-01-03', '2024-01-04'], + sourceIdsBySource: { eod: ['AAPL.US', 'MSFT.US'], qm: [] }, + includeFx: false, + }); + + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 185.64 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-03', close: 184.25 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-04', close: 181.91 }, + { source: 'eod', sourceId: 'MSFT.US', date: '2024-01-03', close: 370.6 }, + ]); + + expect(result.stats.eod.docsRead).toBe(19); + expect(result.stats.eod.emitted).toBe(4); + expect(result.stats.eod.skipped).toEqual({ + missingId: 3, + unrequestedId: 1, + invalidDate: 3, + unrequestedDate: 2, + invalidClose: 6, + }); + assertStatsReconcile(result.stats.eod); + expect(result.stats.qm.findsRun).toBe(0); + expect(result.stats.fx.findsRun).toBe(0); + }); + + test('does not trim source IDs (T-49): surrounded-space IDs match only identical requested IDs', async () => { + const fake = createFakeReader({ + eodPrices: [ + { eodSearchCode: ' AAPL.US ', date: '2024-01-02', close: 185.64 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }, + ], + qmPrices: [ + { qmSearchCode: ' AAPL ', date: '2024-01-02', unadjustedclose: 185.64 }, + { qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.64 }, + ], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { + eod: [' AAPL.US '], + qm: ['AAPL'], + }, + includeFx: false, + }); + + expect(result.closes).toEqual([ + { source: 'eod', sourceId: ' AAPL.US ', date: '2024-01-02', close: 185.64 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-02', close: 185.64 }, + ]); + expect(result.stats.eod.skipped.unrequestedId).toBe(1); + expect(result.stats.qm.skipped.unrequestedId).toBe(1); + assertStatsReconcile(result.stats.eod); + assertStatsReconcile(result.stats.qm); + }); + + test('produces deterministic deep-equal output regardless of cursor or input order', async () => { + const eodDocs = [ + { eodSearchCode: 'MSFT.US', date: '2024-01-03', close: 371.0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 186.0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-03', close: 184.0 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-03', close: 1.335 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.331 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.329 }, + ]; + const qmDocs = [ + { qmSearchCode: 'MSFT', date: '2024-01-02', unadjustedclose: 370.0 }, + { qmSearchCode: 'AAPL', date: '2024-01-03', unadjustedclose: 184.0 }, + { qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.0 }, + ]; + + const fakeA = createFakeReader({ eodPrices: eodDocs, qmPrices: qmDocs }); + const fakeB = createFakeReader({ + eodPrices: [...eodDocs].reverse(), + qmPrices: [...qmDocs].reverse(), + }); + + const resultA = await readSampleCloses(fakeA.reader, { + sampleDates: ['2024-01-03', '2024-01-02'], + sourceIdsBySource: { eod: ['MSFT.US', 'AAPL.US'], qm: ['MSFT', 'AAPL'] }, + }); + const resultB = await readSampleCloses(fakeB.reader, { + sampleDates: ['2024-01-02', '2024-01-03'], + sourceIdsBySource: { eod: ['AAPL.US', 'MSFT.US'], qm: ['AAPL', 'MSFT'] }, + }); + + expect(resultA).toEqual(resultB); + expect(resultA.closes).toEqual([ + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 185.0 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 186.0 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-03', close: 184.0 }, + { source: 'eod', sourceId: 'MSFT.US', date: '2024-01-03', close: 371.0 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-02', close: 185.0 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-03', close: 184.0 }, + { source: 'qm', sourceId: 'MSFT', date: '2024-01-02', close: 370.0 }, + ]); + expect(resultA.fxRates).toEqual([ + { date: '2024-01-02', usdCad: 1.329 }, + { date: '2024-01-02', usdCad: 1.331 }, + { date: '2024-01-03', usdCad: 1.335 }, + ]); + }); + + test('chunks large id sets by idChunkSize with date-first filters and skips empty sources', async () => { + const eodIds = ['A.US', 'B.US', 'C.US', 'D.US', 'E.US']; + const fake = createFakeReader( + { + eodPrices: eodIds.map((id, i) => ({ + eodSearchCode: id, + date: '2024-02-01', + close: 10 + i, + })), + qmPrices: [], + }, + { applyFilter: true } + ); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-02-01'], + sourceIdsBySource: { eod: eodIds, qm: [] }, + idChunkSize: 2, + includeFx: false, + }); + + expect(DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE).toBe(10_000); + expect(fake.calls).toHaveLength(3); + expect(result.stats.eod.findsRun).toBe(3); + expect(result.stats.qm.findsRun).toBe(0); + expect(result.stats.fx.findsRun).toBe(0); + expect(result.closes).toHaveLength(5); + + for (const call of fake.calls) { + expect(call.collectionName).toBe('eodPrices'); + expect(Object.keys(call.filter ?? {})).toEqual(['date', 'eodSearchCode']); + expect(call.filter?.date).toEqual({ $in: ['2024-02-01'] }); + } + expect(fake.calls[0]?.filter?.eodSearchCode).toEqual({ $in: ['A.US', 'B.US'] }); + expect(fake.calls[1]?.filter?.eodSearchCode).toEqual({ $in: ['C.US', 'D.US'] }); + expect(fake.calls[2]?.filter?.eodSearchCode).toEqual({ $in: ['E.US'] }); + }); + + test('rejects non-read-only reader and invalid options before issuing any find', async () => { + const writableFake = createFakeReader({}, { readOnly: false }); + await expect( + readSampleCloses(writableFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + }) + ).rejects.toThrow(/isReadOnly/); + expect(writableFake.calls).toHaveLength(0); + + const validFake = createFakeReader({}); + const badDateInputs: string[][] = [ + [], + ['2024-1-2'], + ['2023-02-29'], + [' 2024-01-02 '], + ['2024-01-02T00:00:00Z'], + makeSampleDates(MAX_SAMPLE_DATES + 1), + ]; + + for (const badDates of badDateInputs) { + await expect( + readSampleCloses(validFake.reader, { + sampleDates: badDates, + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + }) + ).rejects.toThrow(RangeError); + } + + await expect( + readSampleCloses(validFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + batchSize: 0, + }) + ).rejects.toThrow(RangeError); + + await expect( + readSampleCloses(validFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + idChunkSize: -5, + }) + ).rejects.toThrow(RangeError); + + expect(validFake.calls).toHaveLength(0); + }); + + test('rejects buffered array results with TypeError and closes cursors on errors while preserving collection name', async () => { + const bufferedReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => [] as unknown as AsyncIterable>, + }; + + await expect( + readSampleCloses(bufferedReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + }) + ).rejects.toThrow(TypeError); + + // Cursor error on qmPrices (call index 1) with close() also failing: primary error + collection name preserved. + const failingFake = createFakeReader( + { + eodPrices: [{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }], + qmPrices: [ + { qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.64 }, + { qmSearchCode: 'MSFT', date: '2024-01-02', unadjustedclose: 370.0 }, + ], + }, + { + failOnCallIndex: 1, + failAfterDocs: 1, + failMessage: 'socket reset', + failCloseOnCallIndex: 1, + } + ); + + await expect( + readSampleCloses(failingFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: ['AAPL', 'MSFT'] }, + }) + ).rejects.toThrow(/qmPrices.*socket reset/); + + // Both call 0 (eodPrices) and call 1 (qmPrices) must have had close() invoked. + expect(failingFake.closedCount()).toBe(2); + }); + + test('integrates end to end with crossCheckPrices for USD/USD and CAD/USD pairs (confirmed and conflict)', async () => { + const dates = [ + '2024-01-02', + '2024-02-01', + '2024-03-01', + '2024-04-01', + '2024-05-01', + '2024-06-03', + ]; + const usdPrices = [100, 108, 102, 115, 121, 118]; + const fxRatesByIdx = [1.33, 1.35, 1.36, 1.37, 1.38, 1.36]; + + const eodDocs: Record[] = []; + const qmDocs: Record[] = []; + + for (let i = 0; i < dates.length; i++) { + const date = dates[i]!; + const p = usdPrices[i]!; + const fx = fxRatesByIdx[i]!; + + // FX series + eodDocs.push({ eodSearchCode: FX_USD_CAD_SOURCE_ID, date, close: fx }); + + // USD/USD consistent pair (AAPL.US vs AAPL) + eodDocs.push({ eodSearchCode: 'AAPL.US', date, close: p }); + qmDocs.push({ qmSearchCode: 'AAPL', date, unadjustedclose: p * 1.002 }); + + // CAD/USD consistent cross-listed pair (SHOP.TO in CAD vs SHOP in USD) + eodDocs.push({ eodSearchCode: 'SHOP.TO', date, close: p * fx }); + qmDocs.push({ qmSearchCode: 'SHOP', date, unadjustedclose: p }); + + // Mismatched USD/USD pair (ratio off by 15%) + eodDocs.push({ eodSearchCode: 'BAD.US', date, close: p * 1.15 }); + qmDocs.push({ qmSearchCode: 'BAD', date, unadjustedclose: p }); + + // Low-correlation USD/USD pair (same scale near 1.0 ratio, opposite daily moves) + const inverted = usdPrices[dates.length - 1 - i]!; + eodDocs.push({ eodSearchCode: 'UNCORR.US', date, close: p }); + qmDocs.push({ qmSearchCode: 'UNCORR', date, unadjustedclose: inverted }); + } + + const fake = createFakeReader({ eodPrices: eodDocs, qmPrices: qmDocs }, { applyFilter: true }); + const sample = await readSampleCloses(fake.reader, { + sampleDates: dates, + sourceIdsBySource: { + eod: ['AAPL.US', 'SHOP.TO', 'BAD.US', 'UNCORR.US'], + qm: ['AAPL', 'SHOP', 'BAD', 'UNCORR'], + }, + }); + + const check = crossCheckPrices({ + pairs: [ + { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'AAPL', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD' }, + right: { source: 'qm', sourceId: 'SHOP', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'BAD.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'BAD', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'UNCORR.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'UNCORR', currency: 'USD' }, + }, + ], + closes: sample.closes, + usdCadByDate: sample.fxRates, + }); + + const byLeftId = new Map(check.results.map(r => [r.left.sourceId, r])); + expect(byLeftId.get('AAPL.US')?.verdict).toBe('confirmed'); + expect(byLeftId.get('SHOP.TO')?.verdict).toBe('confirmed'); + expect(byLeftId.get('BAD.US')?.verdict).toBe('ratio_mismatch'); + expect(byLeftId.get('UNCORR.US')?.verdict).toBe('low_correlation'); + expect(check.conflicts).toHaveLength(2); + expect(check.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([ + ['BAD.US', 'price_ratio_mismatch'], + ['UNCORR.US', 'price_low_correlation'], + ]); + }); + + test('reconciles skip counts on FX scan for malformed, unrequested, and invalid FX docs', async () => { + const fake = createFakeReader({ + eodPrices: [ + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.335 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: new Date('2024-01-03T12:00:00Z'), close: 1.34 }, + null, + { eodSearchCode: '', date: '2024-01-02', close: 1.33 }, + { eodSearchCode: 'EUR.FOREX', date: '2024-01-02', close: 1.09 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: 'bad-date', close: 1.33 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-09', close: 1.33 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: -1.33 }, + ], + qmPrices: [], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-01-02', '2024-01-03'], + sourceIdsBySource: { eod: [], qm: [] }, + }); + + expect(result.fxRates).toEqual([ + { date: '2024-01-02', usdCad: 1.335 }, + { date: '2024-01-03', usdCad: 1.34 }, + ]); + expect(result.stats.eod.findsRun).toBe(0); + expect(result.stats.qm.findsRun).toBe(0); + expect(result.stats.fx.findsRun).toBe(1); + expect(result.stats.fx.docsRead).toBe(8); + expect(result.stats.fx.emitted).toBe(2); + expect(result.stats.fx.skipped).toEqual({ + missingId: 2, + unrequestedId: 1, + invalidDate: 1, + unrequestedDate: 1, + invalidClose: 1, + }); + assertStatsReconcile(result.stats.fx); + }); +});