stock-bot/apps/stock/data-pipeline/test/sample-closes.test.ts

860 lines
30 KiB
TypeScript

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<string, unknown> | 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<string, unknown> | undefined
): boolean {
if (filter === undefined) {
return true;
}
if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
return false;
}
const record = doc as Record<string, unknown>;
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<string, 0 | 1> | undefined
): Record<string, unknown> {
if (projection === undefined || doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
return doc as Record<string, unknown>;
}
const record = doc as Record<string, unknown>;
const projected: Record<string, unknown> = {};
for (const [key, include] of Object.entries(projection)) {
if (include === 1 && key in record) {
projected[key] = record[key];
}
}
return projected;
}
function createFakeReader(
docsByCollection: Record<string, readonly unknown[]>,
options: FakeReaderOptions = {}
): FakeReaderHandle {
const calls: RecordedFindCall[] = [];
let closed = 0;
const reader: ReadOnlySourceSymbolReader = {
isReadOnly(): boolean {
return options.readOnly ?? true;
},
find<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
filter?: Record<string, unknown>,
findOptions?: SourceSymbolFindOptions
): ReadOnlySourceSymbolCursor<T> {
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<T> {
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<void> {
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<Record<string, unknown>>,
};
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('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',
'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<string, unknown>[] = [];
const qmDocs: Record<string, unknown>[] = [];
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);
});
});