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); }); });