2329 lines
78 KiB
TypeScript
2329 lines
78 KiB
TypeScript
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
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,
|
|
} from '../../apps/stock/data-pipeline/src/security-master';
|
|
|
|
const cliSourcePath = fileURLToPath(
|
|
new URL(
|
|
'../../apps/stock/data-pipeline/src/security-master/run-security-master.ts',
|
|
import.meta.url
|
|
)
|
|
);
|
|
|
|
const tempDirs: string[] = [];
|
|
|
|
function createTempDir(prefix = 'sm-run-cli-'): string {
|
|
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
tempDirs.push(dir);
|
|
return dir;
|
|
}
|
|
|
|
afterEach(() => {
|
|
while (tempDirs.length > 0) {
|
|
const dir = tempDirs.pop();
|
|
if (dir) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
});
|
|
|
|
interface FakeMongoFixture {
|
|
readonly collections: Readonly<Record<string, readonly Record<string, unknown>[]>>;
|
|
readonly barSpanRowsByCollection?: Readonly<Record<string, readonly GroupedBarSpanRow[]>>;
|
|
}
|
|
|
|
function makeAsyncCursor(docs: readonly Record<string, unknown>[]) {
|
|
let closed = false;
|
|
return {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<Record<string, unknown>> {
|
|
for (const doc of docs) {
|
|
if (closed) {
|
|
break;
|
|
}
|
|
yield doc;
|
|
}
|
|
},
|
|
async close(): Promise<void> {
|
|
closed = true;
|
|
},
|
|
};
|
|
}
|
|
|
|
function extractRequestedIdsFromPipeline(pipeline: readonly Record<string, unknown>[]): Set<string> | null {
|
|
for (const stage of pipeline) {
|
|
const match = stage.$match;
|
|
if (match && typeof match === 'object') {
|
|
for (const value of Object.values(match as Record<string, unknown>)) {
|
|
if (value && typeof value === 'object' && Array.isArray((value as { $in?: unknown }).$in)) {
|
|
return new Set(((value as { $in: unknown[] }).$in).map(String));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
interface FindCallDetail {
|
|
readonly collectionName: string;
|
|
readonly filter: Record<string, unknown>;
|
|
readonly options?: Record<string, unknown>;
|
|
}
|
|
|
|
function matchesFakeFindFilter(
|
|
doc: Record<string, unknown>,
|
|
filter: Record<string, unknown>
|
|
): 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: {
|
|
readonly readOnly?: boolean;
|
|
readonly failCollection?: string;
|
|
readonly failAggregate?: boolean;
|
|
} = {}
|
|
): {
|
|
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
|
|
readonly barSpanReader: BarSpanAggregateReader;
|
|
readonly aggregateCalls: Array<{ collectionName: string; pipeline: Record<string, unknown>[] }>;
|
|
readonly findCalls: string[];
|
|
readonly findCallDetails: FindCallDetail[];
|
|
} {
|
|
const readOnly = options.readOnly ?? true;
|
|
const aggregateCalls: Array<{ collectionName: string; pipeline: Record<string, unknown>[] }> = [];
|
|
const findCalls: string[] = [];
|
|
const findCallDetails: FindCallDetail[] = [];
|
|
|
|
const target = {
|
|
isReadOnly(): boolean {
|
|
return readOnly;
|
|
},
|
|
getCollection(collectionName: string) {
|
|
const colTarget = {
|
|
find(filter: Record<string, unknown> = {}, findOptions?: Record<string, unknown>) {
|
|
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] ?? [];
|
|
const filtered =
|
|
(collectionName === 'eodPrices' || collectionName === 'qmPrices') &&
|
|
Object.keys(filter).length > 0
|
|
? docs.filter(doc => matchesFakeFindFilter(doc, filter))
|
|
: docs;
|
|
return makeAsyncCursor(filtered);
|
|
},
|
|
};
|
|
|
|
return new Proxy(colTarget, {
|
|
get(obj, prop, receiver) {
|
|
if (prop === 'find') {
|
|
return Reflect.get(obj, prop, receiver);
|
|
}
|
|
throw new Error(`Forbidden MongoDB collection method called: ${String(prop)}`);
|
|
},
|
|
});
|
|
},
|
|
aggregate<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
collectionName: string,
|
|
pipeline: Record<string, unknown>[]
|
|
): AsyncIterable<T> {
|
|
aggregateCalls.push({ collectionName, pipeline });
|
|
if (options.failAggregate) {
|
|
throw new Error(`Simulated Mongo aggregate failure on ${collectionName}`);
|
|
}
|
|
const allRows = fixture.barSpanRowsByCollection?.[collectionName] ?? [];
|
|
const requestedIds = extractRequestedIdsFromPipeline(pipeline);
|
|
const filtered =
|
|
requestedIds === null
|
|
? allRows
|
|
: allRows.filter(row => typeof row._id === 'string' && requestedIds.has(row._id));
|
|
|
|
return {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
for (const row of filtered) {
|
|
yield row as unknown as T;
|
|
}
|
|
},
|
|
};
|
|
},
|
|
};
|
|
|
|
const proxy = new Proxy(target, {
|
|
get(obj, prop, receiver) {
|
|
if (prop === 'isReadOnly' || prop === 'getCollection' || prop === 'aggregate') {
|
|
return Reflect.get(obj, prop, receiver);
|
|
}
|
|
throw new Error(`Forbidden MongoDB client method called: ${String(prop)}`);
|
|
},
|
|
});
|
|
|
|
return {
|
|
mongoCollectionClient: proxy as unknown as ReadOnlyMongoCollectionClient,
|
|
barSpanReader: proxy as unknown as BarSpanAggregateReader,
|
|
aggregateCalls,
|
|
findCalls,
|
|
findCallDetails,
|
|
};
|
|
}
|
|
|
|
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<string, unknown>[] = [];
|
|
const qmPrices: Record<string, unknown>[] = [];
|
|
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: [
|
|
{ Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' },
|
|
{ Code: 'TO', Name: 'Toronto Exchange', Country: 'Canada', Currency: 'CAD', OperatingMIC: 'XTSE' },
|
|
],
|
|
ibExchanges: [
|
|
{ exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' },
|
|
{ exchange: 'TSE', country: 'CA', currency: 'CAD', mic: 'XTSE' },
|
|
],
|
|
qmExchanges: [
|
|
{ exchange: 'NSD', country: 'US', currency: 'USD' },
|
|
{ exchange: 'TSX', country: 'CA', currency: 'CAD' },
|
|
],
|
|
ceoExchanges: [],
|
|
eodSymbols: [
|
|
{
|
|
eodSearchCode: 'AAPL.US',
|
|
Code: 'AAPL',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Cusip: '037833100',
|
|
Name: 'Apple Inc.',
|
|
Type: 'Common Stock',
|
|
delisted: false,
|
|
},
|
|
{
|
|
eodSearchCode: 'SHOP.TO',
|
|
Code: 'SHOP',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA82509L1076',
|
|
Cusip: '82509L107',
|
|
Name: 'Shopify Inc.',
|
|
Type: 'Common Stock',
|
|
delisted: false,
|
|
},
|
|
],
|
|
ibSymbols: [
|
|
{
|
|
conid: 265598,
|
|
symbol: 'AAPL',
|
|
localSymbol: 'AAPL',
|
|
primaryExchange: 'NASDAQ',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
name: 'Apple Inc.',
|
|
},
|
|
],
|
|
qmSymbols: [
|
|
{
|
|
qmSearchCode: 'AAPL:US',
|
|
symbol: 'AAPL',
|
|
exchange: 'NSD',
|
|
countryCode: 'US',
|
|
currency: 'USD',
|
|
name: 'Apple Inc.',
|
|
active: true,
|
|
},
|
|
{
|
|
// Unresolved symbol: no matching EOD/IB instrument or listing on XTSE.
|
|
qmSearchCode: 'MYSTERY:CA',
|
|
symbol: 'MYSTERY',
|
|
exchange: 'TSX',
|
|
countryCode: 'CA',
|
|
currency: 'CAD',
|
|
name: 'Mystery Corp',
|
|
active: true,
|
|
},
|
|
],
|
|
ceoSymbols: [],
|
|
eodSymbolChange: [],
|
|
eodPrices,
|
|
qmPrices,
|
|
},
|
|
barSpanRowsByCollection: {
|
|
eodPrices: [
|
|
{ _id: 'AAPL.US', firstBarDate: '2015-01-02', lastBarDate: '2026-01-14', barCount: 2770 },
|
|
{ _id: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2026-01-14', barCount: 2680 },
|
|
],
|
|
qmPrices: [
|
|
{ _id: 'AAPL:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 },
|
|
{ _id: 'MYSTERY:CA', firstBarDate: '2022-01-03', lastBarDate: '2025-12-31', barCount: 990 },
|
|
],
|
|
},
|
|
};
|
|
}
|
|
|
|
function makeFakePersistResult(): PersistSecurityMasterResult {
|
|
return {
|
|
instrumentsInserted: 2,
|
|
instrumentsUpdated: 0,
|
|
instrumentsUnchanged: 0,
|
|
instrumentsSkipped: 0,
|
|
identifierHistoryInserted: 4,
|
|
identifierHistoryUnchanged: 0,
|
|
listingsInserted: 2,
|
|
listingsUpdated: 0,
|
|
listingsUnchanged: 0,
|
|
listingsSkipped: 0,
|
|
listingSymbolHistoryInserted: 2,
|
|
listingSymbolHistoryUpdated: 0,
|
|
listingSymbolHistoryUnchanged: 0,
|
|
providerMappingsInserted: 4,
|
|
providerMappingsUpdated: 0,
|
|
providerMappingsUnchanged: 0,
|
|
providerMappingsSkipped: 0,
|
|
providerMappingsDeletedStaleFallback: 0,
|
|
overridesApplied: 0,
|
|
conflictsInserted: 0,
|
|
conflictsUnchanged: 0,
|
|
conflictsDeduplicated: 0,
|
|
pass6OutcomesApplied: 2,
|
|
pass6OutcomesSkipped: 0,
|
|
continuitiesInserted: 0,
|
|
continuitiesUpdated: 0,
|
|
continuitiesUnchanged: 0,
|
|
continuitiesSkipped: 0,
|
|
skippedByReason: {
|
|
instruments: { missing_canonical_name: 0, missing_security_type: 0 },
|
|
listings: { skipped_instrument: 0, missing_instrument: 0, unknown_mic: 0 },
|
|
providerMappings: { missing_listing: 0 },
|
|
pass6Outcomes: { missing_listing: 0 },
|
|
continuities: {
|
|
missing_from_listing: 0,
|
|
missing_to_listing: 0,
|
|
missing_both_listings: 0,
|
|
},
|
|
},
|
|
instrumentIdByIsin: new Map<string, number>(),
|
|
listingIdByKey: new Map<string, number>(),
|
|
};
|
|
}
|
|
|
|
function assertObjectKeysSortedAscii(value: unknown, path = '$'): void {
|
|
if (Array.isArray(value)) {
|
|
for (let i = 0; i < value.length; i++) {
|
|
assertObjectKeysSortedAscii(value[i], `${path}[${i}]`);
|
|
}
|
|
return;
|
|
}
|
|
if (value !== null && typeof value === 'object') {
|
|
const keys = Object.keys(value as Record<string, unknown>);
|
|
const sorted = [...keys].sort(compareAscii);
|
|
expect(keys, `Keys not ASCII-sorted at ${path}`).toEqual(sorted);
|
|
for (const key of keys) {
|
|
assertObjectKeysSortedAscii((value as Record<string, unknown>)[key], `${path}.${key}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
describe('parseRunSecurityMasterArgs', () => {
|
|
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, --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,
|
|
});
|
|
});
|
|
|
|
test('returns { help: true } for --help without requiring other flags', () => {
|
|
expect(parseRunSecurityMasterArgs(['--help'])).toEqual({ help: true });
|
|
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', () => {
|
|
expect(() => parseRunSecurityMasterArgs(['--out-dir', './out'])).toThrow(/--as-of/);
|
|
expect(() => parseRunSecurityMasterArgs(['--as-of', '2026-01-15'])).toThrow(/--out-dir/);
|
|
});
|
|
|
|
test('rejects invalid calendar dates, compact dates, and timestamps', () => {
|
|
for (const badDate of ['2026-13-40', '20260101', '2023-02-29', '2026-01-15T00:00:00Z']) {
|
|
expect(() =>
|
|
parseRunSecurityMasterArgs(['--as-of', badDate, '--out-dir', './out'])
|
|
).toThrow(/Invalid --as-of date/);
|
|
}
|
|
});
|
|
|
|
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'])
|
|
).toThrow(/Unknown argument: --unknown/);
|
|
expect(() =>
|
|
parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', 'positional'])
|
|
).toThrow(/Unknown argument: positional/);
|
|
expect(() =>
|
|
parseRunSecurityMasterArgs(['--as-of', '--out-dir', '/tmp'])
|
|
).toThrow(/Missing value for --as-of/);
|
|
expect(() =>
|
|
parseRunSecurityMasterArgs(['--as-of=2026-01-15', '--out-dir='])
|
|
).toThrow(/Missing value for --out-dir/);
|
|
expect(() =>
|
|
parseRunSecurityMasterArgs(['--as-of=', '--out-dir=/tmp'])
|
|
).toThrow(/Missing value for --as-of/);
|
|
});
|
|
});
|
|
|
|
describe('runSecurityMaster', () => {
|
|
test('happy path writes all four files matching composeSecurityMasterRun byte-for-byte', async () => {
|
|
const fixture = buildUsCaFixture();
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
const outDir = join(createTempDir(), 'nested-report');
|
|
const stdoutChunks: string[] = [];
|
|
let mongoClosed = 0;
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeStdout: text => {
|
|
stdoutChunks.push(text);
|
|
},
|
|
},
|
|
{
|
|
asOfDate: '2026-01-15',
|
|
outDir,
|
|
}
|
|
);
|
|
|
|
// Independently compute expected composeSecurityMasterRun output from the same fixture.
|
|
const refMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
const refReader = createReadOnlyMongoSourceSymbolReader(refMongo.mongoCollectionClient);
|
|
const exchangeRecords: SourceExchangeRecord[] = [];
|
|
for (const source of EXCHANGE_SOURCES) {
|
|
const cursor = await refReader.find<Record<string, unknown>>(
|
|
SOURCE_EXCHANGE_COLLECTIONS[source],
|
|
{}
|
|
);
|
|
for await (const doc of cursor) {
|
|
exchangeRecords.push(normalizeRawExchangeDoc(source, doc));
|
|
}
|
|
}
|
|
const expectedExchanges = classifySourceExchanges(exchangeRecords, {
|
|
knownExchanges: ISO_EXCHANGE_SEEDS,
|
|
});
|
|
const expectedSources = await readSecurityMasterSources(refReader, {
|
|
exchangeLookup: createExchangeSourceLookup(expectedExchanges.mapped),
|
|
});
|
|
const expectedBarSpans = await computeBarSpans(refMongo.barSpanReader, {
|
|
sources: ['eod', 'qm'],
|
|
sourceIdsBySource: {
|
|
eod: ['AAPL.US', 'SHOP.TO'],
|
|
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' }
|
|
);
|
|
|
|
const matchReportContent = readFileSync(
|
|
join(outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport),
|
|
'utf8'
|
|
);
|
|
const conflictsCsvContent = readFileSync(
|
|
join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv),
|
|
'utf8'
|
|
);
|
|
const overrideTemplateContent = readFileSync(
|
|
join(outDir, SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql),
|
|
'utf8'
|
|
);
|
|
const runStatsContent = readFileSync(
|
|
join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson),
|
|
'utf8'
|
|
);
|
|
|
|
expect(matchReportContent).toBe(expectedComposed.reportMarkdown);
|
|
expect(conflictsCsvContent).toBe(expectedComposed.conflictsCsv);
|
|
expect(overrideTemplateContent).toBe(expectedComposed.overrideTemplateSql);
|
|
|
|
expect(runStatsContent.endsWith('\n')).toBe(true);
|
|
const parsedStats = JSON.parse(runStatsContent) as Record<string, unknown>;
|
|
assertObjectKeysSortedAscii(parsedStats);
|
|
expect(parsedStats.asOfDate).toBe('2026-01-15');
|
|
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<string, number> | 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);
|
|
|
|
expect(mongoClosed).toBe(1);
|
|
const summaryText = stdoutChunks.join('');
|
|
expect(summaryText).toContain('Instruments: 2');
|
|
expect(summaryText).toContain('Persisted: no (dry-run)');
|
|
expect(summaryText).toContain('match-report.md');
|
|
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 () => {
|
|
const fixture = buildUsCaFixture();
|
|
const outDir1 = createTempDir('sm-replay-1-');
|
|
const outDir2 = createTempDir('sm-replay-2-');
|
|
|
|
const mongo1 = createStrictReadOnlyFakeMongo(fixture);
|
|
const mongo2 = createStrictReadOnlyFakeMongo(fixture);
|
|
|
|
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 }
|
|
);
|
|
|
|
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 runs`).toBe(content1);
|
|
}
|
|
});
|
|
|
|
test('dry run never invokes PostgreSQL factory or persist function', async () => {
|
|
const fixture = buildUsCaFixture();
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
const outDir = createTempDir();
|
|
let pgFactoryCalls = 0;
|
|
let queryCalls = 0;
|
|
let persistCalls = 0;
|
|
let mongoClosed = 0;
|
|
|
|
const fakeQueryable: SecurityMasterQueryable = {
|
|
async query() {
|
|
queryCalls += 1;
|
|
return { rows: [] };
|
|
},
|
|
};
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
createPostgresClient: () => {
|
|
pgFactoryCalls += 1;
|
|
return { queryable: fakeQueryable, close: () => {} };
|
|
},
|
|
persistFn: async () => {
|
|
persistCalls += 1;
|
|
return makeFakePersistResult();
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir, persist: false }
|
|
);
|
|
|
|
expect(result.persist).toBe(false);
|
|
expect(result.persistResult).toBeNull();
|
|
expect(pgFactoryCalls).toBe(0);
|
|
expect(queryCalls).toBe(0);
|
|
expect(persistCalls).toBe(0);
|
|
expect(mongoClosed).toBe(1);
|
|
});
|
|
|
|
test('--persist invokes env-safety guard before PostgreSQL factory and calls persistFn once', async () => {
|
|
const fixture = buildUsCaFixture();
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
const outDir = createTempDir();
|
|
const callOrder: string[] = [];
|
|
const capturedInputs: PersistSecurityMasterInput[] = [];
|
|
const stdoutChunks: string[] = [];
|
|
|
|
const fakeQueryable: SecurityMasterQueryable = {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
};
|
|
let receivedQueryable: SecurityMasterQueryable | null = null;
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
callOrder.push('closeMongo');
|
|
},
|
|
assertSafety: () => {
|
|
callOrder.push('assertSafety');
|
|
},
|
|
createPostgresClient: (): SecurityMasterPostgresHandle => {
|
|
callOrder.push('createPostgresClient');
|
|
return {
|
|
queryable: fakeQueryable,
|
|
close: () => {
|
|
callOrder.push('closePostgres');
|
|
},
|
|
};
|
|
},
|
|
persistFn: async (queryable, input) => {
|
|
callOrder.push('persistFn');
|
|
receivedQueryable = queryable;
|
|
capturedInputs.push(input);
|
|
return makeFakePersistResult();
|
|
},
|
|
writeStdout: text => {
|
|
stdoutChunks.push(text);
|
|
},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir, persist: true }
|
|
);
|
|
|
|
expect(callOrder).toEqual([
|
|
'assertSafety',
|
|
'createPostgresClient',
|
|
'persistFn',
|
|
'closePostgres',
|
|
'closeMongo',
|
|
]);
|
|
expect(capturedInputs).toHaveLength(1);
|
|
expect(capturedInputs[0]).toEqual(result.composed.persistInput);
|
|
expect(receivedQueryable === fakeQueryable).toBe(true);
|
|
expect(result.persistResult).not.toBeNull();
|
|
expect(stdoutChunks.join('')).toContain('Persisted: yes');
|
|
});
|
|
|
|
test('env-safety guard throwing rejects with step name, never opens PostgreSQL, and closes Mongo', async () => {
|
|
const fixture = buildUsCaFixture();
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
const outDir = createTempDir();
|
|
let pgFactoryCalls = 0;
|
|
let mongoClosed = 0;
|
|
const stdoutChunks: string[] = [];
|
|
const safetyErr = new Error('Safety guard: blocked QA PostgreSQL');
|
|
|
|
let caught: unknown = null;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => {
|
|
throw safetyErr;
|
|
},
|
|
createPostgresClient: () => {
|
|
pgFactoryCalls += 1;
|
|
throw new Error('should not be called');
|
|
},
|
|
writeStdout: text => {
|
|
stdoutChunks.push(text);
|
|
},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir, persist: true }
|
|
);
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(Error);
|
|
expect((caught as Error).message).toContain('env-safety');
|
|
expect((caught as Error).cause).toBe(safetyErr);
|
|
expect(pgFactoryCalls).toBe(0);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdoutChunks).toHaveLength(0);
|
|
});
|
|
|
|
test('assertSecurityMasterPersistSafety rejects QA profile and non-dev PostgreSQL targets before opening PostgreSQL', async () => {
|
|
const buildConfig = (overrides: {
|
|
environment: 'development' | 'qa';
|
|
host?: string;
|
|
port: number;
|
|
database: string;
|
|
}) =>
|
|
stockAppSchema.parse({
|
|
name: 'stock-bot',
|
|
version: '1.0.0',
|
|
environment: overrides.environment,
|
|
service: {
|
|
name: 'data-pipeline',
|
|
port: 2002,
|
|
},
|
|
log: {
|
|
level: 'info',
|
|
},
|
|
database: {
|
|
postgres: {
|
|
enabled: true,
|
|
host: overrides.host ?? 'localhost',
|
|
port: overrides.port,
|
|
database: overrides.database,
|
|
user: 'trading_user',
|
|
password: 'dev_password',
|
|
},
|
|
mongodb: {
|
|
enabled: true,
|
|
uri:
|
|
overrides.environment === 'qa'
|
|
? 'mongodb://localhost:27017/stock'
|
|
: 'mongodb://localhost:27018/stock_dev',
|
|
readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock',
|
|
readOnly: true,
|
|
database: overrides.environment === 'qa' ? 'stock' : 'stock_dev',
|
|
},
|
|
questdb: { enabled: false },
|
|
dragonfly: { enabled: false },
|
|
},
|
|
providers: {},
|
|
features: {},
|
|
});
|
|
|
|
// 1. QA profile targeting QA PostgreSQL (localhost:5432/trading_bot) must be rejected before PG factory runs
|
|
const qaConfig = buildConfig({
|
|
environment: 'qa',
|
|
port: 5432,
|
|
database: 'trading_bot',
|
|
});
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
let pgFactoryCalls = 0;
|
|
let mongoClosed = 0;
|
|
const stdoutChunks: string[] = [];
|
|
|
|
let caught: unknown = null;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => assertSecurityMasterPersistSafety(qaConfig, {}),
|
|
createPostgresClient: () => {
|
|
pgFactoryCalls += 1;
|
|
throw new Error('PostgreSQL factory must not be called for QA profile');
|
|
},
|
|
writeStdout: text => stdoutChunks.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir(), persist: true }
|
|
);
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(Error);
|
|
expect((caught as Error).message).toContain('env-safety');
|
|
expect((caught as Error).message).toContain('NODE_ENV=development');
|
|
expect(pgFactoryCalls).toBe(0);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdoutChunks).toHaveLength(0);
|
|
|
|
// 2. Development profile targeting QA PostgreSQL (even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true) is rejected
|
|
const devQaPgConfig = buildConfig({
|
|
environment: 'development',
|
|
port: 5432,
|
|
database: 'trading_bot',
|
|
});
|
|
expect(() =>
|
|
assertSecurityMasterPersistSafety(devQaPgConfig, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' })
|
|
).toThrow(/Safety guard: development environment cannot target QA PostgreSQL/);
|
|
|
|
// 3. Development profile on port 5433 with non-dev database name is rejected
|
|
const devNonDevDbConfig = buildConfig({
|
|
environment: 'development',
|
|
port: 5433,
|
|
database: 'trading_bot',
|
|
});
|
|
expect(() => assertSecurityMasterPersistSafety(devNonDevDbConfig, {})).toThrow(
|
|
/cannot target QA PostgreSQL/
|
|
);
|
|
|
|
// 4. Development profile targeting isolated dev PostgreSQL (localhost:5433/trading_bot_dev) passes
|
|
const devIsolatedConfig = buildConfig({
|
|
environment: 'development',
|
|
port: 5433,
|
|
database: 'trading_bot_dev',
|
|
});
|
|
expect(() => assertSecurityMasterPersistSafety(devIsolatedConfig, {})).not.toThrow();
|
|
});
|
|
|
|
test('closeMongo failure after successful writes rejects with close-mongo and leaves stdout empty', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const outDir = createTempDir();
|
|
const stdoutChunks: string[] = [];
|
|
const closeErr = new Error('Mongo disconnect timed out');
|
|
|
|
let caught: unknown = null;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
throw closeErr;
|
|
},
|
|
writeStdout: text => {
|
|
stdoutChunks.push(text);
|
|
},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir }
|
|
);
|
|
} catch (error) {
|
|
caught = error;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(Error);
|
|
expect((caught as Error).message).toContain('close-mongo');
|
|
expect((caught as Error).cause).toBe(closeErr);
|
|
expect(stdoutChunks).toHaveLength(0);
|
|
});
|
|
|
|
test('real assertEnvironmentSafety rejects development config targeting QA PostgreSQL 5432/trading_bot', () => {
|
|
const devQaPgConfig = stockAppSchema.parse({
|
|
name: 'stock-bot',
|
|
version: '1.0.0',
|
|
environment: 'development',
|
|
service: {
|
|
name: 'data-pipeline',
|
|
port: 2002,
|
|
},
|
|
log: {
|
|
level: 'info',
|
|
},
|
|
database: {
|
|
postgres: {
|
|
enabled: true,
|
|
host: 'localhost',
|
|
port: 5432,
|
|
database: 'trading_bot',
|
|
user: 'trading_user',
|
|
password: 'dev_password',
|
|
},
|
|
mongodb: {
|
|
enabled: true,
|
|
uri: 'mongodb://localhost:27018/stock_dev',
|
|
readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock',
|
|
readOnly: true,
|
|
database: 'stock_dev',
|
|
},
|
|
questdb: { enabled: false },
|
|
dragonfly: { enabled: false },
|
|
},
|
|
providers: {},
|
|
features: {},
|
|
});
|
|
|
|
expect(() => assertEnvironmentSafety(devQaPgConfig, 'dataPipeline', {})).toThrow(
|
|
/Safety guard: development environment cannot target QA PostgreSQL/
|
|
);
|
|
});
|
|
|
|
test('reader, bar-span, file-write, and persist failures wrap step name, suppress summary, and close clients', async () => {
|
|
const fixture = buildUsCaFixture();
|
|
|
|
// 1. Reader failure (source symbol collection)
|
|
{
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture, { failCollection: 'eodSymbols' });
|
|
let mongoClosed = 0;
|
|
const stdout: string[] = [];
|
|
let caught: unknown;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir() }
|
|
);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect((caught as Error).message).toContain('read-sources');
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdout).toHaveLength(0);
|
|
}
|
|
|
|
// 2. Bar-span failure
|
|
{
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture, { failAggregate: true });
|
|
let mongoClosed = 0;
|
|
const stdout: string[] = [];
|
|
let caught: unknown;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir() }
|
|
);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect((caught as Error).message).toContain('compute-bar-spans');
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdout).toHaveLength(0);
|
|
}
|
|
|
|
// 3. File-write failure + secondary closeMongo error does not mask primary error
|
|
{
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
let mongoClosed = 0;
|
|
const stdout: string[] = [];
|
|
const writeErr = new Error('ENOSPC: disk full');
|
|
let caught: unknown;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
throw new Error('secondary disconnect error');
|
|
},
|
|
writeFile: () => {
|
|
throw writeErr;
|
|
},
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir() }
|
|
);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect((caught as Error).message).toContain('write-files');
|
|
expect((caught as Error).cause).toBe(writeErr);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdout).toHaveLength(0);
|
|
}
|
|
|
|
// 4. Persist failure closes both PostgreSQL handle and MongoDB client
|
|
{
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(fixture);
|
|
let mongoClosed = 0;
|
|
let pgClosed = 0;
|
|
const stdout: string[] = [];
|
|
const persistErr = new Error('deadlock detected');
|
|
let caught: unknown;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => {},
|
|
createPostgresClient: () => ({
|
|
queryable: {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
},
|
|
close: () => {
|
|
pgClosed += 1;
|
|
},
|
|
}),
|
|
persistFn: async () => {
|
|
throw persistErr;
|
|
},
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir(), persist: true }
|
|
);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
expect((caught as Error).message).toContain('persist');
|
|
expect((caught as Error).cause).toBe(persistErr);
|
|
expect(pgClosed).toBe(1);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdout).toHaveLength(0);
|
|
}
|
|
});
|
|
|
|
test('rejects non-read-only Mongo client and static source contains zero write/index/drop tokens', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { readOnly: false });
|
|
let mongoClosed = 0;
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir() }
|
|
);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect((caught as Error).message).toContain('read-exchanges');
|
|
expect((caught as Error).message).toContain('read-only');
|
|
expect(mongoClosed).toBe(1);
|
|
|
|
const sourceText = readFileSync(cliSourcePath, 'utf8');
|
|
const forbiddenPattern = /\b(insert|update|delete|drop|createIndex|bulkWrite)\b/i;
|
|
expect(forbiddenPattern.test(sourceText)).toBe(false);
|
|
expect(/(insert|update|delete|drop|createIndex|bulkWrite)/i.test(sourceText)).toBe(false);
|
|
});
|
|
|
|
test('empty sources succeed, write all four files with zero stats, and skip bar-span aggregates', async () => {
|
|
const emptyFixture: FakeMongoFixture = { collections: {} };
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(emptyFixture);
|
|
const outDir = createTempDir();
|
|
let mongoClosed = 0;
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir }
|
|
);
|
|
|
|
expect(fakeMongo.aggregateCalls).toHaveLength(0);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(result.composed.stageA.instruments).toHaveLength(0);
|
|
expect(result.composed.stageB.listings).toHaveLength(0);
|
|
expect(result.composed.report.conflicts).toHaveLength(0);
|
|
|
|
for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) {
|
|
const content = readFileSync(join(outDir, filename), 'utf8');
|
|
expect(typeof content).toBe('string');
|
|
}
|
|
|
|
const parsedStats = JSON.parse(
|
|
readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8')
|
|
) as {
|
|
barSpans: { totalRowsRead: number; totalSpans: number };
|
|
reportSummary: { instruments: number; listings: number; conflicts: number };
|
|
};
|
|
expect(parsedStats.barSpans.totalRowsRead).toBe(0);
|
|
expect(parsedStats.barSpans.totalSpans).toBe(0);
|
|
expect(parsedStats.reportSummary.instruments).toBe(0);
|
|
expect(parsedStats.reportSummary.listings).toBe(0);
|
|
expect(parsedStats.reportSummary.conflicts).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('runSecurityMaster (QA edge cases)', () => {
|
|
async function captureRejection(promise: Promise<unknown>): Promise<Error> {
|
|
try {
|
|
await promise;
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(Error);
|
|
return error as Error;
|
|
}
|
|
throw new Error('expected promise to reject');
|
|
}
|
|
|
|
function buildPgConfig(overrides: {
|
|
environment?: 'development' | 'qa';
|
|
enabled?: boolean;
|
|
port: number;
|
|
database: string;
|
|
}) {
|
|
const environment = overrides.environment ?? 'development';
|
|
return stockAppSchema.parse({
|
|
name: 'stock-bot',
|
|
version: '1.0.0',
|
|
environment,
|
|
service: { name: 'data-pipeline', port: 2002 },
|
|
log: { level: 'info' },
|
|
database: {
|
|
postgres: {
|
|
enabled: overrides.enabled ?? true,
|
|
host: 'localhost',
|
|
port: overrides.port,
|
|
database: overrides.database,
|
|
user: 'trading_user',
|
|
password: 'dev_password',
|
|
},
|
|
mongodb: {
|
|
enabled: true,
|
|
uri: 'mongodb://localhost:27018/stock_dev',
|
|
readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock',
|
|
readOnly: true,
|
|
database: 'stock_dev',
|
|
},
|
|
questdb: { enabled: false },
|
|
dragonfly: { enabled: false },
|
|
},
|
|
providers: {},
|
|
features: {},
|
|
});
|
|
}
|
|
|
|
test('failing env-safety guard runs before any MongoDB read', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
let mongoClosed = 0;
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => {
|
|
throw new Error('blocked');
|
|
},
|
|
createPostgresClient: () => {
|
|
throw new Error('must not be called');
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir(), persist: true }
|
|
)
|
|
);
|
|
|
|
expect(error.message).toContain('env-safety');
|
|
expect(fakeMongo.findCalls).toHaveLength(0);
|
|
expect(fakeMongo.aggregateCalls).toHaveLength(0);
|
|
expect(mongoClosed).toBe(1);
|
|
});
|
|
|
|
test('--persist without guard or PostgreSQL factory rejects at env-safety with no reads or writes', async () => {
|
|
for (const missing of ['assertSafety', 'createPostgresClient'] as const) {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const writes: string[] = [];
|
|
let mongoClosed = 0;
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
...(missing === 'assertSafety'
|
|
? {
|
|
createPostgresClient: () => {
|
|
throw new Error('must not be called');
|
|
},
|
|
}
|
|
: { assertSafety: () => {} }),
|
|
writeFile: filePath => {
|
|
writes.push(filePath);
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir(), persist: true }
|
|
)
|
|
);
|
|
|
|
expect(error.message).toContain('env-safety');
|
|
expect(error.message).toContain(missing);
|
|
expect(fakeMongo.findCalls).toHaveLength(0);
|
|
expect(writes).toHaveLength(0);
|
|
expect(mongoClosed).toBe(1);
|
|
}
|
|
});
|
|
|
|
test('invalid asOfDate or empty outDir passed programmatically rejects at validate-options before Mongo', async () => {
|
|
const cases = [
|
|
{ asOfDate: '2023-02-29', outDir: '/tmp/x' },
|
|
{ asOfDate: '20260115', outDir: '/tmp/x' },
|
|
{ asOfDate: '2026-01-15', outDir: ' ' },
|
|
];
|
|
for (const options of cases) {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
let mongoClosed = 0;
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
options
|
|
)
|
|
);
|
|
expect(error.message).toContain('validate-options');
|
|
expect(fakeMongo.findCalls).toHaveLength(0);
|
|
expect(mongoClosed).toBe(1);
|
|
}
|
|
});
|
|
|
|
test('exchange collection read failure rejects at read-exchanges, writes nothing, closes Mongo', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), {
|
|
failCollection: 'ibExchanges',
|
|
});
|
|
const writes: string[] = [];
|
|
const stdout: string[] = [];
|
|
let mongoClosed = 0;
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
writeFile: filePath => {
|
|
writes.push(filePath);
|
|
},
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir() }
|
|
)
|
|
);
|
|
|
|
expect(error.message).toContain('read-exchanges');
|
|
expect((error.cause as Error).message).toContain('ibExchanges');
|
|
expect(writes).toHaveLength(0);
|
|
expect(stdout).toHaveLength(0);
|
|
expect(mongoClosed).toBe(1);
|
|
});
|
|
|
|
test('write failure on a later file never opens PostgreSQL under --persist', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const writes: string[] = [];
|
|
let pgFactoryCalls = 0;
|
|
let mongoClosed = 0;
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => {},
|
|
createPostgresClient: () => {
|
|
pgFactoryCalls += 1;
|
|
throw new Error('must not be called');
|
|
},
|
|
writeFile: filePath => {
|
|
writes.push(filePath);
|
|
if (writes.length === 3) {
|
|
throw new Error('EACCES');
|
|
}
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: '/virtual/out', persist: true }
|
|
)
|
|
);
|
|
|
|
expect(error.message).toContain('write-files');
|
|
expect(writes).toEqual([
|
|
join('/virtual/out', 'match-report.md'),
|
|
join('/virtual/out', 'conflicts.csv'),
|
|
join('/virtual/out', 'override-template.sql'),
|
|
]);
|
|
expect(pgFactoryCalls).toBe(0);
|
|
expect(mongoClosed).toBe(1);
|
|
});
|
|
|
|
test('PostgreSQL factory failure rejects at persist after artifacts exist and closes Mongo', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const outDir = createTempDir();
|
|
const stdout: string[] = [];
|
|
let mongoClosed = 0;
|
|
let persistCalls = 0;
|
|
const connectErr = new Error('ECONNREFUSED 127.0.0.1:5433');
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => {},
|
|
createPostgresClient: async () => {
|
|
throw connectErr;
|
|
},
|
|
persistFn: async () => {
|
|
persistCalls += 1;
|
|
return makeFakePersistResult();
|
|
},
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir, persist: true }
|
|
)
|
|
);
|
|
|
|
expect(error.message).toContain('"persist"');
|
|
expect(error.cause).toBe(connectErr);
|
|
expect(persistCalls).toBe(0);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdout).toHaveLength(0);
|
|
for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) {
|
|
expect(readFileSync(join(outDir, filename), 'utf8').length).toBeGreaterThan(0);
|
|
}
|
|
});
|
|
|
|
test('PostgreSQL close failure after successful persist rejects and suppresses the summary', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const stdout: string[] = [];
|
|
let mongoClosed = 0;
|
|
const closeErr = new Error('pool end failed');
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
mongoClosed += 1;
|
|
},
|
|
assertSafety: () => {},
|
|
createPostgresClient: () => ({
|
|
queryable: {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
},
|
|
close: () => {
|
|
throw closeErr;
|
|
},
|
|
}),
|
|
persistFn: async () => makeFakePersistResult(),
|
|
writeStdout: text => stdout.push(text),
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir(), persist: true }
|
|
)
|
|
);
|
|
|
|
expect(error.message).toContain('"persist"');
|
|
expect(error.cause).toBe(closeErr);
|
|
expect(mongoClosed).toBe(1);
|
|
expect(stdout).toHaveLength(0);
|
|
});
|
|
|
|
test('persist failure is not masked by a secondary PostgreSQL close failure', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const persistErr = new Error('unique violation');
|
|
let pgClosed = 0;
|
|
|
|
const error = await captureRejection(
|
|
runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
assertSafety: () => {},
|
|
createPostgresClient: () => ({
|
|
queryable: {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
},
|
|
close: () => {
|
|
pgClosed += 1;
|
|
throw new Error('secondary close error');
|
|
},
|
|
}),
|
|
persistFn: async () => {
|
|
throw persistErr;
|
|
},
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir(), persist: true }
|
|
)
|
|
);
|
|
|
|
expect(error.cause).toBe(persistErr);
|
|
expect(pgClosed).toBe(1);
|
|
});
|
|
|
|
test('bar spans are targeted to sorted in-scope EOD and QM ids and stats reconcile', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const outDir = createTempDir();
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
writeStdout: () => {},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir }
|
|
);
|
|
|
|
const requested = new Map(
|
|
fakeMongo.aggregateCalls.map(call => [
|
|
call.collectionName,
|
|
[...(extractRequestedIdsFromPipeline(call.pipeline) ?? new Set<string>(['<untargeted>']))],
|
|
])
|
|
);
|
|
expect([...requested.keys()].sort()).toEqual(['eodPrices', 'qmPrices']);
|
|
expect(requested.get('eodPrices')).toEqual(['AAPL.US', 'SHOP.TO']);
|
|
expect(requested.get('qmPrices')).toEqual(['AAPL:US', 'MYSTERY:CA']);
|
|
|
|
const stats = JSON.parse(
|
|
readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8')
|
|
) as {
|
|
exchanges: {
|
|
countsByCollection: Record<string, number>;
|
|
mapped: number;
|
|
unresolved: number;
|
|
total: number;
|
|
};
|
|
barSpans: { totalSpans: number; totalRowsRead: number };
|
|
reportSummary: { instruments: number; listings: number; conflicts: number };
|
|
};
|
|
expect(stats.exchanges.countsByCollection).toEqual({ ceo: 0, eod: 2, ib: 2, qm: 2 });
|
|
expect(stats.exchanges.total).toBe(stats.exchanges.mapped + stats.exchanges.unresolved);
|
|
expect(stats.barSpans.totalSpans).toBe(4);
|
|
expect(stats.reportSummary.instruments).toBe(result.composed.stageA.instruments.length);
|
|
expect(stats.reportSummary.listings).toBe(result.composed.stageB.listings.length);
|
|
expect(stats.reportSummary.conflicts).toBe(result.composed.report.conflicts.length);
|
|
expect(result.runStatsJson).toBe(
|
|
readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8')
|
|
);
|
|
});
|
|
|
|
test('summary is written exactly once and only after Mongo closes', async () => {
|
|
const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture());
|
|
const events: string[] = [];
|
|
|
|
const result = await runSecurityMaster(
|
|
{
|
|
mongoCollectionClient: fakeMongo.mongoCollectionClient,
|
|
barSpanReader: fakeMongo.barSpanReader,
|
|
closeMongo: () => {
|
|
events.push('closeMongo');
|
|
},
|
|
writeStdout: text => {
|
|
events.push(`stdout:${text}`);
|
|
},
|
|
},
|
|
{ asOfDate: '2026-01-15', outDir: createTempDir() }
|
|
);
|
|
|
|
expect(events).toEqual(['closeMongo', `stdout:${result.summary}`]);
|
|
});
|
|
|
|
test('assertSecurityMasterPersistSafety accepts dev safety DB and rejects disabled or non-dev targets', () => {
|
|
expect(() =>
|
|
assertSecurityMasterPersistSafety(
|
|
buildPgConfig({ port: 5433, database: 'stock_bot_safety_qa' }),
|
|
{}
|
|
)
|
|
).not.toThrow();
|
|
expect(() =>
|
|
assertSecurityMasterPersistSafety(buildPgConfig({ port: 5433, database: 'analytics' }), {})
|
|
).toThrow(/isolated dev PostgreSQL database/);
|
|
expect(() =>
|
|
assertSecurityMasterPersistSafety(
|
|
buildPgConfig({ enabled: false, port: 5433, database: 'trading_bot_dev' }),
|
|
{}
|
|
)
|
|
).toThrow(/PostgreSQL is disabled/);
|
|
expect(() =>
|
|
assertSecurityMasterPersistSafety(
|
|
buildPgConfig({ environment: 'qa', port: 5433, database: 'trading_bot_dev' }),
|
|
{}
|
|
)
|
|
).toThrow(/qa environment/);
|
|
});
|
|
});
|
|
|
|
describe('run-security-master CLI process', () => {
|
|
function runCliProcess(args: readonly string[]) {
|
|
const proc = Bun.spawnSync([process.execPath, 'run', cliSourcePath, ...args], {
|
|
stdout: 'pipe',
|
|
stderr: 'pipe',
|
|
env: { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? '' },
|
|
});
|
|
return {
|
|
exitCode: proc.exitCode,
|
|
stdout: proc.stdout.toString(),
|
|
stderr: proc.stderr.toString(),
|
|
};
|
|
}
|
|
|
|
test('--help exits 0 and prints usage without connecting to MongoDB', () => {
|
|
const result = runCliProcess(['--help']);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.stdout).toContain(RUN_SECURITY_MASTER_USAGE);
|
|
});
|
|
|
|
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'],
|
|
]) {
|
|
const result = runCliProcess(args);
|
|
expect(result.exitCode).toBe(1);
|
|
expect(result.stderr.startsWith('Error: ')).toBe(true);
|
|
expect(result.stdout).not.toContain('Security master run complete');
|
|
}
|
|
});
|
|
});
|
|
|
|
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);
|
|
}
|
|
});
|
|
});
|