From 73b34f4c49b33af214d051befd58e47de76f1222 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 20:46:41 -0500 Subject: [PATCH] =?UTF-8?q?T-104:=20M1.1=20Pass=204a=20=E2=80=94=20data-pi?= =?UTF-8?q?peline:=20read-only=2025-date=20sample-close=20+=20USD/CAD=20re?= =?UTF-8?q?ader=20(`{=20date:=20{=20$in:=20sampleDates=20}=20}`=20over=20`?= =?UTF-8?q?eodPrices`=20/=20`qmPrices`=20/=20`CAD.FOREX`)=20with=20tests?= =?UTF-8?q?=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',