From cf511f05c066f8b8b5c5a41456c6eeb8315aff26 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 20:40:47 -0500 Subject: [PATCH 1/5] =?UTF-8?q?T-104:=20M1.1=20Pass=204a=20=E2=80=94=20dat?= =?UTF-8?q?a-pipeline:=20read-only=2025-date=20sample-close=20+=20USD/CAD?= =?UTF-8?q?=20reader=20(`{=20date:=20{=20$in:=20sampleDates=20}=20}`=20ove?= =?UTF-8?q?r=20`eodPrices`=20/=20`qmPrices`=20/=20`CAD.FOREX`)=20with=20te?= =?UTF-8?q?sts=20and=20local=20benchmark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 15 + .../benchmarks/sample-closes-benchmark.ts | 187 +++++ .../src/security-master/index.ts | 18 + .../src/security-master/sample-closes.ts | 506 ++++++++++++ .../data-pipeline/test/sample-closes.test.ts | 753 ++++++++++++++++++ 5 files changed, 1479 insertions(+) create mode 100644 apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts create mode 100644 apps/stock/data-pipeline/src/security-master/sample-closes.ts create mode 100644 apps/stock/data-pipeline/test/sample-closes.test.ts 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); + }); +}); From 73b34f4c49b33af214d051befd58e47de76f1222 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 20:46:41 -0500 Subject: [PATCH 2/5] =?UTF-8?q?T-104:=20M1.1=20Pass=204a=20=E2=80=94=20dat?= =?UTF-8?q?a-pipeline:=20read-only=2025-date=20sample-close=20+=20USD/CAD?= =?UTF-8?q?=20reader=20(`{=20date:=20{=20$in:=20sampleDates=20}=20}`=20ove?= =?UTF-8?q?r=20`eodPrices`=20/=20`qmPrices`=20/=20`CAD.FOREX`)=20with=20te?= =?UTF-8?q?sts=20and=20local=20benchmark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 2 +- .../src/security-master/sample-closes.ts | 29 +++-- .../data-pipeline/test/sample-closes.test.ts | 107 ++++++++++++++++++ 3 files changed, 129 insertions(+), 9 deletions(-) diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index a1998de5..6664a2b0 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -67,7 +67,7 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto ## 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. +- **Date storage finding & `$in` type:** `eodPrices` (`apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts`) explicitly enforces and persists `date` as an exact `YYYY-MM-DD` string. `qmPrices` (`apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts`) copies the provider's `price.date` field verbatim and derives a BSON `Date` separately in `dateTime`, so exact `YYYY-MM-DD` formatting on `qmPrices.date` is an assumption based on the QuoteMedia payload until verified against live QA MongoDB or a captured provider fixture. Keeping the approved string query, `buildSampleCloseFilter` emits date-first `{ date: { $in: string[] } }` filters (sorted `YYYY-MM-DD` strings, aligning with `BAR_SPAN_COLLECTIONS` in `src/normalization/bar-spans.ts` and `design/DATA-CONTRACTS.md`) 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`; because any format or BSON-type mismatch on `date` would exclude rows before decode, row counts should be verified on the first live read-only 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: diff --git a/apps/stock/data-pipeline/src/security-master/sample-closes.ts b/apps/stock/data-pipeline/src/security-master/sample-closes.ts index bd44423b..98270938 100644 --- a/apps/stock/data-pipeline/src/security-master/sample-closes.ts +++ b/apps/stock/data-pipeline/src/security-master/sample-closes.ts @@ -226,9 +226,11 @@ async function streamSampleCloseFind( onDoc: (doc: unknown) => void ): Promise { assertReadOnlyReader(reader); - let cursor: ReadOnlySourceSymbolCursor> | null = null; + let closableHandle: Pick>, 'close'> | null = + null; let primaryError: unknown = undefined; let hasPrimaryError = false; + let isInvalidCursorError = false; try { const rawCursor = await reader.find>( @@ -236,22 +238,31 @@ async function streamSampleCloseFind( filter, findOptions ); + if ( + rawCursor !== null && + (typeof rawCursor === 'object' || typeof rawCursor === 'function') + ) { + closableHandle = rawCursor as Pick< + ReadOnlySourceSymbolCursor>, + 'close' + >; + } if (Array.isArray(rawCursor) || !isAsyncIterable>(rawCursor)) { + isInvalidCursorError = true; 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) { + for await (const doc of rawCursor) { onDoc(doc); } } catch (error) { primaryError = error; hasPrimaryError = true; } finally { - if (cursor !== null && typeof cursor.close === 'function') { + if (closableHandle !== null && typeof closableHandle.close === 'function') { try { - await cursor.close(); + await closableHandle.close(); } catch (closeError) { if (!hasPrimaryError) { primaryError = closeError; @@ -262,7 +273,7 @@ async function streamSampleCloseFind( } if (hasPrimaryError) { - if (primaryError instanceof TypeError) { + if (isInvalidCursorError) { throw primaryError; } throw wrapCollectionReadError(collectionName, primaryError); @@ -286,8 +297,10 @@ function compareFxRates(a: FxRateByDateRecord, b: FxRateByDateRecord): number { * 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. + * `eodPrices` (`price-storage.ts`) enforces `YYYY-MM-DD` strings for `date`, while + * `qmPrices` (`prices.action.ts`) copies the provider's `date` field verbatim (assumed + * `YYYY-MM-DD`, with BSON `Date` stored separately in `dateTime`), so `$in` emits sorted + * `YYYY-MM-DD` strings. */ export function buildSampleCloseFilter( source: SampleCloseSource, diff --git a/apps/stock/data-pipeline/test/sample-closes.test.ts b/apps/stock/data-pipeline/test/sample-closes.test.ts index 6cf5c45e..2b5950f4 100644 --- a/apps/stock/data-pipeline/test/sample-closes.test.ts +++ b/apps/stock/data-pipeline/test/sample-closes.test.ts @@ -627,6 +627,113 @@ describe('Pass 4a sample-closes reader', () => { expect(failingFake.closedCount()).toBe(2); }); + test('wraps TypeError thrown during iteration or close with collection name and original cause while closing cursor', async () => { + const iterationCause = new TypeError('cannot decode malformed BSON field'); + let iterationCloseCalls = 0; + + const iterationTypeErrorReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find = Record>( + collectionName: string + ): ReadOnlySourceSymbolCursor { + if (collectionName === 'qmPrices') { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + yield { + qmSearchCode: 'AAPL', + date: '2024-01-02', + unadjustedclose: 185.64, + } as unknown as T; + throw iterationCause; + }, + async close(): Promise { + iterationCloseCalls += 1; + }, + }; + } + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty + }, + async close(): Promise { + // noop + }, + }; + }, + }; + + let caughtIterationError: unknown; + try { + await readSampleCloses(iterationTypeErrorReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: ['AAPL'] }, + includeFx: false, + }); + } catch (error) { + caughtIterationError = error; + } + + expect(caughtIterationError).toBeInstanceOf(Error); + expect((caughtIterationError as Error).message).toContain('qmPrices'); + expect((caughtIterationError as Error).message).toContain('cannot decode malformed BSON field'); + expect((caughtIterationError as Error).cause).toBe(iterationCause); + expect(iterationCloseCalls).toBe(1); + + const closeCause = new TypeError('cursor close internal TypeError'); + const closeTypeErrorReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find = Record>(): ReadOnlySourceSymbolCursor { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty + }, + async close(): Promise { + throw closeCause; + }, + }; + }, + }; + + let caughtCloseError: unknown; + try { + await readSampleCloses(closeTypeErrorReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + includeFx: false, + }); + } catch (error) { + caughtCloseError = error; + } + + expect(caughtCloseError).toBeInstanceOf(Error); + expect((caughtCloseError as Error).message).toContain('eodPrices'); + expect((caughtCloseError as Error).message).toContain('cursor close internal TypeError'); + expect((caughtCloseError as Error).cause).toBe(closeCause); + }); + + test('rejects an invalid closable handle with TypeError and still releases it via close()', async () => { + let invalidHandleClosed = 0; + const invalidClosableReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => + ({ + async close(): Promise { + invalidHandleClosed += 1; + }, + }) as unknown as AsyncIterable>, + }; + + await expect( + readSampleCloses(invalidClosableReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + includeFx: false, + }) + ).rejects.toThrow(TypeError); + + expect(invalidHandleClosed).toBe(1); + }); + test('integrates end to end with crossCheckPrices for USD/USD and CAD/USD pairs (confirmed and conflict)', async () => { const dates = [ '2024-01-02', From 6e8bf434f96d6eec4f6a11c262c8915af012893d Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 20:51:55 -0500 Subject: [PATCH 3/5] T-104: tests --- .../test/sample-closes-edge.test.ts | 330 ++++++++++++++++++ 1 file changed, 330 insertions(+) create mode 100644 apps/stock/data-pipeline/test/sample-closes-edge.test.ts diff --git a/apps/stock/data-pipeline/test/sample-closes-edge.test.ts b/apps/stock/data-pipeline/test/sample-closes-edge.test.ts new file mode 100644 index 00000000..9de5c1e5 --- /dev/null +++ b/apps/stock/data-pipeline/test/sample-closes-edge.test.ts @@ -0,0 +1,330 @@ +import { describe, expect, test } from 'bun:test'; +import { + buildSampleCloseFilter, + createReadOnlyMongoSourceSymbolReader, + EOD_SAMPLE_CLOSES_PROJECTION, + FX_USD_CAD_SOURCE_ID, + MAX_SAMPLE_DATES, + QM_SAMPLE_CLOSES_PROJECTION, + readSampleCloses, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SampleCloseSource, + type SampleCloseSourceReadStats, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +// QA edge cases for the Pass 4a sample-close reader that complement sample-closes.test.ts. +// All readers are in-memory; no MongoDB / PostgreSQL / network. + +interface RecordedCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +function unfilteredReader(docsByCollection: Record): { + reader: ReadOnlySourceSymbolReader; + calls: RecordedCall[]; +} { + const calls: RecordedCall[] = []; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + calls.push({ collectionName, filter, options }); + const docs = docsByCollection[collectionName] ?? []; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (const doc of docs) { + yield doc as T; + } + }, + }; + }, + }; + return { reader, calls }; +} + +function expectReconciled(stats: SampleCloseSourceReadStats): void { + const s = stats.skipped; + expect(stats.skippedTotal).toBe( + s.missingId + s.unrequestedId + s.invalidDate + s.unrequestedDate + s.invalidClose + ); + expect(stats.docsRead).toBe(stats.emitted + stats.skippedTotal); +} + +function makeDistinctDates(count: number): string[] { + const out: string[] = []; + const start = Date.UTC(2020, 0, 1); + for (let i = 0; i < count; i++) { + out.push(new Date(start + i * 86_400_000).toISOString().slice(0, 10)); + } + return out; +} + +describe('Pass 4a sample-closes reader — QA edge cases', () => { + test('streams end to end through createReadOnlyMongoSourceSymbolReader, forwarding filter/projection/batchSize and closing driver cursors', async () => { + const collectionCalls: Array<{ + name: string; + filter: Record; + options: SourceSymbolFindOptions | undefined; + }> = []; + let driverCursorsClosed = 0; + const store: Record[]> = { + eodPrices: [ + { eodSearchCode: 'RY.TO', date: '2024-03-01', close: 130.5 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-03-01', close: 1.355 }, + ], + qmPrices: [{ qmSearchCode: 'RY', date: '2024-03-01', unadjustedclose: 96.3 }], + }; + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find(filter: Record, options?: SourceSymbolFindOptions) { + collectionCalls.push({ name, filter, options }); + const idField = name === 'eodPrices' ? 'eodSearchCode' : 'qmSearchCode'; + const ids = (filter[idField] as { $in: string[] }).$in; + const dates = (filter.date as { $in: string[] }).$in; + const docs = (store[name] ?? []).filter( + d => ids.includes(d[idField] as string) && dates.includes(d.date as string) + ); + return { + async *[Symbol.asyncIterator]() { + yield* docs; + }, + async close() { + driverCursorsClosed += 1; + }, + }; + }, + }; + }, + }; + + const result = await readSampleCloses(createReadOnlyMongoSourceSymbolReader(client), { + sampleDates: ['2024-03-01'], + sourceIdsBySource: { eod: ['RY.TO'], qm: ['RY'] }, + batchSize: 1000, + }); + + expect(collectionCalls.map(c => c.name)).toEqual(['eodPrices', 'qmPrices', 'eodPrices']); + expect(collectionCalls[0]?.options).toEqual({ + projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, + batchSize: 1000, + }); + expect(collectionCalls[1]?.options).toEqual({ + projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, + batchSize: 1000, + }); + for (const call of collectionCalls) { + expect(Object.keys(call.filter)[0]).toBe('date'); + } + expect(driverCursorsClosed).toBe(3); + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'RY.TO', date: '2024-03-01', close: 130.5 }, + { source: 'qm', sourceId: 'RY', date: '2024-03-01', close: 96.3 }, + ]); + expect(result.fxRates).toEqual([{ date: '2024-03-01', usdCad: 1.355 }]); + }); + + test('accepts exactly MAX_SAMPLE_DATES dates and applies the cap after de-duplication', async () => { + const exact = makeDistinctDates(MAX_SAMPLE_DATES); + const { reader } = unfilteredReader({}); + const atCap = await readSampleCloses(reader, { + sampleDates: exact, + sourceIdsBySource: { eod: ['A.US'], qm: [] }, + includeFx: false, + }); + expect(atCap.sampleDates).toHaveLength(MAX_SAMPLE_DATES); + + const withDuplicates = [...exact, ...exact.slice(0, 10)]; + expect(withDuplicates.length).toBeGreaterThan(MAX_SAMPLE_DATES); + const deduped = await readSampleCloses(reader, { + sampleDates: withDuplicates, + sourceIdsBySource: { eod: ['A.US'], qm: [] }, + includeFx: false, + }); + expect(deduped.sampleDates).toEqual(exact); + }); + + test('chunked finds never emit a row twice and count other-chunk ids as unrequested', async () => { + const ids = ['A.US', 'B.US', 'C.US', 'D.US']; + const { reader, calls } = unfilteredReader({ + eodPrices: ids.map((id, i) => ({ eodSearchCode: id, date: '2024-02-01', close: 10 + i })), + }); + + const result = await readSampleCloses(reader, { + sampleDates: ['2024-02-01'], + sourceIdsBySource: { eod: ids, qm: [] }, + idChunkSize: 2, + includeFx: false, + }); + + expect(calls).toHaveLength(2); + expect(result.stats.eod.findsRun).toBe(2); + expect(result.closes.map(c => c.sourceId)).toEqual(ids); + expect(result.stats.eod.docsRead).toBe(8); + expect(result.stats.eod.emitted).toBe(4); + expect(result.stats.eod.skipped.unrequestedId).toBe(4); + expectReconciled(result.stats.eod); + }); + + test('wraps synchronous throws and rejected find() promises with the collection name and cause', async () => { + const syncCause = new Error('auth failed'); + const syncReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => { + throw syncCause; + }, + }; + const syncError = await readSampleCloses(syncReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: ['AAPL'] }, + includeFx: false, + }).catch((e: unknown) => e); + expect(syncError).toBeInstanceOf(Error); + expect((syncError as Error).message).toContain('qmPrices'); + expect((syncError as Error).message).toContain('auth failed'); + expect((syncError as Error).cause).toBe(syncCause); + + const asyncCause = new Error('server selection timed out'); + const asyncReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => Promise.reject(asyncCause), + }; + const asyncError = await readSampleCloses(asyncReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + includeFx: false, + }).catch((e: unknown) => e); + expect((asyncError as Error).message).toContain('eodPrices'); + expect((asyncError as Error).cause).toBe(asyncCause); + }); + + test('requested ids with surrounding spaces do not match trimmed stored ids, and blank-only id lists issue no finds', async () => { + const { reader, calls } = unfilteredReader({ + eodPrices: [{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185 }], + qmPrices: [{ qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185 }], + }); + + const result = await readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US '], qm: [' ', ''] }, + includeFx: false, + }); + + expect(calls).toHaveLength(1); + expect(calls[0]?.filter?.eodSearchCode).toEqual({ $in: ['AAPL.US '] }); + expect(result.closes).toEqual([]); + expect(result.stats.eod.skipped.unrequestedId).toBe(1); + expect(result.stats.qm.findsRun).toBe(0); + }); + + test('stops before the next find when the reader stops reporting read-only mid-run', async () => { + let readOnly = true; + const collections: string[] = []; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => readOnly, + find = Record>( + collectionName: string + ): ReadOnlySourceSymbolCursor { + collections.push(collectionName); + readOnly = false; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty + }, + }; + }, + }; + + await expect( + readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: ['AAPL'] }, + }) + ).rejects.toThrow(/isReadOnly/); + expect(collections).toEqual(['eodPrices']); + }); + + test('qm rows never fall back to close/adjustedclose when unadjustedclose is missing', async () => { + const { reader } = unfilteredReader({ + qmPrices: [ + { qmSearchCode: 'AAPL', date: '2024-01-02', close: 185, adjustedclose: 184 }, + { qmSearchCode: 'AAPL', date: '2024-01-03', unadjustedclose: null, close: 186 }, + ], + }); + + const result = await readSampleCloses(reader, { + sampleDates: ['2024-01-02', '2024-01-03'], + sourceIdsBySource: { eod: [], qm: ['AAPL'] }, + includeFx: false, + }); + + expect(result.closes).toEqual([]); + expect(result.stats.qm.skipped.invalidClose).toBe(2); + expectReconciled(result.stats.qm); + }); + + test('FX rates keep CAD-per-USD orientation and includeFx=false issues no FX find', async () => { + const docs = { eodPrices: [{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.35 }] }; + + const withFx = await readSampleCloses(unfilteredReader(docs).reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: [] }, + }); + expect(withFx.fxRates).toEqual([{ date: '2024-01-02', usdCad: 1.35 }]); + + const noFx = unfilteredReader(docs); + const withoutFx = await readSampleCloses(noFx.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: [] }, + includeFx: false, + }); + expect(noFx.calls).toHaveLength(0); + expect(withoutFx.fxRates).toEqual([]); + expect(withoutFx.stats.fx.findsRun).toBe(0); + }); + + test('does not mutate caller inputs', async () => { + const sampleDates = ['2024-01-03', '2024-01-02', '2024-01-03']; + const eod = ['B.US', 'A.US', FX_USD_CAD_SOURCE_ID]; + const qm = ['B', 'A']; + const { reader } = unfilteredReader({}); + + buildSampleCloseFilter('eod', sampleDates, eod); + await readSampleCloses(reader, { sampleDates, sourceIdsBySource: { eod, qm } }); + + expect(sampleDates).toEqual(['2024-01-03', '2024-01-02', '2024-01-03']); + expect(eod).toEqual(['B.US', 'A.US', FX_USD_CAD_SOURCE_ID]); + expect(qm).toEqual(['B', 'A']); + }); + + test('rejects unsupported sources and non-string requested ids before any find', async () => { + expect(() => + buildSampleCloseFilter('ib' as unknown as SampleCloseSource, ['2024-01-02']) + ).toThrow(RangeError); + + const { reader, calls } = unfilteredReader({}); + await expect( + readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['A.US'], qm: [42 as unknown as string] }, + }) + ).rejects.toThrow(TypeError); + await expect( + readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['A.US'], qm: [] }, + batchSize: 1.5, + }) + ).rejects.toThrow(RangeError); + expect(calls).toHaveLength(0); + }); +}); From 2c9d26b1ca6ba1b4ff2b27510a6a43c353602d94 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 21:15:51 -0500 Subject: [PATCH 4/5] =?UTF-8?q?T-105:=20M1.1=20Pass=204b=20=E2=80=94=20dat?= =?UTF-8?q?a-pipeline:=20wire=20the=2025-date=20sample-close=20reader=20in?= =?UTF-8?q?to=20`run-security-master.ts`=20so=20the=20match=20report=20car?= =?UTF-8?q?ries=20real=20price=20cross-check=20verdicts=20(read-only=20Mon?= =?UTF-8?q?go,=20tests=20+=20local=20benchmark)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../run-security-master-pass4-benchmark.ts | 358 ++++++++ .../src/security-master/index.ts | 4 + .../security-master/run-security-master.ts | 387 +++++++- test/unit/security-master-run-cli.test.ts | 824 +++++++++++++++++- 4 files changed, 1554 insertions(+), 19 deletions(-) create mode 100644 apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts diff --git a/apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts b/apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts new file mode 100644 index 00000000..d3513ba7 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts @@ -0,0 +1,358 @@ +/** + * Reproducible headless benchmark for Pass 4b `runSecurityMaster` end-to-end wiring. + * Streams 20,000 EOD<->QM candidate pairs x 25 sample dates (1,000,025 sample-close/FX docs) + * through in-memory async-generator fake readers with zero database or disk writes. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts + */ + +import type { + BarSpanAggregateReader, + GroupedBarSpanRow, +} from '../src/normalization/bar-spans'; +import { + FX_USD_CAD_SOURCE_ID, + runSecurityMaster, + type ReadOnlyMongoCollectionClient, +} from '../src/security-master'; + +const PAIR_COUNT = 20_000; +const SAMPLE_DATE_COUNT = 25; +const MISMATCH_EVERY = 200; // 100 ratio_mismatch pairs, 19,900 confirmed pairs +const AS_OF_DATE = '2026-01-15'; +const FIRST_BAR_DATE = '2020-01-02'; +const LAST_BAR_DATE = '2026-01-14'; + +function computeIsinCheckDigit(isinBody11: string): string { + let digits = ''; + for (let i = 0; i < isinBody11.length; i++) { + const code = isinBody11.charCodeAt(i); + if (code >= 65 && code <= 90) { + digits += String(code - 55); + } else { + digits += isinBody11[i] ?? ''; + } + } + let sum = 0; + let doubleDigit = true; + for (let i = digits.length - 1; i >= 0; i--) { + let val = digits.charCodeAt(i) - 48; + if (doubleDigit) { + val *= 2; + if (val > 9) { + val -= 9; + } + } + sum += val; + doubleDigit = !doubleDigit; + } + return String((10 - (sum % 10)) % 10); +} + +function makeSyntheticIsin(index: number): string { + const body = `US${String(100_000_000 + index).padStart(9, '0')}`; + return `${body}${computeIsinCheckDigit(body)}`; +} + +function makePureLetterTicker(index: number): string { + let n = index; + const c3 = String.fromCharCode(65 + (n % 26)); + n = Math.floor(n / 26); + const c2 = String.fromCharCode(65 + (n % 26)); + n = Math.floor(n / 26); + const c1 = String.fromCharCode(65 + (n % 26)); + n = Math.floor(n / 26); + const c0 = String.fromCharCode(65 + (n % 26)); + return `${c0}${c1}${c2}${c3}`; +} + +function deterministicClose(pairIndex: number, dateIndex: number): number { + // Deterministic non-constant trajectory per pair so log-return variance is strictly positive. + const base = 20 + (pairIndex % 180); + const wave = ((pairIndex * 31 + dateIndex * 17) % 37) * 0.45; + const trend = dateIndex * (0.35 + (pairIndex % 7) * 0.05); + return Number((base + wave + trend).toFixed(4)); +} + +function createBenchmarkMongo(pairCount: number): { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly barSpanReader: BarSpanAggregateReader; +} { + const tickers = new Array(pairCount); + const isins = new Array(pairCount); + const eodIndexById = new Map(); + const qmIndexById = new Map(); + + for (let i = 0; i < pairCount; i++) { + const ticker = makePureLetterTicker(i); + tickers[i] = ticker; + isins[i] = makeSyntheticIsin(i); + eodIndexById.set(`${ticker}.US`, i); + qmIndexById.set(`${ticker}:US`, i); + } + + const eodExchanges = [ + { Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' }, + ]; + const ibExchanges = [{ exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' }]; + const qmExchanges = [{ exchange: 'NSD', country: 'US', currency: 'USD' }]; + + const mongoCollectionClient: ReadOnlyMongoCollectionClient = { + isReadOnly(): boolean { + return true; + }, + getCollection(collectionName: string) { + return { + find = Record>( + filter: Record = {} + ) { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + if (collectionName === 'eodExchanges') { + for (const doc of eodExchanges) { + yield doc as unknown as T; + } + return; + } + if (collectionName === 'ibExchanges') { + for (const doc of ibExchanges) { + yield doc as unknown as T; + } + return; + } + if (collectionName === 'qmExchanges') { + for (const doc of qmExchanges) { + yield doc as unknown as T; + } + return; + } + if ( + collectionName === 'ceoExchanges' || + collectionName === 'ibSymbols' || + collectionName === 'ceoSymbols' || + collectionName === 'eodSymbolChange' + ) { + return; + } + if (collectionName === 'eodSymbols') { + for (let i = 0; i < pairCount; i++) { + const ticker = tickers[i]; + const isin = isins[i]; + if (ticker === undefined || isin === undefined) { + continue; + } + yield { + eodSearchCode: `${ticker}.US`, + Code: ticker, + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: isin, + Name: `Bench Corp ${ticker}`, + Type: 'Common Stock', + delisted: false, + } as unknown as T; + } + return; + } + if (collectionName === 'qmSymbols') { + for (let i = 0; i < pairCount; i++) { + const ticker = tickers[i]; + if (ticker === undefined) { + continue; + } + yield { + qmSearchCode: `${ticker}:US`, + symbol: ticker, + exchange: 'NSD', + countryCode: 'US', + currency: 'USD', + name: `Bench Corp ${ticker}`, + active: true, + } as unknown as T; + } + return; + } + + const dates = ((filter.date as { $in?: string[] } | undefined)?.$in ?? []) as string[]; + if (collectionName === 'eodPrices') { + const ids = + ((filter.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[]; + if (ids.length === 1 && ids[0] === FX_USD_CAD_SOURCE_ID) { + for (let d = 0; d < dates.length; d++) { + yield { + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date: dates[d], + close: Number((1.34 + (d % 7) * 0.005).toFixed(4)), + } as unknown as T; + } + return; + } + for (let d = 0; d < dates.length; d++) { + const date = dates[d]; + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + if (id === undefined) { + continue; + } + const idx = eodIndexById.get(id); + if (idx === undefined) { + continue; + } + yield { + eodSearchCode: id, + date, + close: deterministicClose(idx, d), + } as unknown as T; + } + } + return; + } + + if (collectionName === 'qmPrices') { + const ids = + ((filter.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[]; + for (let d = 0; d < dates.length; d++) { + const date = dates[d]; + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + if (id === undefined) { + continue; + } + const idx = qmIndexById.get(id); + if (idx === undefined) { + continue; + } + const baseClose = deterministicClose(idx, d); + const mult = idx % MISMATCH_EVERY === 0 ? 2 : 1; + yield { + qmSearchCode: id, + date, + unadjustedclose: Number((baseClose * mult).toFixed(4)), + } as unknown as T; + } + } + } + }, + async close(): Promise { + // No-op for in-memory benchmark cursor. + }, + }; + }, + }; + }, + }; + + const barSpanReader: BarSpanAggregateReader = { + aggregate = Record>( + collectionName: string, + pipeline: Record[] + ): AsyncIterable { + let requestedIds: string[] = []; + for (const stage of pipeline) { + const match = stage.$match as Record | undefined; + if (match && typeof match === 'object') { + for (const value of Object.values(match)) { + if ( + value && + typeof value === 'object' && + Array.isArray((value as { $in?: unknown }).$in) + ) { + requestedIds = (value as { $in: string[] }).$in; + } + } + } + } + const isEod = collectionName === 'eodPrices'; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < requestedIds.length; i++) { + const id = requestedIds[i]; + if (id === undefined) { + continue; + } + const exists = isEod ? eodIndexById.has(id) : qmIndexById.has(id); + if (!exists) { + continue; + } + const row: GroupedBarSpanRow = { + _id: id, + firstBarDate: FIRST_BAR_DATE, + lastBarDate: LAST_BAR_DATE, + barCount: 1510, + }; + yield row as unknown as T; + } + }, + }; + }, + }; + + return { mongoCollectionClient, barSpanReader }; +} + +async function main(): Promise { + const { mongoCollectionClient, barSpanReader } = createBenchmarkMongo(PAIR_COUNT); + + if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { + Bun.gc(true); + } + const heapBefore = process.memoryUsage().heapUsed; + const startedAt = performance.now(); + + const result = await runSecurityMaster( + { + mongoCollectionClient, + barSpanReader, + writeFile: () => {}, + writeStdout: () => {}, + }, + { + asOfDate: AS_OF_DATE, + outDir: '/virtual/benchmark-out', + batchSize: 5_000, + pass4: { enabled: true, sampleDateCount: SAMPLE_DATE_COUNT }, + } + ); + + const elapsedMs = performance.now() - startedAt; + const heapAfter = process.memoryUsage().heapUsed; + const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); + + if (result.composed.pass4 === null || result.sampleCloses === null) { + throw new Error('Benchmark failed: Pass 4 did not execute'); + } + + const expectedMismatches = Math.ceil(PAIR_COUNT / MISMATCH_EVERY); + const expectedConfirmed = PAIR_COUNT - expectedMismatches; + const { pairsIn, byVerdict } = result.composed.pass4.stats; + if ( + pairsIn !== PAIR_COUNT || + byVerdict.confirmed !== expectedConfirmed || + byVerdict.ratio_mismatch !== expectedMismatches + ) { + throw new Error( + `Benchmark verdict mismatch: pairsIn=${pairsIn}, confirmed=${byVerdict.confirmed} (expected ${expectedConfirmed}), ratio_mismatch=${byVerdict.ratio_mismatch} (expected ${expectedMismatches})` + ); + } + + const totalDocsRead = + result.sampleCloses.stats.eod.docsRead + + result.sampleCloses.stats.qm.docsRead + + result.sampleCloses.stats.fx.docsRead; + const pairsPerSec = Math.round(PAIR_COUNT / (elapsedMs / 1000)); + const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000)); + + const lines = [ + 'Pass 4b runSecurityMaster benchmark (in-memory async cursor, zero DB, zero disk)', + ` Workload: ${PAIR_COUNT.toLocaleString('en-US')} EOD<->QM pairs x ${SAMPLE_DATE_COUNT} dates (${totalDocsRead.toLocaleString('en-US')} sample-close/FX docs)`, + ` Verdicts: confirmed=${byVerdict.confirmed.toLocaleString('en-US')}, ratio_mismatch=${byVerdict.ratio_mismatch.toLocaleString('en-US')}, low_correlation=${byVerdict.low_correlation}, insufficient_data=${byVerdict.insufficient_data}`, + ` Elapsed: ${elapsedMs.toFixed(1)} ms`, + ` Throughput: ${pairsPerSec.toLocaleString('en-US')} pairs/s | ${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 0d6c305a..7dbcd44c 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -217,15 +217,19 @@ export { export { assertSecurityMasterPersistSafety, + buildSampleDateCalendar, formatRunSecurityMasterSummary, parseRunSecurityMasterArgs, RUN_SECURITY_MASTER_USAGE, runSecurityMaster, SECURITY_MASTER_OUTPUT_FILES, type ParsedRunSecurityMasterArgs, + type Pass4SkippedReason, type RunSecurityMasterDeps, type RunSecurityMasterOptions, type RunSecurityMasterOutput, + type RunSecurityMasterPass4Options, + type RunSecurityMasterPass4Summary, type SecurityMasterPostgresHandle, } from './run-security-master'; diff --git a/apps/stock/data-pipeline/src/security-master/run-security-master.ts b/apps/stock/data-pipeline/src/security-master/run-security-master.ts index d8090a05..ce107fa7 100644 --- a/apps/stock/data-pipeline/src/security-master/run-security-master.ts +++ b/apps/stock/data-pipeline/src/security-master/run-security-master.ts @@ -36,7 +36,18 @@ import { type SecurityMasterQueryable, type SecurityMasterQueryResult, } from './persist'; +import { + DEFAULT_SAMPLE_DATE_COUNT, + selectSampleDates, + type PriceCrossCheckVerdictCounts, +} from './price-cross-check'; import { composeSecurityMasterRun, type ComposeSecurityMasterRunResult } from './run'; +import { + MAX_SAMPLE_DATES, + readSampleCloses, + type ReadSampleClosesResult, + type ReadSampleClosesStats, +} from './sample-closes'; import { createExchangeSourceLookup, createReadOnlyMongoSourceSymbolReader, @@ -54,13 +65,15 @@ export const SECURITY_MASTER_OUTPUT_FILES = Object.freeze({ } as const); export const RUN_SECURITY_MASTER_USAGE = [ - 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of --out-dir [--persist] [--help]', + 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of --out-dir [--persist] [--skip-price-cross-check] [--sample-dates ] [--help]', '', 'Options:', - ' --as-of Required. Calendar reference date for Pass 6 delisting classification.', - ' --out-dir Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.', - ' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).', - ' --help Show this help message and exit.', + ' --as-of Required. Calendar reference date for Pass 6 delisting classification.', + ' --out-dir Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.', + ' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).', + ' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).', + ` --sample-dates Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`, + ' --help Show this help message and exit.', ].join('\n'); export type ParsedRunSecurityMasterArgs = @@ -70,8 +83,27 @@ export type ParsedRunSecurityMasterArgs = readonly asOfDate: string; readonly outDir: string; readonly persist: boolean; + readonly skipPriceCrossCheck: boolean; + readonly sampleDateCount: number; }; +export interface RunSecurityMasterPass4Options { + readonly enabled?: boolean; + readonly sampleDateCount?: number; +} + +export type Pass4SkippedReason = 'disabled' | 'no_sample_dates' | 'no_candidate_pairs'; + +export interface RunSecurityMasterPass4Summary { + readonly sampleDates: readonly string[]; + readonly candidatePairs: number; + readonly eodIdsRequested: number; + readonly qmIdsRequested: number; + readonly stats: ReadSampleClosesStats | null; + readonly byVerdict: PriceCrossCheckVerdictCounts | null; + readonly skippedReason: Pass4SkippedReason | null; +} + export interface SecurityMasterPostgresHandle { readonly queryable: SecurityMasterQueryable; close(): Promise | void; @@ -88,6 +120,8 @@ export interface RunSecurityMasterDeps { | Promise | SecurityMasterPostgresHandle; readonly persistFn?: typeof persistSecurityMaster; + readonly readSampleClosesFn?: typeof readSampleCloses; + readonly composeFn?: typeof composeSecurityMasterRun; readonly writeFile?: (filePath: string, content: string) => Promise | void; readonly writeStdout?: (text: string) => void; } @@ -99,6 +133,7 @@ export interface RunSecurityMasterOptions { readonly countries?: readonly string[] | null; readonly batchSize?: number; readonly barSpans?: Omit; + readonly pass4?: RunSecurityMasterPass4Options; } export interface RunSecurityMasterOutput { @@ -110,6 +145,8 @@ export interface RunSecurityMasterOutput { readonly exchangeCountsByCollection: Readonly>; readonly sources: SecurityMasterSourcesResult; readonly barSpans: ComputeBarSpansResult; + readonly sampleCloses: ReadSampleClosesResult | null; + readonly pass4: RunSecurityMasterPass4Summary; readonly composed: ComposeSecurityMasterRunResult; readonly persistResult: PersistSecurityMasterResult | null; readonly runStatsJson: string; @@ -117,6 +154,166 @@ export interface RunSecurityMasterOutput { } const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const STRICT_INT_PATTERN = /^-?\d+$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function parseYmdComponents(value: string): { year: number; month: number; day: number } | null { + if (!EXACT_YMD_PATTERN.test(value)) { + return null; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + if (year < 1 || year > 9999 || month < 1 || month > 12) { + return null; + } + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + if (day < 1 || day > maxDay) { + return null; + } + return { year, month, day }; +} + +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; +} + +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}`; +} + +/** + * Builds a deterministic ascending Mon-Fri YYYY-MM-DD calendar over the overlapping + * date window where both EOD and QM have observed bars, clamped to `asOfDate`. + */ +export function buildSampleDateCalendar( + barSpans: Pick, + asOfDate: string +): string[] { + if (!barSpans || !barSpans.index || !isValidAsOfDate(asOfDate)) { + return []; + } + + let minEodFirst: string | null = null; + let maxEodLast: string | null = null; + let minQmFirst: string | null = null; + let maxQmLast: string | null = null; + + for (const span of barSpans.index) { + if ( + !span || + typeof span.barCount !== 'number' || + !Number.isFinite(span.barCount) || + span.barCount <= 0 + ) { + continue; + } + if (span.source !== 'eod' && span.source !== 'qm') { + continue; + } + if ( + parseYmdComponents(span.firstBarDate) === null || + parseYmdComponents(span.lastBarDate) === null || + span.firstBarDate > span.lastBarDate + ) { + continue; + } + if (span.source === 'eod') { + if (minEodFirst === null || span.firstBarDate < minEodFirst) { + minEodFirst = span.firstBarDate; + } + if (maxEodLast === null || span.lastBarDate > maxEodLast) { + maxEodLast = span.lastBarDate; + } + } else { + if (minQmFirst === null || span.firstBarDate < minQmFirst) { + minQmFirst = span.firstBarDate; + } + if (maxQmLast === null || span.lastBarDate > maxQmLast) { + maxQmLast = span.lastBarDate; + } + } + } + + if (minEodFirst === null || maxEodLast === null || minQmFirst === null || maxQmLast === null) { + return []; + } + + const start = minEodFirst > minQmFirst ? minEodFirst : minQmFirst; + const overlapEnd = maxEodLast < maxQmLast ? maxEodLast : maxQmLast; + const end = overlapEnd < asOfDate ? overlapEnd : asOfDate; + + if (start > end) { + return []; + } + + const startParts = parseYmdComponents(start); + const endParts = parseYmdComponents(end); + if (startParts === null || endParts === null) { + return []; + } + + const startDay = daysFromCivil(startParts.year, startParts.month, startParts.day); + const endDay = daysFromCivil(endParts.year, endParts.month, endParts.day); + const calendar: string[] = []; + + for (let dayNum = startDay; dayNum <= endDay; dayNum++) { + const dow = (((dayNum + 4) % 7) + 7) % 7; + if (dow >= 1 && dow <= 5) { + const civil = civilFromDays(dayNum); + calendar.push(formatUtcYmd(civil.year, civil.month, civil.day)); + } + } + + return calendar; +} + +function parseSampleDateCountArg(raw: string): number { + if (!STRICT_INT_PATTERN.test(raw)) { + throw usageError( + `Invalid --sample-dates value "${raw}": expected an integer between 1 and ${MAX_SAMPLE_DATES}` + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_SAMPLE_DATES) { + throw usageError( + `Invalid --sample-dates value "${raw}": expected an integer between 1 and ${MAX_SAMPLE_DATES}` + ); + } + return parsed; +} function isValidAsOfDate(value: string): boolean { return EXACT_YMD_PATTERN.test(value) && normalizeBarDate(value) === value; @@ -152,6 +349,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe let asOfDate: string | undefined; let outDir: string | undefined; let persist = false; + let skipPriceCrossCheck = false; + let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; @@ -163,6 +362,27 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe persist = true; continue; } + if (arg === '--skip-price-cross-check') { + skipPriceCrossCheck = true; + continue; + } + if (arg === '--sample-dates') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --sample-dates'); + } + sampleDateCount = parseSampleDateCountArg(value); + i += 1; + continue; + } + if (arg?.startsWith('--sample-dates=')) { + const value = arg.slice('--sample-dates='.length); + if (value.trim().length === 0) { + throw usageError('Missing value for --sample-dates'); + } + sampleDateCount = parseSampleDateCountArg(value); + continue; + } if (arg === '--as-of') { const value = argv[i + 1]; if (!value || value.trim().length === 0 || value.startsWith('--')) { @@ -221,6 +441,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe asOfDate, outDir, persist, + skipPriceCrossCheck, + sampleDateCount, }; } @@ -262,9 +484,9 @@ export function formatRunSecurityMasterSummary( params: Pick< RunSecurityMasterOutput, 'asOfDate' | 'outDir' | 'persist' | 'filesWritten' | 'composed' - > + > & { readonly pass4?: RunSecurityMasterPass4Summary } ): string { - const { asOfDate, outDir, persist, composed } = params; + const { asOfDate, outDir, persist, composed, pass4 } = params; const resolutionParts = composed.report.resolutionBySource.map(row => { const pct = row.eligibleResolvedPct === null @@ -280,11 +502,25 @@ export function formatRunSecurityMasterSummary( SECURITY_MASTER_OUTPUT_FILES.runStatsJson, ]; + const pass4StatusLabel = + composed.stats.pass4.status === 'skipped' && pass4?.skippedReason + ? `skipped (${pass4.skippedReason})` + : composed.stats.pass4.status; + const pass4DateCount = pass4?.sampleDates.length ?? 0; + const byVerdict = composed.pass4?.stats.byVerdict ?? pass4?.byVerdict ?? null; + const pass4Line = + ` Pass 4 price cross-check: ${pass4StatusLabel} ` + + `(dates=${pass4DateCount}, ` + + `confirmed=${byVerdict?.confirmed ?? 0}, ` + + `ratio_mismatch=${byVerdict?.ratio_mismatch ?? 0}, ` + + `low_correlation=${byVerdict?.low_correlation ?? 0}, ` + + `insufficient_data=${byVerdict?.insufficient_data ?? 0})`; + const lines = [ `Security master run complete (as-of ${asOfDate})`, ` Instruments: ${composed.stageA.instruments.length} | Listings: ${composed.stageB.listings.length} | Conflicts: ${composed.report.conflicts.length}`, ` Resolution (eligible): ${resolutionParts.length > 0 ? resolutionParts.join(', ') : 'none'}`, - ` Pass 4 price cross-check: ${composed.stats.pass4.status} (sample closes not yet wired)`, + pass4Line, ` Files written (${outDir}): ${fileNames.join(', ')}`, ` Persisted: ${persist ? 'yes' : 'no (dry-run)'}`, ]; @@ -313,6 +549,37 @@ export async function runSecurityMaster( throw wrapStepError('validate-options', new Error('outDir must be a non-empty string')); } + let pass4Enabled = true; + let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT; + if (options.pass4 !== undefined) { + if (options.pass4 === null || typeof options.pass4 !== 'object') { + throw wrapStepError('validate-options', new Error('pass4 options must be an object')); + } + if (options.pass4.enabled !== undefined) { + if (typeof options.pass4.enabled !== 'boolean') { + throw wrapStepError('validate-options', new Error('pass4.enabled must be a boolean')); + } + pass4Enabled = options.pass4.enabled; + } + if (options.pass4.sampleDateCount !== undefined) { + const count = options.pass4.sampleDateCount; + if ( + typeof count !== 'number' || + !Number.isSafeInteger(count) || + count < 1 || + count > MAX_SAMPLE_DATES + ) { + throw wrapStepError( + 'validate-options', + new Error( + `Invalid pass4.sampleDateCount "${String(count)}": expected a positive safe integer <= ${MAX_SAMPLE_DATES}` + ) + ); + } + sampleDateCount = count; + } + } + // Step 1: Environment safety check before opening PostgreSQL or reading Mongo when --persist is requested. if (persist) { try { @@ -405,10 +672,11 @@ export async function runSecurityMaster( throw wrapStepError('compute-bar-spans', error); } - // Step 5: Compose Stage A -> Stage B -> Pass 6 -> Report + PersistInput (Pass 4 omitted). + // Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs. + const composeFn = deps.composeFn ?? composeSecurityMasterRun; let composed: ComposeSecurityMasterRunResult; try { - composed = composeSecurityMasterRun( + composed = composeFn( { sources, barSpans, @@ -422,10 +690,100 @@ export async function runSecurityMaster( throw wrapStepError('compose', error); } + // Step 5b: Read targeted sample closes + USD/CAD FX and re-compose with Pass 4 when applicable. + let pass4Wired = false; + let sampleCloses: ReadSampleClosesResult | null = null; + let pass4SampleDates: string[] = []; + let pass4EodIds: string[] = []; + let pass4QmIds: string[] = []; + let pass4SkippedReason: Pass4SkippedReason | null = null; + const candidatePairsCount = composed.pass4CandidatePairs.length; + + if (!pass4Enabled) { + pass4SkippedReason = 'disabled'; + } else { + const calendar = buildSampleDateCalendar(barSpans, options.asOfDate); + pass4SampleDates = + calendar.length > 0 ? selectSampleDates(calendar, { count: sampleDateCount }) : []; + + if (pass4SampleDates.length === 0) { + pass4SkippedReason = 'no_sample_dates'; + } else { + const eodRawIds: string[] = []; + const qmRawIds: string[] = []; + for (let i = 0; i < composed.pass4CandidatePairs.length; i++) { + const pair = composed.pass4CandidatePairs[i]; + if (!pair) { + continue; + } + if (pair.left.source === 'eod') { + eodRawIds.push(pair.left.sourceId); + } else if (pair.left.source === 'qm') { + qmRawIds.push(pair.left.sourceId); + } + if (pair.right.source === 'eod') { + eodRawIds.push(pair.right.sourceId); + } else if (pair.right.source === 'qm') { + qmRawIds.push(pair.right.sourceId); + } + } + pass4EodIds = collectSortedUniqueIds(eodRawIds); + pass4QmIds = collectSortedUniqueIds(qmRawIds); + + if (candidatePairsCount === 0 || (pass4EodIds.length === 0 && pass4QmIds.length === 0)) { + pass4SkippedReason = 'no_candidate_pairs'; + } else { + const readSampleClosesFn = deps.readSampleClosesFn ?? readSampleCloses; + try { + sampleCloses = await readSampleClosesFn(sourceReader, { + sampleDates: pass4SampleDates, + sourceIdsBySource: { + eod: pass4EodIds, + qm: pass4QmIds, + }, + includeFx: true, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }); + pass4Wired = true; + } catch (error) { + throw wrapStepError('read-sample-closes', error); + } + + try { + composed = composeFn( + { + sources, + barSpans, + exchanges, + sampleCloses: sampleCloses.closes, + fxRates: sampleCloses.fxRates, + }, + { + asOfDate: options.asOfDate, + } + ); + } catch (error) { + throw wrapStepError('compose', error); + } + } + } + } + + const pass4Summary: RunSecurityMasterPass4Summary = { + sampleDates: pass4SampleDates, + candidatePairs: candidatePairsCount, + eodIdsRequested: pass4EodIds.length, + qmIdsRequested: pass4QmIds.length, + stats: sampleCloses?.stats ?? null, + byVerdict: composed.pass4?.stats.byVerdict ?? null, + skippedReason: pass4SkippedReason, + }; + // Step 6: Write deterministic artifacts into outDir. const statsArtifact = { asOfDate: options.asOfDate, - pass4Wired: false, + pass4Wired, + pass4: pass4Summary, exchanges: { countsByCollection: exchangeCountsByCollection, mapped: exchanges.mapped.length, @@ -516,6 +874,7 @@ export async function runSecurityMaster( persist, filesWritten, composed, + pass4: pass4Summary, }); output = { @@ -527,6 +886,8 @@ export async function runSecurityMaster( exchangeCountsByCollection, sources, barSpans, + sampleCloses, + pass4: pass4Summary, composed, persistResult, runStatsJson, @@ -664,6 +1025,10 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P asOfDate: parsed.asOfDate, outDir: parsed.outDir, persist: parsed.persist, + pass4: { + enabled: !parsed.skipPriceCrossCheck, + sampleDateCount: parsed.sampleDateCount, + }, } ); } diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts index faba4bee..675c30bd 100644 --- a/test/unit/security-master-run-cli.test.ts +++ b/test/unit/security-master-run-cli.test.ts @@ -5,29 +5,39 @@ import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { assertEnvironmentSafety, stockAppSchema } from '@stock-bot/stock-config'; import { + BarSpanIndex, computeBarSpans, type BarSpanAggregateReader, type GroupedBarSpanRow, } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; import { assertSecurityMasterPersistSafety, + buildSampleDateCalendar, classifySourceExchanges, compareAscii, composeSecurityMasterRun, createExchangeSourceLookup, createReadOnlyMongoSourceSymbolReader, + crossCheckPrices, + DEFAULT_SAMPLE_DATE_COUNT, EXCHANGE_SOURCES, + FX_USD_CAD_SOURCE_ID, ISO_EXCHANGE_SEEDS, + MAX_SAMPLE_DATES, normalizeRawExchangeDoc, parseRunSecurityMasterArgs, + readSampleCloses, readSecurityMasterSources, RUN_SECURITY_MASTER_USAGE, runSecurityMaster, SECURITY_MASTER_OUTPUT_FILES, + selectSampleDates, SOURCE_EXCHANGE_COLLECTIONS, + type ComposeSecurityMasterRunInput, type PersistSecurityMasterInput, type PersistSecurityMasterResult, type ReadOnlyMongoCollectionClient, + type ReadSampleClosesOptions, type SecurityMasterPostgresHandle, type SecurityMasterQueryable, type SourceExchangeRecord, @@ -93,6 +103,33 @@ function extractRequestedIdsFromPipeline(pipeline: readonly Record; + readonly options?: Record; +} + +function matchesFakeFindFilter( + doc: Record, + filter: Record +): boolean { + for (const [field, condition] of Object.entries(filter)) { + if ( + condition !== null && + typeof condition === 'object' && + Array.isArray((condition as { $in?: unknown }).$in) + ) { + const allowed = new Set((condition as { $in: unknown[] }).$in); + if (!allowed.has(doc[field])) { + return false; + } + } else if (doc[field] !== condition) { + return false; + } + } + return true; +} + function createStrictReadOnlyFakeMongo( fixture: FakeMongoFixture, options: { @@ -105,10 +142,12 @@ function createStrictReadOnlyFakeMongo( readonly barSpanReader: BarSpanAggregateReader; readonly aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }>; readonly findCalls: string[]; + readonly findCallDetails: FindCallDetail[]; } { const readOnly = options.readOnly ?? true; const aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }> = []; const findCalls: string[] = []; + const findCallDetails: FindCallDetail[] = []; const target = { isReadOnly(): boolean { @@ -116,13 +155,23 @@ function createStrictReadOnlyFakeMongo( }, getCollection(collectionName: string) { const colTarget = { - find(_filter: Record = {}) { + find(filter: Record = {}, findOptions?: Record) { findCalls.push(collectionName); + findCallDetails.push({ + collectionName, + filter, + ...(findOptions !== undefined ? { options: findOptions } : {}), + }); if (options.failCollection === collectionName) { throw new Error(`Simulated Mongo find failure on ${collectionName}`); } const docs = fixture.collections[collectionName] ?? []; - return makeAsyncCursor(docs); + const filtered = + (collectionName === 'eodPrices' || collectionName === 'qmPrices') && + Object.keys(filter).length > 0 + ? docs.filter(doc => matchesFakeFindFilter(doc, filter)) + : docs; + return makeAsyncCursor(filtered); }, }; @@ -174,10 +223,53 @@ function createStrictReadOnlyFakeMongo( barSpanReader: proxy as unknown as BarSpanAggregateReader, aggregateCalls, findCalls, + findCallDetails, }; } -function buildUsCaFixture(): FakeMongoFixture { +function buildUsCaFixture(options: { readonly qmPriceMultiplier?: number } = {}): FakeMongoFixture { + const qmMultiplier = options.qmPriceMultiplier ?? 1; + const spanIndex = new BarSpanIndex(); + spanIndex.merge({ + source: 'eod', + sourceId: 'AAPL.US', + firstBarDate: '2015-01-02', + lastBarDate: '2026-01-14', + barCount: 2770, + }); + spanIndex.merge({ + source: 'qm', + sourceId: 'AAPL:US', + firstBarDate: '2018-01-02', + lastBarDate: '2026-01-14', + barCount: 2015, + }); + const calendar = buildSampleDateCalendar({ index: spanIndex }, '2026-01-15'); + const fixtureDates = Array.from( + new Set([ + ...selectSampleDates(calendar, { count: DEFAULT_SAMPLE_DATE_COUNT }), + ...selectSampleDates(calendar, { count: 10 }), + ]) + ).sort(compareAscii); + + const eodPrices: Record[] = []; + const qmPrices: Record[] = []; + for (let i = 0; i < fixtureDates.length; i++) { + const date = fixtureDates[i]!; + const aaplClose = Number((100 + ((i * 17) % 53) + i * 0.75).toFixed(4)); + const shopClose = Number((60 + ((i * 11) % 31) + i * 0.5).toFixed(4)); + const fxRate = Number((1.32 + (i % 9) * 0.012).toFixed(4)); + eodPrices.push( + { eodSearchCode: 'AAPL.US', date, close: aaplClose }, + { eodSearchCode: 'SHOP.TO', date, close: shopClose }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date, close: fxRate } + ); + qmPrices.push( + { qmSearchCode: 'AAPL:US', date, unadjustedclose: Number((aaplClose * qmMultiplier).toFixed(4)) }, + { qmSearchCode: 'MYSTERY:CA', date, unadjustedclose: Number((25 + i * 0.4).toFixed(4)) } + ); + } + return { collections: { eodExchanges: [ @@ -255,6 +347,8 @@ function buildUsCaFixture(): FakeMongoFixture { ], ceoSymbols: [], eodSymbolChange: [], + eodPrices, + qmPrices, }, barSpanRowsByCollection: { eodPrices: [ @@ -333,27 +427,50 @@ function assertObjectKeysSortedAscii(value: unknown, path = '$'): void { } describe('parseRunSecurityMasterArgs', () => { - test('parses required space-separated args with default persist=false', () => { + test('parses required space-separated args with default persist=false and Pass 4 enabled', () => { const parsed = parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './tmp/out']); expect(parsed).toEqual({ help: false, asOfDate: '2026-01-15', outDir: './tmp/out', persist: false, + skipPriceCrossCheck: false, + sampleDateCount: DEFAULT_SAMPLE_DATE_COUNT, }); }); - test('parses = syntax, leap day, and --persist flag', () => { + test('parses = syntax, leap day, --persist, --skip-price-cross-check, and --sample-dates', () => { const parsed = parseRunSecurityMasterArgs([ '--as-of=2024-02-29', '--out-dir=/tmp/sm-report', '--persist', + '--skip-price-cross-check', + '--sample-dates=10', ]); expect(parsed).toEqual({ help: false, asOfDate: '2024-02-29', outDir: '/tmp/sm-report', persist: true, + skipPriceCrossCheck: true, + sampleDateCount: 10, + }); + + const parsedSpace = parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './tmp/out', + '--sample-dates', + String(MAX_SAMPLE_DATES), + ]); + expect(parsedSpace).toEqual({ + help: false, + asOfDate: '2026-01-15', + outDir: './tmp/out', + persist: false, + skipPriceCrossCheck: false, + sampleDateCount: MAX_SAMPLE_DATES, }); }); @@ -362,6 +479,8 @@ describe('parseRunSecurityMasterArgs', () => { expect(RUN_SECURITY_MASTER_USAGE).toContain('--as-of'); expect(RUN_SECURITY_MASTER_USAGE).toContain('--out-dir'); expect(RUN_SECURITY_MASTER_USAGE).toContain('--persist'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--skip-price-cross-check'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--sample-dates'); }); test('rejects missing --as-of or --out-dir', () => { @@ -377,6 +496,47 @@ describe('parseRunSecurityMasterArgs', () => { } }); + test('rejects invalid --sample-dates values (0, 65, negative, float, non-numeric, missing)', () => { + for (const badValue of ['0', String(MAX_SAMPLE_DATES + 1), '-1', '10.5', 'abc', '10abc']) { + expect(() => + parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './out', + '--sample-dates', + badValue, + ]) + ).toThrow(/Invalid --sample-dates value/); + expect(() => + parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './out', + `--sample-dates=${badValue}`, + ]) + ).toThrow(/Invalid --sample-dates value/); + } + + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--sample-dates']) + ).toThrow(/Missing value for --sample-dates/); + expect(() => + parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './out', + '--sample-dates', + '--persist', + ]) + ).toThrow(/Missing value for --sample-dates/); + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--sample-dates=']) + ).toThrow(/Missing value for --sample-dates/); + }); + test('rejects unknown flags, positional args, and flags missing values', () => { expect(() => parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--unknown']) @@ -447,11 +607,25 @@ describe('runSecurityMaster', () => { qm: ['AAPL:US', 'MYSTERY:CA'], }, }); + const expectedCalendar = buildSampleDateCalendar(expectedBarSpans, '2026-01-15'); + const expectedSampleDates = selectSampleDates(expectedCalendar, { + count: DEFAULT_SAMPLE_DATE_COUNT, + }); + const expectedSampleCloses = await readSampleCloses(refReader, { + sampleDates: expectedSampleDates, + sourceIdsBySource: { + eod: ['AAPL.US'], + qm: ['AAPL:US'], + }, + includeFx: true, + }); const expectedComposed = composeSecurityMasterRun( { sources: expectedSources, barSpans: expectedBarSpans, exchanges: expectedExchanges, + sampleCloses: expectedSampleCloses.closes, + fxRates: expectedSampleCloses.fxRates, }, { asOfDate: '2026-01-15' } ); @@ -481,8 +655,26 @@ describe('runSecurityMaster', () => { const parsedStats = JSON.parse(runStatsContent) as Record; assertObjectKeysSortedAscii(parsedStats); expect(parsedStats.asOfDate).toBe('2026-01-15'); - expect(parsedStats.pass4Wired).toBe(false); - expect(result.composed.pass4).toBeNull(); + expect(parsedStats.pass4Wired).toBe(true); + expect(result.composed.pass4).not.toBeNull(); + expect(result.composed.pass4?.stats.byVerdict.confirmed).toBeGreaterThanOrEqual(1); + const pass4Stats = parsedStats.pass4 as { + sampleDates: string[]; + candidatePairs: number; + eodIdsRequested: number; + qmIdsRequested: number; + skippedReason: string | null; + byVerdict: Record | null; + }; + expect(pass4Stats.sampleDates.length).toBeGreaterThanOrEqual(5); + expect(pass4Stats.sampleDates.length).toBeLessThanOrEqual(DEFAULT_SAMPLE_DATE_COUNT); + // AAPL has 3 sources on XNAS (eod, ib, qm) -> 3 pairwise candidate pairs, + // with 1 eod ID (AAPL.US) and 1 qm ID (AAPL:US) requested for sample closes. + expect(pass4Stats.candidatePairs).toBe(3); + expect(pass4Stats.eodIdsRequested).toBe(1); + expect(pass4Stats.qmIdsRequested).toBe(1); + expect(pass4Stats.skippedReason).toBeNull(); + expect(pass4Stats.byVerdict?.confirmed).toBeGreaterThanOrEqual(1); expect(result.composed.stageA.instruments.length).toBe(2); expect(result.composed.stageB.unresolved.some(u => u.sourceId === 'MYSTERY:CA')).toBe(true); @@ -491,7 +683,13 @@ describe('runSecurityMaster', () => { expect(summaryText).toContain('Instruments: 2'); expect(summaryText).toContain('Persisted: no (dry-run)'); expect(summaryText).toContain('match-report.md'); - expect(summaryText).toContain('skipped'); + expect(summaryText).toContain('executed'); + expect(summaryText).toContain(`dates=${pass4Stats.sampleDates.length}`); + expect(summaryText).toContain('confirmed=1'); + expect(summaryText).toContain('ratio_mismatch=0'); + expect(summaryText).toContain('low_correlation=0'); + expect(summaryText).toContain('insufficient_data=2'); + expect(summaryText).not.toContain('not yet wired'); }); test('produces byte-identical files across repeated runs in different output directories', async () => { @@ -1509,6 +1707,8 @@ describe('run-security-master CLI process', () => { test('usage errors exit non-zero with an Error line on stderr and no success summary', () => { for (const args of [ ['--as-of', '2026-02-30', '--out-dir', 'x'], + ['--as-of', '2026-01-15', '--out-dir', 'x', '--sample-dates', '0'], + ['--as-of', '2026-01-15', '--out-dir', 'x', '--sample-dates', '65'], ['--bogus'], ['--out-dir', 'x'], ]) { @@ -1519,3 +1719,611 @@ describe('run-security-master CLI process', () => { } }); }); + +describe('buildSampleDateCalendar', () => { + test('excludes weekends and clamps end date to min(eod, qm, asOfDate)', () => { + const index = new BarSpanIndex(); + // 2024-01-04 (Thu) .. 2024-01-15 (Mon) + index.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2024-01-01', + lastBarDate: '2024-01-15', + barCount: 10, + }); + index.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2024-01-04', + lastBarDate: '2024-01-12', + barCount: 7, + }); + + // Clamped to asOfDate=2024-01-10 (Wed); excludes Sat 2024-01-06 and Sun 2024-01-07 + const clamped = buildSampleDateCalendar({ index }, '2024-01-10'); + expect(clamped).toEqual([ + '2024-01-04', + '2024-01-05', + '2024-01-08', + '2024-01-09', + '2024-01-10', + ]); + + // When asOfDate is later than qm lastBarDate, end clamps to qm lastBarDate (2024-01-12) + const qmClamped = buildSampleDateCalendar({ index }, '2024-01-20'); + expect(qmClamped).toEqual([ + '2024-01-04', + '2024-01-05', + '2024-01-08', + '2024-01-09', + '2024-01-10', + '2024-01-11', + '2024-01-12', + ]); + }); + + test('returns empty array when a source has no spans, start > end, weekend-only, or invalid asOfDate', () => { + // Missing QM + const onlyEod = new BarSpanIndex(); + onlyEod.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2024-01-01', + lastBarDate: '2024-01-31', + barCount: 20, + }); + expect(buildSampleDateCalendar({ index: onlyEod }, '2024-01-31')).toEqual([]); + + // Missing EOD + const onlyQm = new BarSpanIndex(); + onlyQm.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2024-01-01', + lastBarDate: '2024-01-31', + barCount: 20, + }); + expect(buildSampleDateCalendar({ index: onlyQm }, '2024-01-31')).toEqual([]); + + // Non-overlapping (start > end) + const disjoint = new BarSpanIndex(); + disjoint.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2020-01-02', + lastBarDate: '2021-12-31', + barCount: 500, + }); + disjoint.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2022-01-03', + lastBarDate: '2024-01-15', + barCount: 500, + }); + expect(buildSampleDateCalendar({ index: disjoint }, '2024-01-15')).toEqual([]); + + // Weekend-only window: 2024-01-06 (Sat) .. 2024-01-07 (Sun) + const weekendOnly = new BarSpanIndex(); + weekendOnly.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2024-01-06', + lastBarDate: '2024-01-07', + barCount: 1, + }); + weekendOnly.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2024-01-06', + lastBarDate: '2024-01-07', + barCount: 1, + }); + expect(buildSampleDateCalendar({ index: weekendOnly }, '2024-01-10')).toEqual([]); + + // Invalid asOfDate + expect(buildSampleDateCalendar({ index: onlyEod }, '2023-02-29')).toEqual([]); + }); + + test('is deterministic across repeated calls regardless of BarSpanIndex insertion order', () => { + const spans = [ + { source: 'eod' as const, sourceId: 'B.US', firstBarDate: '2024-01-05', lastBarDate: '2024-01-19', barCount: 11 }, + { source: 'eod' as const, sourceId: 'A.US', firstBarDate: '2024-01-02', lastBarDate: '2024-01-10', barCount: 7 }, + { source: 'qm' as const, sourceId: 'B:US', firstBarDate: '2024-01-08', lastBarDate: '2024-01-26', barCount: 15 }, + { source: 'qm' as const, sourceId: 'A:US', firstBarDate: '2024-01-03', lastBarDate: '2024-01-12', barCount: 8 }, + ]; + const indexA = new BarSpanIndex(); + for (const s of spans) { + indexA.merge(s); + } + const indexB = new BarSpanIndex(); + for (const s of [...spans].reverse()) { + indexB.merge(s); + } + const calA1 = buildSampleDateCalendar({ index: indexA }, '2024-01-18'); + const calA2 = buildSampleDateCalendar({ index: indexA }, '2024-01-18'); + const calB = buildSampleDateCalendar({ index: indexB }, '2024-01-18'); + expect(calA1).toEqual(calA2); + expect(calA1).toEqual(calB); + }); +}); + +describe('runSecurityMaster Pass 4 wiring', () => { + test('2x non-FX price ratio mismatch produces price_ratio_mismatch in conflicts.csv and match-report.md', async () => { + const fixture = buildUsCaFixture({ qmPriceMultiplier: 2 }); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-conflict-'); + const stdoutChunks: string[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(result.composed.pass4).not.toBeNull(); + expect(result.composed.pass4?.stats.byVerdict.ratio_mismatch).toBeGreaterThanOrEqual(1); + + const conflictsCsv = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), + 'utf8' + ); + const matchReport = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), + 'utf8' + ); + expect(conflictsCsv).toContain('price_ratio_mismatch'); + expect(matchReport).toContain('price_ratio_mismatch'); + expect(stdoutChunks.join('')).toContain('ratio_mismatch=1'); + }); + + test('FX forwarding (Option A Test 1): reads CAD.FOREX with includeFx=true and forwards fxRates to compose', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-fx-'); + + const capturedReadOptions: ReadSampleClosesOptions[] = []; + const capturedComposeInputs: ComposeSecurityMasterRunInput[] = []; + let readFxRatesCount = 0; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + readSampleClosesFn: async (reader, options) => { + expect(reader.isReadOnly()).toBe(true); + capturedReadOptions.push(options); + const readResult = await readSampleCloses(reader, options); + readFxRatesCount = readResult.fxRates.length; + return readResult; + }, + composeFn: (input, options) => { + capturedComposeInputs.push(input); + return composeSecurityMasterRun(input, options); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(capturedReadOptions).toHaveLength(1); + expect(capturedReadOptions[0]?.includeFx).toBe(true); + expect(capturedComposeInputs).toHaveLength(2); + expect(capturedComposeInputs[0]?.fxRates).toBeUndefined(); + expect(result.sampleCloses).not.toBeNull(); + expect(readFxRatesCount).toBe(result.pass4.sampleDates.length); + expect(capturedComposeInputs[1]?.fxRates).toEqual(result.sampleCloses?.fxRates); + + const fxFinds = fakeMongo.findCallDetails.filter( + call => + call.collectionName === 'eodPrices' && + Array.isArray((call.filter.eodSearchCode as { $in?: unknown[] } | undefined)?.$in) && + (call.filter.eodSearchCode as { $in: unknown[] }).$in.includes(FX_USD_CAD_SOURCE_ID) + ); + expect(fxFinds).toHaveLength(1); + expect(fxFinds[0]?.filter).toEqual({ + date: { $in: result.pass4.sampleDates }, + eodSearchCode: { $in: [FX_USD_CAD_SOURCE_ID] }, + }); + + const parsedStats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4: { stats: { fx: { emitted: number } } } }; + expect(parsedStats.pass4.stats.fx.emitted).toBe(readFxRatesCount); + }); + + test('USD/CAD verdict (Option A Test 2): crossCheckPrices confirms USD EOD vs CAD QM pair using extracted fxRates', async () => { + const dates = [ + '2025-01-06', + '2025-02-05', + '2025-03-05', + '2025-04-07', + '2025-05-05', + '2025-06-05', + ]; + const usdCloses = [80.0, 88.5, 84.2, 95.1, 102.4, 98.7]; + const fxRates = [1.34, 1.36, 1.35, 1.38, 1.37, 1.39]; + + const fakeMongo = createStrictReadOnlyFakeMongo({ + collections: { + eodPrices: [ + ...dates.map((date, idx) => ({ + eodSearchCode: 'SHOP.US', + date, + close: usdCloses[idx], + })), + ...dates.map((date, idx) => ({ + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date, + close: fxRates[idx], + })), + ], + qmPrices: dates.map((date, idx) => ({ + qmSearchCode: 'SHOP:CA', + date, + unadjustedclose: Number(((usdCloses[idx] ?? 0) * (fxRates[idx] ?? 0)).toFixed(6)), + })), + }, + }); + const reader = createReadOnlyMongoSourceSymbolReader(fakeMongo.mongoCollectionClient); + const extracted = await readSampleCloses(reader, { + sampleDates: dates, + sourceIdsBySource: { eod: ['SHOP.US'], qm: ['SHOP:CA'] }, + includeFx: true, + }); + + const pair = { + left: { source: 'eod', sourceId: 'SHOP.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'SHOP:CA', currency: 'CAD' }, + }; + + const withFx = crossCheckPrices({ + pairs: [pair], + closes: extracted.closes, + usdCadByDate: extracted.fxRates, + }); + expect(withFx.results).toHaveLength(1); + expect(withFx.results[0]?.verdict).toBe('confirmed'); + expect(withFx.stats.byVerdict.confirmed).toBe(1); + + const withoutFx = crossCheckPrices({ + pairs: [pair], + closes: extracted.closes, + usdCadByDate: [], + }); + expect(withoutFx.results[0]?.verdict).toBe('insufficient_data'); + expect(withoutFx.stats.byVerdict.confirmed).toBe(0); + expect(withoutFx.stats.skippedMissingFxDates).toBeGreaterThanOrEqual(5); + }); + + test('query-shape & read-only guard: sample-close reads use date $in filter and request only Pass 4 endpoint IDs', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-query-'); + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + const priceFinds = fakeMongo.findCallDetails.filter( + call => call.collectionName === 'eodPrices' || call.collectionName === 'qmPrices' + ); + expect(priceFinds).toHaveLength(3); // EOD equity, QM equity, EOD FX + + for (const call of priceFinds) { + expect(call.filter.date).toEqual({ $in: result.pass4.sampleDates }); + } + + const eodEquityFind = priceFinds.find( + call => + call.collectionName === 'eodPrices' && + !(call.filter.eodSearchCode as { $in: string[] }).$in.includes(FX_USD_CAD_SOURCE_ID) + ); + const qmEquityFind = priceFinds.find(call => call.collectionName === 'qmPrices'); + + // Only AAPL.US and AAPL:US are Pass 4 endpoints; SHOP.TO, MYSTERY:CA, and IB 265598 are excluded. + expect(eodEquityFind?.filter.eodSearchCode).toEqual({ $in: ['AAPL.US'] }); + expect(qmEquityFind?.filter.qmSearchCode).toEqual({ $in: ['AAPL:US'] }); + }); + + test('skip paths (disabled, no_sample_dates, no_candidate_pairs) issue zero sample-close reads', async () => { + // (a) pass4.enabled: false + { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir('sm-skip-disabled-'); + const stdoutChunks: string[] = []; + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir, pass4: { enabled: false } } + ); + expect( + fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices') + ).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBe('disabled'); + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4Wired: boolean; pass4: { skippedReason: string | null } }; + expect(stats.pass4Wired).toBe(false); + expect(stats.pass4.skippedReason).toBe('disabled'); + expect(stdoutChunks.join('')).toContain('skipped (disabled)'); + } + + // (b) non-overlapping EOD/QM bar spans -> no_sample_dates + { + const base = buildUsCaFixture(); + const nonOverlapping: FakeMongoFixture = { + ...base, + barSpanRowsByCollection: { + eodPrices: [ + { _id: 'AAPL.US', firstBarDate: '2015-01-02', lastBarDate: '2017-12-29', barCount: 750 }, + ], + qmPrices: [ + { _id: 'AAPL:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 }, + ], + }, + }; + const fakeMongo = createStrictReadOnlyFakeMongo(nonOverlapping); + const outDir = createTempDir('sm-skip-nodates-'); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + expect( + fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices') + ).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBe('no_sample_dates'); + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4Wired: boolean; pass4: { skippedReason: string | null } }; + expect(stats.pass4Wired).toBe(false); + expect(stats.pass4.skippedReason).toBe('no_sample_dates'); + } + + // (c) zero candidate pairs -> no_candidate_pairs + { + const base = buildUsCaFixture(); + const noPairs: FakeMongoFixture = { + ...base, + collections: { + ...base.collections, + // Keep only unpaired SHOP.TO (EOD) and MYSTERY:CA (QM) with overlapping spans + eodSymbols: (base.collections.eodSymbols ?? []).filter(d => d.eodSearchCode === 'SHOP.TO'), + ibSymbols: [], + qmSymbols: (base.collections.qmSymbols ?? []).filter(d => d.qmSearchCode === 'MYSTERY:CA'), + }, + }; + const fakeMongo = createStrictReadOnlyFakeMongo(noPairs); + const outDir = createTempDir('sm-skip-nopairs-'); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + expect( + fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices') + ).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBe('no_candidate_pairs'); + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4Wired: boolean; pass4: { skippedReason: string | null } }; + expect(stats.pass4Wired).toBe(false); + expect(stats.pass4.skippedReason).toBe('no_candidate_pairs'); + } + }); + + test('sample-close read failure wraps step read-sample-closes, writes no artifacts, skips persist, and closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { + failCollection: 'qmPrices', + }); + const writes: string[] = []; + const stdout: string[] = []; + let pgFactoryCalls = 0; + let persistCalls = 0; + let mongoClosed = 0; + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('must not be called'); + }, + persistFn: async () => { + persistCalls += 1; + return makeFakePersistResult(); + }, + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: '/virtual/out', persist: true } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('read-sample-closes'); + expect(writes).toHaveLength(0); + expect(pgFactoryCalls).toBe(0); + expect(persistCalls).toBe(0); + expect(stdout).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('programmatic pass4 option validation rejects invalid counts before Mongo and respects sampleDateCount=10', async () => { + for (const badCount of [0, MAX_SAMPLE_DATES + 1, -1, 10.5, Number.NaN]) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { + asOfDate: '2026-01-15', + outDir: createTempDir(), + pass4: { sampleDateCount: badCount }, + } + ); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('validate-options'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + + // Valid sampleDateCount=10 yields at most 10 sample dates + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { + asOfDate: '2026-01-15', + outDir: createTempDir(), + pass4: { sampleDateCount: 10 }, + } + ); + expect(result.pass4.sampleDates.length).toBeLessThanOrEqual(10); + expect(result.pass4.sampleDates.length).toBe(10); + expect(result.composed.pass4?.stats.byVerdict.confirmed).toBe(1); + }); + + test('determinism: repeated runs with Pass 4 active (confirmed + conflict) write byte-identical artifacts', async () => { + const base = buildUsCaFixture(); + // Add a second paired security (MSFT) with a 2x conflict so both confirmed and conflict paths are active. + const msftEodDates = (base.collections.eodPrices ?? []) + .filter(d => d.eodSearchCode === 'AAPL.US') + .map(d => String(d.date)); + const deterministicFixture: FakeMongoFixture = { + collections: { + ...base.collections, + eodSymbols: [ + ...(base.collections.eodSymbols ?? []), + { + eodSearchCode: 'MSFT.US', + Code: 'MSFT', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US5949181045', + Cusip: '594918104', + Name: 'Microsoft Corp', + Type: 'Common Stock', + delisted: false, + }, + ], + qmSymbols: [ + ...(base.collections.qmSymbols ?? []), + { + qmSearchCode: 'MSFT:US', + symbol: 'MSFT', + exchange: 'NSD', + countryCode: 'US', + currency: 'USD', + name: 'Microsoft Corp', + active: true, + }, + ], + eodPrices: [ + ...(base.collections.eodPrices ?? []), + ...msftEodDates.map((date, idx) => ({ + eodSearchCode: 'MSFT.US', + date, + close: Number((200 + ((idx * 13) % 41) + idx * 0.9).toFixed(4)), + })), + ], + qmPrices: [ + ...(base.collections.qmPrices ?? []), + ...msftEodDates.map((date, idx) => ({ + qmSearchCode: 'MSFT:US', + date, + unadjustedclose: Number(((200 + ((idx * 13) % 41) + idx * 0.9) * 2).toFixed(4)), + })), + ], + }, + barSpanRowsByCollection: { + eodPrices: [ + ...(base.barSpanRowsByCollection?.eodPrices ?? []), + { _id: 'MSFT.US', firstBarDate: '2015-01-02', lastBarDate: '2026-01-14', barCount: 2770 }, + ], + qmPrices: [ + ...(base.barSpanRowsByCollection?.qmPrices ?? []), + { _id: 'MSFT:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 }, + ], + }, + }; + + const outDir1 = createTempDir('sm-pass4-det-1-'); + const outDir2 = createTempDir('sm-pass4-det-2-'); + const mongo1 = createStrictReadOnlyFakeMongo(deterministicFixture); + const mongo2 = createStrictReadOnlyFakeMongo(deterministicFixture); + + const run1 = await runSecurityMaster( + { + mongoCollectionClient: mongo1.mongoCollectionClient, + barSpanReader: mongo1.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: outDir1 } + ); + await runSecurityMaster( + { + mongoCollectionClient: mongo2.mongoCollectionClient, + barSpanReader: mongo2.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: outDir2 } + ); + + expect(run1.composed.pass4?.stats.byVerdict.confirmed).toBe(1); + expect(run1.composed.pass4?.stats.byVerdict.ratio_mismatch).toBe(1); + + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + const content1 = readFileSync(join(outDir1, filename), 'utf8'); + const content2 = readFileSync(join(outDir2, filename), 'utf8'); + expect(content2, `${filename} differed between Pass 4 runs`).toBe(content1); + } + }); +}); From c9fd52cbbc19b7f20dce8a0b020a1ab96dbefdf3 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 21:21:53 -0500 Subject: [PATCH 5/5] T-105: tests --- test/unit/security-master-run-cli.test.ts | 310 ++++++++++++++++++++++ 1 file changed, 310 insertions(+) diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts index 675c30bd..926377b1 100644 --- a/test/unit/security-master-run-cli.test.ts +++ b/test/unit/security-master-run-cli.test.ts @@ -2327,3 +2327,313 @@ describe('runSecurityMaster Pass 4 wiring', () => { } }); }); + +describe('runSecurityMaster Pass 4 wiring (QA edge cases)', () => { + test('read runs but returns no closes: pass4Wired=true, composed.pass4 null, artifacts still written', async () => { + const base = buildUsCaFixture(); + const fixture: FakeMongoFixture = { + ...base, + collections: { ...base.collections, eodPrices: [], qmPrices: [] }, + }; + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-empty-'); + const stdoutChunks: string[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices')).toHaveLength(3); + expect(result.sampleCloses).not.toBeNull(); + expect(result.sampleCloses?.closes).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBeNull(); + expect(result.pass4.byVerdict).toBeNull(); + expect(result.pass4.sampleDates).toHaveLength(DEFAULT_SAMPLE_DATE_COUNT); + + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { + pass4Wired: boolean; + pass4: { + byVerdict: unknown; + skippedReason: unknown; + stats: { eod: { emitted: number }; qm: { emitted: number }; fx: { emitted: number } }; + }; + }; + expect(stats.pass4Wired).toBe(true); + expect(stats.pass4.byVerdict).toBeNull(); + expect(stats.pass4.skippedReason).toBeNull(); + expect(stats.pass4.stats.eod.emitted).toBe(0); + expect(stats.pass4.stats.qm.emitted).toBe(0); + expect(stats.pass4.stats.fx.emitted).toBe(0); + + const conflictsCsv = readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), 'utf8'); + expect(conflictsCsv).not.toContain('price_ratio_mismatch'); + const summary = stdoutChunks.join(''); + expect(summary).toContain('Pass 4 price cross-check: skipped'); + expect(summary).toContain(`dates=${DEFAULT_SAMPLE_DATE_COUNT}`); + expect(summary).toContain('confirmed=0'); + expect(summary).not.toContain('not yet wired'); + }); + + test('--persist with Pass 4 active persists the second (price-checked) compose result', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture({ qmPriceMultiplier: 2 })); + const composeResults: ReturnType[] = []; + const persistInputs: PersistSecurityMasterInput[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + assertSafety: () => {}, + createPostgresClient: (): SecurityMasterPostgresHandle => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => {}, + }), + persistFn: async (_queryable, input) => { + persistInputs.push(input); + return makeFakePersistResult(); + }, + composeFn: (input, options) => { + const composedResult = composeSecurityMasterRun(input, options); + composeResults.push(composedResult); + return composedResult; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir('sm-pass4-persist-'), persist: true } + ); + + expect(composeResults).toHaveLength(2); + expect(composeResults[0]?.pass4).toBeNull(); + expect(composeResults[1]?.pass4?.stats.byVerdict.ratio_mismatch).toBe(1); + expect(persistInputs).toHaveLength(1); + expect(persistInputs[0] === composeResults[1]?.persistInput).toBe(true); + expect(result.composed === composeResults[1]).toBe(true); + }); + + test('second compose failure rejects at compose after the read, writes nothing, closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const writes: string[] = []; + const stdout: string[] = []; + let composeCalls = 0; + let readCalls = 0; + let mongoClosed = 0; + let caught: unknown = null; + + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + readSampleClosesFn: async (reader, options) => { + readCalls += 1; + return readSampleCloses(reader, options); + }, + composeFn: (input, options) => { + composeCalls += 1; + if (composeCalls === 2) { + throw new Error('simulated second compose failure'); + } + return composeSecurityMasterRun(input, options); + }, + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: '/virtual/out' } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('compose'); + expect((caught as Error).message).not.toContain('read-sample-closes'); + expect(readCalls).toBe(1); + expect(composeCalls).toBe(2); + expect(writes).toHaveLength(0); + expect(stdout).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('batchSize is forwarded to sample-close finds only when provided', async () => { + const withBatch = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const capturedWith: ReadSampleClosesOptions[] = []; + await runSecurityMaster( + { + mongoCollectionClient: withBatch.mongoCollectionClient, + barSpanReader: withBatch.barSpanReader, + readSampleClosesFn: async (reader, options) => { + capturedWith.push(options); + return readSampleCloses(reader, options); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), batchSize: 7 } + ); + expect(capturedWith[0]?.batchSize).toBe(7); + const priceFindsWith = withBatch.findCallDetails.filter( + c => c.collectionName === 'eodPrices' || c.collectionName === 'qmPrices' + ); + expect(priceFindsWith).toHaveLength(3); + for (const call of priceFindsWith) { + expect(call.options?.batchSize).toBe(7); + } + + const withoutBatch = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const capturedWithout: ReadSampleClosesOptions[] = []; + await runSecurityMaster( + { + mongoCollectionClient: withoutBatch.mongoCollectionClient, + barSpanReader: withoutBatch.barSpanReader, + readSampleClosesFn: async (reader, options) => { + capturedWithout.push(options); + return readSampleCloses(reader, options); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + expect(capturedWithout).toHaveLength(1); + expect('batchSize' in (capturedWithout[0] ?? {})).toBe(false); + }); + + test('programmatic pass4 rejects null and non-boolean enabled at validate-options before any Mongo read', async () => { + const badPass4Values: unknown[] = [null, 'on', { enabled: 'yes' }, { enabled: 1 }, { sampleDateCount: '10' }]; + for (const badPass4 of badPass4Values) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { + asOfDate: '2026-01-15', + outDir: createTempDir(), + pass4: badPass4 as { enabled?: boolean }, + } + ); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('validate-options'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(fakeMongo.aggregateCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + }); + + test('selected sample dates are ascending, unique, Mon-Fri, inside the overlap window, and mirrored in run-stats.json', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir('sm-pass4-dates-'); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + const dates = result.pass4.sampleDates; + expect(dates).toHaveLength(DEFAULT_SAMPLE_DATE_COUNT); + expect([...dates].sort(compareAscii)).toEqual([...dates]); + expect(new Set(dates).size).toBe(dates.length); + for (const date of dates) { + const dow = new Date(`${date}T00:00:00Z`).getUTCDay(); + expect(dow).toBeGreaterThanOrEqual(1); + expect(dow).toBeLessThanOrEqual(5); + // Overlap of fixture spans: QM starts 2018-01-02, both end 2026-01-14. + expect(date >= '2018-01-02').toBe(true); + expect(date <= '2026-01-14').toBe(true); + } + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4: { sampleDates: string[] } }; + expect(stats.pass4.sampleDates).toEqual([...dates]); + }); +}); + +describe('buildSampleDateCalendar (QA edge cases)', () => { + function twoSourceIndex(first: string, last: string): BarSpanIndex { + const index = new BarSpanIndex(); + index.merge({ source: 'eod', sourceId: 'X.US', firstBarDate: first, lastBarDate: last, barCount: 5 }); + index.merge({ source: 'qm', sourceId: 'X:US', firstBarDate: first, lastBarDate: last, barCount: 5 }); + return index; + } + + test('handles year boundaries and leap days (2000 and 2024)', () => { + expect(buildSampleDateCalendar({ index: twoSourceIndex('2023-12-28', '2024-01-02') }, '2024-01-02')).toEqual([ + '2023-12-28', + '2023-12-29', + '2024-01-01', + '2024-01-02', + ]); + expect(buildSampleDateCalendar({ index: twoSourceIndex('2024-02-28', '2024-03-01') }, '2024-03-01')).toEqual([ + '2024-02-28', + '2024-02-29', + '2024-03-01', + ]); + expect(buildSampleDateCalendar({ index: twoSourceIndex('2000-02-28', '2000-03-01') }, '2000-03-01')).toEqual([ + '2000-02-28', + '2000-02-29', + '2000-03-01', + ]); + }); + + test('matches a Date.getUTCDay weekday oracle over 2019-2026', () => { + const calendar = buildSampleDateCalendar({ index: twoSourceIndex('2019-01-01', '2026-12-31') }, '2026-12-31'); + const expected: string[] = []; + for ( + let ms = Date.UTC(2019, 0, 1); + ms <= Date.UTC(2026, 11, 31); + ms += 86_400_000 + ) { + const d = new Date(ms); + const dow = d.getUTCDay(); + if (dow >= 1 && dow <= 5) { + expected.push(d.toISOString().slice(0, 10)); + } + } + expect(calendar).toEqual(expected); + }); + + test('ignores zero-bar, inverted, and invalid-date spans when computing the window', () => { + const index = twoSourceIndex('2024-01-08', '2024-01-12'); + index.merge({ source: 'eod', sourceId: 'Z.US', firstBarDate: '2020-01-01', lastBarDate: '2030-01-01', barCount: 0 }); + index.merge({ source: 'qm', sourceId: 'Y:US', firstBarDate: '2024-02-30', lastBarDate: '2024-03-05', barCount: 3 }); + expect(buildSampleDateCalendar({ index }, '2030-01-01')).toEqual([ + '2024-01-08', + '2024-01-09', + '2024-01-10', + '2024-01-11', + '2024-01-12', + ]); + }); + + test('asOfDate before the overlap start yields an empty calendar', () => { + expect(buildSampleDateCalendar({ index: twoSourceIndex('2024-01-08', '2024-01-12') }, '2024-01-05')).toEqual([]); + }); +});