T-104: M1.1 Pass 4a — data-pipeline: read-only 25-date sample-close + USD/CAD reader ({ date: { $in: sampleDates } } over eodPrices / qmPrices / CAD.FOREX) with tests and local benchmark
This commit is contained in:
parent
cf511f05c0
commit
73b34f4c49
3 changed files with 129 additions and 9 deletions
|
|
@ -67,7 +67,7 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@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:
|
||||
|
||||
|
|
|
|||
|
|
@ -226,9 +226,11 @@ async function streamSampleCloseFind(
|
|||
onDoc: (doc: unknown) => void
|
||||
): Promise<void> {
|
||||
assertReadOnlyReader(reader);
|
||||
let cursor: ReadOnlySourceSymbolCursor<Record<string, unknown>> | null = null;
|
||||
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
|
||||
null;
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
let isInvalidCursorError = false;
|
||||
|
||||
try {
|
||||
const rawCursor = await reader.find<Record<string, unknown>>(
|
||||
|
|
@ -236,22 +238,31 @@ async function streamSampleCloseFind(
|
|||
filter,
|
||||
findOptions
|
||||
);
|
||||
if (
|
||||
rawCursor !== null &&
|
||||
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
|
||||
) {
|
||||
closableHandle = rawCursor as Pick<
|
||||
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
|
||||
'close'
|
||||
>;
|
||||
}
|
||||
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(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<Record<string, unknown>>;
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
if (collectionName === 'qmPrices') {
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
yield {
|
||||
qmSearchCode: 'AAPL',
|
||||
date: '2024-01-02',
|
||||
unadjustedclose: 185.64,
|
||||
} as unknown as T;
|
||||
throw iterationCause;
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
iterationCloseCalls += 1;
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
// empty
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
// 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<T extends Record<string, unknown> = Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
// empty
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
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<void> {
|
||||
invalidHandleClosed += 1;
|
||||
},
|
||||
}) as unknown as AsyncIterable<Record<string, unknown>>,
|
||||
};
|
||||
|
||||
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',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue