import { describe, expect, test } from 'bun:test'; import { canonicalizeJsonValue, DEFAULT_VALID_FROM, formatListingNaturalKey, MAX_PERSIST_CHUNK_SIZE, persistSecurityMaster, PROVIDER_MAPPING_CONFIDENCE, SECURITY_MASTER_PERSIST_LOCK_NAMESPACE, stableJsonStringify, type DelistingChainResult, type PersistSecurityMasterInput, type SecurityMasterQueryable, type SecurityMasterQueryResult, type SecurityType, type StageAMatchResult, type StageBMatchResult, } from '../../apps/stock/data-pipeline/src/security-master'; interface RecordedQuery { text: string; values: readonly unknown[] | undefined; } function emptyStageA(): StageAMatchResult { return { instruments: [], unresolved: [], conflicts: [], stats: { totalInputRecords: 0, totalInstruments: 0, bySource: { ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, }, }, }; } function emptyStageB(): StageBMatchResult { return { listings: [], providerMappings: [], unresolved: [], conflicts: [], stats: { totalListings: 0, totalProviderMappings: 0, listingsWithIbConid: 0, excludedFunds: 0, bySource: { eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, }, }, }; } function createMockClient( handler?: ( text: string, values: readonly unknown[] | undefined, index: number ) => SecurityMasterQueryResult | Promise ): { client: SecurityMasterQueryable; queries: RecordedQuery[] } { const queries: RecordedQuery[] = []; let nextInstrumentId = 100; let nextListingId = 1000; const client: SecurityMasterQueryable = { release: () => undefined, async query>( text: string, values?: readonly unknown[] ): Promise> { const index = queries.length; queries.push({ text, values }); if (handler) { return (await handler(text, values, index)) as SecurityMasterQueryResult; } if (text.startsWith('SELECT mic FROM exchange')) { return { rows: [{ mic: 'XNAS' }, { mic: 'XNYS' }, { mic: 'XTSE' }, { mic: 'OTCM' }], } as unknown as SecurityMasterQueryResult; } if (text.startsWith('INSERT INTO instrument (')) { const isins = (values?.[0] as string[]) ?? []; return { rows: isins.map(isin => ({ instrument_id: nextInstrumentId++, primary_isin: isin, })), } as unknown as SecurityMasterQueryResult; } if (text.startsWith('INSERT INTO instrument_identifier_history')) { const ids = (values?.[0] as number[]) ?? []; return { rows: ids.map(() => ({ inserted: 1 })), } as unknown as SecurityMasterQueryResult; } if (text.startsWith('INSERT INTO listing (')) { const instrumentIds = (values?.[0] as number[]) ?? []; const mics = (values?.[1] as string[]) ?? []; const roots = (values?.[2] as string[]) ?? []; const suffixes = (values?.[3] as string[]) ?? []; const currencies = (values?.[4] as string[]) ?? []; return { rows: instrumentIds.map((instrumentId, i) => ({ listing_id: nextListingId++, instrument_id: instrumentId, mic: mics[i], ticker_root: roots[i], class_suffix: suffixes[i], currency: currencies[i], })), } as unknown as SecurityMasterQueryResult; } if (text.includes('INTO listing_symbol_history')) { const firstCol = (values?.[0] as unknown[]) ?? []; return { rows: [{ inserted_count: firstCol.length, updated_count: 0 }], } as unknown as SecurityMasterQueryResult; } if (text.startsWith('INSERT INTO provider_mapping')) { const sources = (values?.[0] as string[]) ?? []; const sourceIds = (values?.[1] as string[]) ?? []; const validFroms = (values?.[2] as string[]) ?? []; return { rows: sources.map((source, i) => ({ source, source_id: sourceIds[i], valid_from: validFroms[i], inserted: true, })), } as unknown as SecurityMasterQueryResult; } if (text.startsWith('INSERT INTO corporate_action_continuity')) { const firstCol = (values?.[0] as unknown[]) ?? []; return { rows: firstCol.map(() => ({ inserted: true })), } as unknown as SecurityMasterQueryResult; } if (text.includes('WITH enforced AS')) { return { rows: [], } as unknown as SecurityMasterQueryResult; } return { rows: [] } as SecurityMasterQueryResult; }, }; return { client, queries }; } describe('persistSecurityMaster unit tests', () => { test('rejects a pg.Pool-shaped object and non-queryable inputs', async () => { const fakePool = { totalCount: 1, idleCount: 1, waitingCount: 0, query: async () => ({ rows: [] }), } as unknown as SecurityMasterQueryable; const emptyInput: PersistSecurityMasterInput = { stageA: emptyStageA(), stageB: emptyStageB(), securityTypeByIsin: new Map(), }; await expect(persistSecurityMaster(fakePool, emptyInput)).rejects.toThrow(/PoolClient/); await expect( persistSecurityMaster(null as unknown as SecurityMasterQueryable, emptyInput) ).rejects.toThrow(/query\(\)/); }); test('validates chunkSize bounds', async () => { const { client } = createMockClient(); const emptyInput: PersistSecurityMasterInput = { stageA: emptyStageA(), stageB: emptyStageB(), securityTypeByIsin: new Map(), }; await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 0 })).rejects.toThrow( RangeError ); await expect(persistSecurityMaster(client, emptyInput, { chunkSize: -5 })).rejects.toThrow( RangeError ); await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 1.5 })).rejects.toThrow( RangeError ); await expect( persistSecurityMaster(client, emptyInput, { chunkSize: MAX_PERSIST_CHUNK_SIZE + 1 }) ).rejects.toThrow(RangeError); }); test('empty input fast path runs only BEGIN, advisory lock, override CTE, and COMMIT', async () => { const { client, queries } = createMockClient(); const result = await persistSecurityMaster(client, { stageA: emptyStageA(), stageB: emptyStageB(), securityTypeByIsin: new Map(), }); expect(queries.map(q => q.text.trim().split('\n')[0])).toEqual([ 'BEGIN', 'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))', 'WITH enforced AS (', 'COMMIT', ]); expect(queries[1]?.values).toEqual([SECURITY_MASTER_PERSIST_LOCK_NAMESPACE]); expect(result.instrumentsInserted).toBe(0); expect(result.listingsInserted).toBe(0); expect(result.providerMappingsInserted).toBe(0); expect(result.overridesApplied).toBe(0); }); test('parameterizes all SQL values and never interpolates untrusted strings into SQL text', async () => { const { client, queries } = createMockClient(); const hostileName = "O'Brien Corp; DROP TABLE instrument; --"; const hostileSourceId = "BAD'ID;DELETE"; const stageA = emptyStageA(); stageA.instruments.push({ primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: hostileName, members: [{ source: 'ib', sourceId: hostileSourceId, currency: 'USD', method: 'tier1_isin' }], }); stageA.conflicts.push({ source: 'eod', sourceId: hostileSourceId, conflictKind: 'isin_cusip_mismatch', detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null, }, }); const stageB = emptyStageB(); const key = { primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', }; stageB.listings.push({ ...key, ibConid: 265598, ibPrimaryExchange: 'NASDAQ', listedFrom: '1980-12-12', listedTo: null, }); stageB.providerMappings.push({ source: 'ib', sourceId: hostileSourceId, listingKey: key, method: 'tier1_isin', validFrom: null, validTo: null, }); await persistSecurityMaster(client, { stageA, stageB, securityTypeByIsin: new Map([['US0378331005', 'common']]), }); for (const q of queries) { expect(q.text).not.toContain(hostileName); expect(q.text).not.toContain(hostileSourceId); expect(q.text).not.toContain('US0378331005'); } const mappingInsert = queries.find(q => q.text.startsWith('INSERT INTO provider_mapping')); expect(mappingInsert?.values?.[2]).toEqual([DEFAULT_VALID_FROM]); expect(mappingInsert?.values?.[6]).toEqual([ PROVIDER_MAPPING_CONFIDENCE.tier1_isin.toFixed(3), ]); }); test('statement count scales with O(ceil(N / chunkSize)) rather than O(N)', async () => { const count = 600; const chunkSize = 200; const stageA = emptyStageA(); const stageB = emptyStageB(); const securityTypeByIsin = new Map(); for (let i = 0; i < count; i++) { const isin = `US${String(i).padStart(9, '0')}0`; const cusip = String(i).padStart(9, '0'); stageA.instruments.push({ primaryIsin: isin, primaryCusip: cusip, issuerCountry: 'US', canonicalName: `Corp ${i}`, members: [{ source: 'eod', sourceId: `T${i}.US`, currency: 'USD', method: 'tier1_isin' }], }); securityTypeByIsin.set(isin, 'common'); const key = { primaryIsin: isin, mic: 'XNAS', tickerRoot: `T${i}`, classSuffix: '', currency: 'USD', }; stageB.listings.push({ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null, }); stageB.providerMappings.push({ source: 'eod', sourceId: `T${i}.US`, listingKey: key, method: 'tier1_isin', validFrom: null, validTo: null, }); stageB.providerMappings.push({ source: 'qm', sourceId: `T${i}:US`, listingKey: key, method: 'tier3_ticker_span', validFrom: '2020-01-01', validTo: null, }); } const { client, queries } = createMockClient(); const result = await persistSecurityMaster( client, { stageA, stageB, securityTypeByIsin }, { chunkSize } ); expect(result.instrumentsInserted).toBe(count); expect(result.listingsInserted).toBe(count); expect(result.providerMappingsInserted).toBe(count * 2); // 3 chunks for instruments (select+insert), 6 for id_history (ISIN+CUSIP), // 1 exchange select, 3+3+3 for listings (select+insert+symbol_history), // 6 for provider_mapping, plus BEGIN/lock/override/COMMIT = 31 queries total << 600 rows. expect(queries.length).toBeLessThan(40); }); test('canonicalizes JSONB keys deterministically regardless of property insertion order', () => { const a = { z: 1, a: { d: 2, b: [3, undefined, { y: true, x: false }] }, dropMe: undefined }; const b = { a: { b: [3, null, { x: false, y: true }], d: 2 }, z: 1 }; expect(stableJsonStringify(a)).toBe(stableJsonStringify(b)); expect(canonicalizeJsonValue(Number.NaN)).toBeNull(); }); test('selects best member source for instrument_identifier_history (tier1_isin > tier2_cusip, ib > eod)', async () => { const stageA = emptyStageA(); stageA.instruments.push( { primaryIsin: 'US0000000010', primaryCusip: null, issuerCountry: 'US', canonicalName: 'Tier1 IB wins over EOD', members: [ { source: 'eod', sourceId: 'A.US', currency: 'USD', method: 'tier1_isin' }, { source: 'ib', sourceId: '1', currency: 'USD', method: 'tier1_isin' }, ], }, { primaryIsin: 'US0000000020', primaryCusip: null, issuerCountry: 'US', canonicalName: 'Tier1 EOD wins over Tier2 IB', members: [ { source: 'ib', sourceId: '2', currency: 'USD', method: 'tier2_cusip' }, { source: 'eod', sourceId: 'B.US', currency: 'USD', method: 'tier1_isin' }, ], }, { primaryIsin: 'US0000000030', primaryCusip: null, issuerCountry: 'US', canonicalName: 'Empty members falls back to eod', members: [], } ); const { client, queries } = createMockClient(); await persistSecurityMaster(client, { stageA, stageB: emptyStageB(), securityTypeByIsin: new Map([ ['US0000000010', 'common'], ['US0000000020', 'common'], ['US0000000030', 'common'], ]), }); const idHistoryQuery = queries.find(q => q.text.startsWith('INSERT INTO instrument_identifier_history') ); expect(idHistoryQuery?.values?.[4]).toEqual(['ib', 'eod', 'eod']); }); test('rejects duplicate input natural keys and duplicate DB listing rows', async () => { const { client } = createMockClient(); // 1. Duplicate primaryIsin const dupIsin = emptyStageA(); dupIsin.instruments.push( { primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: 'Apple', members: [], }, { primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: 'Apple Dup', members: [], } ); await expect( persistSecurityMaster(client, { stageA: dupIsin, stageB: emptyStageB(), securityTypeByIsin: new Map([['US0378331005', 'common']]), }) ).rejects.toThrow(/Duplicate primaryIsin/); // 2. Duplicate listing natural key const stageA = emptyStageA(); stageA.instruments.push({ primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: 'Apple', members: [], }); const dupListing = emptyStageB(); const key = { primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', }; dupListing.listings.push( { ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null }, { ...key, ibConid: 1, ibPrimaryExchange: 'NASDAQ', listedFrom: null, listedTo: null } ); await expect( persistSecurityMaster(client, { stageA, stageB: dupListing, securityTypeByIsin: new Map([['US0378331005', 'common']]), }) ).rejects.toThrow(/Duplicate listing natural key/); // 3. Duplicate provider_mapping PK const dupMapping = emptyStageB(); dupMapping.listings.push({ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null, }); dupMapping.providerMappings.push( { source: 'eod', sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin', validFrom: null, validTo: null, }, { source: 'eod', sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin', validFrom: DEFAULT_VALID_FROM, validTo: null, } ); await expect( persistSecurityMaster(client, { stageA, stageB: dupMapping, securityTypeByIsin: new Map([['US0378331005', 'common']]), }) ).rejects.toThrow(/Duplicate provider_mapping primary key/); // 4. Duplicate Pass 6 listing outcome const dupPass6: DelistingChainResult = { continuities: [], listingOutcomes: [ { listingKey: key, delistReason: 'active', terminalReturn: null }, { listingKey: key, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, ], conflicts: [], stats: { totalInputListings: 1, processedListings: 1, skippedMalformedEntries: 0, skippedInvalidDates: 0, skippedDuplicateKeys: 0, continuitiesCreated: 0, conflictsDetected: 0, byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 0 }, }, }; const singleStageB = emptyStageB(); singleStageB.listings.push({ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null, }); await expect( persistSecurityMaster(client, { stageA, stageB: singleStageB, pass6: dupPass6, securityTypeByIsin: new Map([['US0378331005', 'common']]), }) ).rejects.toThrow(/Duplicate listing outcome key/); // 5. Duplicate existing DB listing rows for incoming natural key const { client: dupDbClient, queries: dupDbQueries } = createMockClient(text => { if (text.startsWith('SELECT') && text.includes('FROM instrument')) { return { rows: [ { instrument_id: 7, primary_isin: 'US0378331005', primary_cusip: '037833100', canonical_name: 'Apple', security_type: 'common', issuer_country: 'US', }, ], }; } if (text.startsWith('SELECT mic FROM exchange')) { return { rows: [{ mic: 'XNAS' }] }; } if (text.startsWith('SELECT') && text.includes('FROM listing')) { return { rows: [ { listing_id: 1, instrument_id: 7, mic: 'XNAS', ticker_root: 'AAPL', class_suffix: '', currency: 'USD', ib_conid: null, ib_primary_exchange: null, listed_from: null, listed_to: null, delist_reason: null, terminal_return: null, }, { listing_id: 2, instrument_id: 7, mic: 'XNAS', ticker_root: 'AAPL', class_suffix: '', currency: 'USD', ib_conid: null, ib_primary_exchange: null, listed_from: '2020-01-01', listed_to: null, delist_reason: null, terminal_return: null, }, ], }; } return { rows: [] }; }); await expect( persistSecurityMaster(dupDbClient, { stageA, stageB: singleStageB, securityTypeByIsin: new Map([['US0378331005', 'common']]), }) ).rejects.toThrow(/duplicate rows for natural key/); expect(dupDbQueries.at(-1)?.text).toBe('ROLLBACK'); }); test('executes ROLLBACK and rethrows original error on mid-run failure (even if ROLLBACK fails)', async () => { const boom = new Error('injected check violation'); const { client, queries } = createMockClient(text => { if (text.startsWith('INSERT INTO instrument (')) { throw boom; } if (text === 'ROLLBACK') { throw new Error('rollback also failed'); } return { rows: [] }; }); const stageA = emptyStageA(); stageA.instruments.push({ primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: 'Apple Inc.', members: [], }); await expect( persistSecurityMaster(client, { stageA, stageB: emptyStageB(), securityTypeByIsin: new Map([['US0378331005', 'common']]), }) ).rejects.toBe(boom); expect(queries.some(q => q.text === 'BEGIN')).toBe(true); expect(queries.some(q => q.text === 'ROLLBACK')).toBe(true); expect(queries.some(q => q.text === 'COMMIT')).toBe(false); expect(formatListingNaturalKey({ primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', })).toBe('US0378331005\u0000XNAS\u0000AAPL\u0000\u0000USD'); }); test('rejects overlapping calls on the same client before issuing BEGIN and allows sequential reuse', async () => { let releaseFirstBegin!: () => void; const firstBeginPaused = new Promise(resolve => { releaseFirstBegin = resolve; }); let beginCount = 0; const { client, queries } = createMockClient(async text => { if (text === 'BEGIN') { beginCount += 1; if (beginCount === 1) { await firstBeginPaused; } } return { rows: [] }; }); const emptyInput: PersistSecurityMasterInput = { stageA: emptyStageA(), stageB: emptyStageB(), securityTypeByIsin: new Map(), }; const firstCall = persistSecurityMaster(client, emptyInput); const secondCall = persistSecurityMaster(client, emptyInput); await expect(secondCall).rejects.toThrow(/overlapping calls on the same client/); // Second call must reject before issuing a second BEGIN. expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(1); releaseFirstBegin(); const firstResult = await firstCall; expect(firstResult.instrumentsInserted).toBe(0); // Once the first call completes, sequential reuse of the same client succeeds. const thirdResult = await persistSecurityMaster(client, emptyInput); expect(thirdResult.instrumentsInserted).toBe(0); expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(2); }); test('counts each provider_mapping key once across matcher and override outcomes', async () => { const stageA = emptyStageA(); stageA.instruments.push({ primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: 'Apple Inc.', members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], }); const key = { primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', }; const stageB = emptyStageB(); stageB.listings.push({ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: '1980-12-12', listedTo: null, }); stageB.providerMappings.push( // Existing row skipped by matcher because override exists, then updated by override { source: 'eod', sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin', validFrom: '1980-12-12', validTo: null, }, // Fresh row inserted by matcher, then immediately updated by override -> net outcome: inserted { source: 'ib', sourceId: '265598', listingKey: key, method: 'tier1_isin', validFrom: '1980-12-12', validTo: null, }, // Existing row unchanged by matcher and not in override -> unchanged { source: 'qm', sourceId: 'AAPL:US', listingKey: key, method: 'tier3_ticker_span', validFrom: '2010-01-04', validTo: null, } ); const { client } = createMockClient((text, values) => { if (text.startsWith('SELECT mic FROM exchange')) { return { rows: [{ mic: 'XNAS' }] }; } if (text.startsWith('INSERT INTO instrument (')) { return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] }; } if (text.startsWith('INSERT INTO instrument_identifier_history')) { const ids = (values?.[0] as number[]) ?? []; return { rows: ids.map(() => ({ inserted: 1 })) }; } if (text.startsWith('INSERT INTO listing (')) { return { rows: [ { listing_id: 10, instrument_id: 1, mic: 'XNAS', ticker_root: 'AAPL', class_suffix: '', currency: 'USD', }, ], }; } if (text.includes('INTO listing_symbol_history')) { return { rows: [{ inserted_count: 1, updated_count: 0 }] }; } if (text.startsWith('INSERT INTO provider_mapping')) { // Only the fresh ib row is inserted by matcher; eod is skipped by override guard; qm unchanged. return { rows: [ { source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: true }, ], }; } if (text.includes('WITH enforced AS')) { return { rows: [ { source: 'eod', source_id: 'AAPL.US', valid_from: '1980-12-12', inserted: false }, { source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: false }, { source: 'qm', source_id: 'OVR_NEW:US', valid_from: '2021-01-01', inserted: true }, { source: 'qm', source_id: 'OVR_SAME:US', valid_from: '2021-01-01', inserted: null }, ], }; } return { rows: [] }; }); const result = await persistSecurityMaster(client, { stageA, stageB, securityTypeByIsin: new Map([['US0378331005', 'common']]), }); expect(result.overridesApplied).toBe(4); expect(result.providerMappingsInserted).toBe(2); // ib (fresh+overridden) + OVR_NEW expect(result.providerMappingsUpdated).toBe(1); // eod (existing+overridden) expect(result.providerMappingsUnchanged).toBe(2); // qm AAPL:US + OVR_SAME }); });