import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; import { buildMatchReport, classifySourceExchanges, crossCheckPrices, DEFAULT_MAX_CONFLICT_ROWS, DEFAULT_MIN_RESOLVED_PCT, DEFAULT_OTC_MICS, DEFAULT_OVERRIDE_VALID_FROM, EXCLUDED_BY_DESIGN_STAGE_B_REASONS, generateOverrideSeedSql, generateOverrideTemplateSql, linkDelistingChains, MATCH_REPORT_PASSES, matchInstrumentsStageA, matchListingsStageB, renderConflictsCsv, renderMatchReportMarkdown, sourceCountryKey, type MatchReport, type OverrideSeedRow, type StageAMatchResult, type StageBMatchResult, type StageBSource, type StageBUnresolvedReason, type UnifiedConflictRow, } from '../../apps/stock/data-pipeline/src/security-master'; const matchReportSourcePath = fileURLToPath( new URL('../../apps/stock/data-pipeline/src/security-master/match-report.ts', import.meta.url) ); function makeRng(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function shuffleWithSeed(items: readonly T[], seed: number): T[] { const copy = [...items]; const rng = makeRng(seed); for (let i = copy.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); const tmp = copy[i]; const swap = copy[j]; if (tmp !== undefined && swap !== undefined) { copy[i] = swap; copy[j] = tmp; } } return copy; } /** * Minimal strict RFC 4180 CSV parser supporting quoted fields, doubled quotes, and embedded CR/LF. */ function parseRfc4180Csv(input: string): string[][] { const rows: string[][] = []; let row: string[] = []; let field = ''; let inQuotes = false; let i = 0; while (i < input.length) { const ch = input[i]; if (inQuotes) { if (ch === '"') { if (input[i + 1] === '"') { field += '"'; i += 2; } else { inQuotes = false; i += 1; } } else { field += ch; i += 1; } continue; } if (ch === '"' && field.length === 0) { inQuotes = true; i += 1; } else if (ch === ',') { row.push(field); field = ''; i += 1; } else if (ch === '\r' && input[i + 1] === '\n') { row.push(field); rows.push(row); row = []; field = ''; i += 2; } else if (ch === '\n') { row.push(field); rows.push(row); row = []; field = ''; i += 1; } else { field += ch; i += 1; } } if (inQuotes) { throw new Error('Unterminated quoted CSV field'); } if (field.length > 0 || row.length > 0) { row.push(field); rows.push(row); } return rows; } function makeEmptyStageA(): 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 makeEmptyStageB(): 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 buildRealPipelineFixture() { const exchanges = classifySourceExchanges([ { source: 'eod', code: 'US', operatingMic: 'XNAS', country: 'US', currency: 'USD' }, { source: 'eod', code: 'TO', operatingMic: 'XTSE', country: 'CA', currency: 'CAD' }, { source: 'ceo', code: 'TSX', country: 'CA', currency: 'CAD' }, { source: 'ib', code: 'UNKNOWN_EX', country: 'US', currency: 'USD' }, ]); // Valid ISINs: // Apple: US0378331005 (CUSIP 037833100) // Royal Bank of Canada: CA7800871021 (CUSIP 780087102) // Microsoft: US5949181045 (CUSIP 594918104) const stageA = matchInstrumentsStageA([ { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', country: 'US', currency: 'USD', name: 'Apple Inc.', }, { source: 'ib', sourceId: '265598', isin: 'US0378331005', country: 'US', currency: 'USD', name: 'APPLE INC', }, { source: 'eod', sourceId: 'RY.TO', cusip: '780087102', country: 'CA', currency: 'CAD', name: 'Royal Bank of Canada', }, { source: 'eod', sourceId: 'RY.US', isin: 'CA7800871021', country: 'US', currency: 'USD', name: 'Royal Bank of Canada', }, { source: 'eod', sourceId: 'BADFUND.US', isin: 'US5949181045', country: 'US', currency: 'USD', name: 'Excluded Mutual Fund', }, // Stage A conflict: ISIN vs CUSIP mismatch { source: 'eod', sourceId: 'MISMATCH.US', isin: 'US0378331005', cusip: '594918104', country: 'US', currency: 'USD', }, // Stage A unresolved: missing both ISIN and CUSIP { source: 'ib', sourceId: 'NOID_1', country: 'US', currency: 'USD', }, ]); const stageB = matchListingsStageB({ instruments: stageA.instruments, eodListings: [ { sourceId: 'AAPL.US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: { firstBarDate: '2010-01-04', lastBarDate: '2025-01-10' }, }, { sourceId: 'RY.TO', ticker: 'RY', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: { firstBarDate: '2010-01-04', lastBarDate: '2025-01-10' }, }, { sourceId: 'RY.US', ticker: 'RY', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: { firstBarDate: '2010-01-04', lastBarDate: '2024-06-01' }, }, { sourceId: 'BADFUND.US', ticker: 'BADF', mic: null, role: 'excluded_fund', currency: 'USD', span: { firstBarDate: '2020-01-02', lastBarDate: '2024-01-02' }, }, ], ibContracts: [ { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ', }, ], tickerSources: [ { source: 'qm', sourceId: 'AAPL:US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: { firstBarDate: '2015-01-02', lastBarDate: '2025-01-10' }, }, { source: 'ceo', sourceId: 'ceo:RY', ticker: 'RY', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: { firstBarDate: '2018-01-02', lastBarDate: '2025-01-10' }, }, // Duplicate sourceId in tickerSources -> Stage B conflict { source: 'ceo', sourceId: 'ceo:RY', ticker: 'RY', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: { firstBarDate: '2018-01-02', lastBarDate: '2025-01-10' }, }, ], }); const sampleDates = [ '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-08', '2024-01-09', ]; const priceCrossCheck = crossCheckPrices({ pairs: [ { left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, right: { source: 'qm', sourceId: 'AAPL:US', currency: 'USD' }, }, { left: { source: 'eod', sourceId: 'RY.TO', currency: 'CAD' }, right: { source: 'ceo', sourceId: 'ceo:RY', currency: 'CAD' }, }, ], closes: [ // Confirmed pair (ratio ~1.0, correlation 1.0) ...sampleDates.flatMap((date, idx) => [ { source: 'eod', sourceId: 'AAPL.US', date, close: 180 + idx * 2 }, { source: 'qm', sourceId: 'AAPL:US', date, close: 180 + idx * 2 }, ]), // Ratio mismatch pair (2x price difference -> emits price_ratio_mismatch conflict) ...sampleDates.flatMap((date, idx) => [ { source: 'eod', sourceId: 'RY.TO', date, close: 100 + idx * 2 }, { source: 'ceo', sourceId: 'ceo:RY', date, close: 200 + idx * 4 }, ]), ], usdCadByDate: sampleDates.map(date => ({ date, usdCad: 1.35 })), }); const delistingChains = linkDelistingChains( { listings: [ ...stageB.listings, // OTC continuation for RY.US (ended 2024-06-01 -> OTC starts 2024-06-04) { primaryIsin: 'CA7800871021', mic: 'OTCM', tickerRoot: 'RYOTC', classSuffix: '', currency: 'USD', ibConid: null, ibPrimaryExchange: null, listedFrom: '2024-06-04', listedTo: '2025-01-10', }, // Invalid dates listing -> triggers Pass 6 conflict (source: null, sourceId: null) { primaryIsin: 'US0378331005', mic: 'XNYS', tickerRoot: 'AAPLBAD', classSuffix: '', currency: 'USD', ibConid: null, ibPrimaryExchange: null, listedFrom: '2025-05-01', listedTo: '2024-01-01', }, ], otcMics: DEFAULT_OTC_MICS, }, { asOfDate: '2025-01-10' } ); const sourceCountries = new Map([ [sourceCountryKey('eod', 'AAPL.US'), 'US'], [sourceCountryKey('ib', '265598'), 'US'], [sourceCountryKey('qm', 'AAPL:US'), 'US'], [sourceCountryKey('eod', 'RY.TO'), 'CA'], [sourceCountryKey('ceo', 'ceo:RY'), 'CA'], [sourceCountryKey('eod', 'RY.US'), 'US'], [sourceCountryKey('eod', 'BADFUND.US'), 'US'], ]); return { exchanges, stageA, stageB, priceCrossCheck, delistingChains, sourceCountries }; } describe('security-master match-report purity & exports', () => { test('re-exports all public functions/constants and contains zero I/O or wall-clock calls', () => { expect(typeof buildMatchReport).toBe('function'); expect(typeof renderMatchReportMarkdown).toBe('function'); expect(typeof renderConflictsCsv).toBe('function'); expect(typeof generateOverrideSeedSql).toBe('function'); expect(typeof generateOverrideTemplateSql).toBe('function'); expect(DEFAULT_MIN_RESOLVED_PCT).toBe(0.95); expect(DEFAULT_MAX_CONFLICT_ROWS).toBe(200); expect(DEFAULT_OVERRIDE_VALID_FROM).toBe('1900-01-01'); expect(EXCLUDED_BY_DESIGN_STAGE_B_REASONS).toEqual([ 'excluded_fund', 'composite_venue', 'ats_routing_venue', 'forex_venue', ]); expect(MATCH_REPORT_PASSES).toEqual(['stage_a', 'stage_b', 'pass4', 'pass6']); const sourceText = readFileSync(matchReportSourcePath, 'utf8'); expect(sourceText).not.toMatch(/from\s+['"](?:node:)?(?:fs|net|http|https|dgram|tls|child_process)['"]/); expect(sourceText).not.toMatch(/from\s+['"](?:pg|mongodb|@stock-bot\/postgres|@stock-bot\/mongodb)['"]/); expect(sourceText).not.toContain('Date.now'); expect(sourceText).not.toContain('new Date'); }); }); describe('buildMatchReport', () => { test('reconciles real Stage A, Stage B, Pass 4, and Pass 6 outputs accurately', () => { const fixture = buildRealPipelineFixture(); const report = buildMatchReport(fixture); expect(report.exchangeCoverage).toEqual({ mapped: fixture.exchanges.mapped.length, unresolved: fixture.exchanges.unresolved.length, total: fixture.exchanges.mapped.length + fixture.exchanges.unresolved.length, mappedPct: fixture.exchanges.mapped.length / (fixture.exchanges.mapped.length + fixture.exchanges.unresolved.length), }); expect(report.meetsExitThresholds.exchangesMapped100).toBe(false); for (const row of report.resolutionBySource) { const expected = fixture.stageB.stats.bySource[row.source]; expect(row.total).toBe(expected.total); expect(row.matched).toBe(expected.matched); expect(row.unresolved).toBe(expected.unresolved); expect(row.conflict).toBe(expected.conflict); } const eodRow = report.resolutionBySource.find(r => r.source === 'eod'); expect(eodRow?.excludedByDesign).toBe(1); expect(eodRow?.eligibleTotal).toBe(3); expect(eodRow?.eligibleResolvedPct).toBe(1); const expectedTotalConflicts = fixture.stageA.conflicts.length + fixture.stageB.conflicts.length + fixture.priceCrossCheck.conflicts.length + fixture.delistingChains.conflicts.length; expect(expectedTotalConflicts).toBeGreaterThanOrEqual(4); expect(report.conflicts.length).toBe(expectedTotalConflicts); const countSum = report.conflictsByPassKind.reduce((acc, row) => acc + row.count, 0); expect(countSum).toBe(expectedTotalConflicts); expect(report.priceCrossCheck).toEqual({ pairsIn: fixture.priceCrossCheck.stats.pairsIn, invalidPairs: fixture.priceCrossCheck.stats.invalidPairs, conflictsEmitted: fixture.priceCrossCheck.stats.conflictsEmitted, byVerdict: fixture.priceCrossCheck.stats.byVerdict, }); expect(report.delistingChains).toEqual({ totalInputListings: fixture.delistingChains.stats.totalInputListings, processedListings: fixture.delistingChains.stats.processedListings, continuitiesCreated: fixture.delistingChains.stats.continuitiesCreated, conflictsDetected: fixture.delistingChains.stats.conflictsDetected, byOutcome: fixture.delistingChains.stats.byOutcome, }); expect(report.delistingChains?.continuitiesCreated).toBe(1); const pass6Conflict = report.conflicts.find(c => c.pass === 'pass6'); expect(pass6Conflict).toBeDefined(); expect(pass6Conflict?.source).toBeNull(); expect(pass6Conflict?.sourceId).toBeNull(); // Country resolution populated for US and CA expect(report.resolutionByCountry.map(c => c.country)).toEqual(['CA', 'US']); const usCountry = report.resolutionByCountry.find(c => c.country === 'US'); expect(usCountry?.excludedByDesign).toBe(1); }); test('computes eligibleResolvedPct exclusions, null zero-denominators, and exact exit thresholds', () => { const excludedReasons: StageBUnresolvedReason[] = [ 'excluded_fund', 'composite_venue', 'ats_routing_venue', 'forex_venue', ]; const stageB = makeEmptyStageB(); // eod: 19 matched, 1 real unresolved, 4 excluded-by-design => total=24, eligible=20, eligibleResolvedPct=19/20=0.95 stageB.stats.bySource.eod = { total: 24, matched: 19, unresolved: 5, conflict: 0 }; // ib: 2 excluded-by-design only => total=2, eligible=0 => eligibleResolvedPct = null (not NaN/Infinity) stageB.stats.bySource.ib = { total: 2, matched: 0, unresolved: 2, conflict: 0 }; // qm & ceo: total=0 => both pcts null stageB.unresolved = [ ...excludedReasons.map((reason, idx) => ({ source: 'eod' as StageBSource, sourceId: `EOD_EXCL_${idx}`, reason, primaryIsin: null, })), { source: 'eod', sourceId: 'EOD_MISSING_MIC', reason: 'missing_mic', primaryIsin: null, }, { source: 'ib', sourceId: 'IB_ATS_1', reason: 'ats_routing_venue', primaryIsin: null, }, { source: 'ib', sourceId: 'IB_FX_1', reason: 'forex_venue', primaryIsin: null, }, ]; const mappedExchanges = classifySourceExchanges([ { source: 'ceo', code: 'TSX', country: 'CA', currency: 'CAD' }, ]); const atThreshold = buildMatchReport( { exchanges: mappedExchanges, stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0.95 } ); const eod = atThreshold.resolutionBySource.find(r => r.source === 'eod'); expect(eod?.excludedByDesign).toBe(4); expect(eod?.eligibleTotal).toBe(20); expect(eod?.resolvedPct).toBeCloseTo(19 / 24, 12); expect(eod?.eligibleResolvedPct).toBe(0.95); const ib = atThreshold.resolutionBySource.find(r => r.source === 'ib'); expect(ib?.excludedByDesign).toBe(2); expect(ib?.eligibleTotal).toBe(0); expect(ib?.resolvedPct).toBe(0); expect(ib?.eligibleResolvedPct).toBeNull(); const qm = atThreshold.resolutionBySource.find(r => r.source === 'qm'); expect(qm?.resolvedPct).toBeNull(); expect(qm?.eligibleResolvedPct).toBeNull(); expect(atThreshold.meetsExitThresholds).toEqual({ exchangesMapped100: true, equitiesResolved95: true, }); // Flips to false right above 0.95 const aboveThreshold = buildMatchReport( { exchanges: mappedExchanges, stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0.9501 } ); expect(aboveThreshold.meetsExitThresholds.equitiesResolved95).toBe(false); // 18/20 = 0.90 fails default 0.95 const belowStageB = makeEmptyStageB(); belowStageB.stats.bySource.eod = { total: 20, matched: 18, unresolved: 2, conflict: 0 }; const belowReport = buildMatchReport({ exchanges: mappedExchanges, stageA: makeEmptyStageA(), stageB: belowStageB, }); expect(belowReport.meetsExitThresholds.equitiesResolved95).toBe(false); // Unresolved exchange flips exchangesMapped100 to false const unresolvedExchanges = classifySourceExchanges([ { source: 'ceo', code: 'TSX', country: 'CA', currency: 'CAD' }, { source: 'ib', code: 'BAD_EX', country: 'US', currency: 'USD' }, ]); const unresolvedExReport = buildMatchReport({ exchanges: unresolvedExchanges, stageA: makeEmptyStageA(), stageB, }); expect(unresolvedExReport.meetsExitThresholds.exchangesMapped100).toBe(false); // All-zero input returns false for both thresholds and never NaN const emptyReport = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB(), }); expect(emptyReport.meetsExitThresholds).toEqual({ exchangesMapped100: false, equitiesResolved95: false, }); expect(emptyReport.exchangeCoverage).toBeNull(); // Invalid minResolvedPct throws expect(() => buildMatchReport( { stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }, { minResolvedPct: -0.01 } ) ).toThrow(); expect(() => buildMatchReport( { stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }, { minResolvedPct: 1.01 } ) ).toThrow(); expect(() => buildMatchReport( { stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }, { minResolvedPct: Number.NaN } ) ).toThrow(); }); test('produces byte-identical Markdown, CSV, and SQL under shuffled inputs and omits timestamps', () => { const fixture = buildRealPipelineFixture(); // Add extra tie-breaking conflicts (same pass/kind/source/sourceId, different detail) const stageAConflicts = [ ...fixture.stageA.conflicts, { source: 'eod' as const, sourceId: 'DUP.US', conflictKind: 'duplicate_source_id' as const, detail: { isin: 'US0378331005', cusip: null, country: 'US', derivedIsin: null }, }, { source: 'eod' as const, sourceId: 'DUP.US', conflictKind: 'duplicate_source_id' as const, detail: { isin: 'US5949181045', cusip: null, country: 'US', derivedIsin: null }, }, ]; const pass6Conflicts = [ ...fixture.delistingChains.conflicts, { conflictKind: 'invalid_listing_dates' as const, detail: { primaryIsin: 'CA7800871021', currency: 'CAD', fromListingKeys: [], toListingKeys: [], candidateListingKeys: [], listedFrom: '2024-09-01', listedTo: '2024-01-01', reason: 'listed_to_before_listed_from', }, }, ]; const baselineReport = buildMatchReport({ exchanges: fixture.exchanges, stageA: { ...fixture.stageA, conflicts: stageAConflicts }, stageB: fixture.stageB, priceCrossCheck: fixture.priceCrossCheck, delistingChains: { ...fixture.delistingChains, conflicts: pass6Conflicts }, sourceCountries: fixture.sourceCountries, }); const shuffledReport = buildMatchReport({ exchanges: { mapped: shuffleWithSeed(fixture.exchanges.mapped, 11), unresolved: shuffleWithSeed(fixture.exchanges.unresolved, 12), }, stageA: { ...fixture.stageA, unresolved: shuffleWithSeed(fixture.stageA.unresolved, 13), conflicts: shuffleWithSeed(stageAConflicts, 14), }, stageB: { ...fixture.stageB, unresolved: shuffleWithSeed(fixture.stageB.unresolved, 15), conflicts: shuffleWithSeed(fixture.stageB.conflicts, 16), }, priceCrossCheck: { ...fixture.priceCrossCheck, conflicts: shuffleWithSeed(fixture.priceCrossCheck.conflicts, 17), }, delistingChains: { ...fixture.delistingChains, conflicts: shuffleWithSeed(pass6Conflicts, 18), }, sourceCountries: fixture.sourceCountries, }); const mdA = renderMatchReportMarkdown(baselineReport); const mdB = renderMatchReportMarkdown(shuffledReport); expect(mdA).toBe(mdB); const csvA = renderConflictsCsv(baselineReport); const csvB = renderConflictsCsv(shuffledReport); expect(csvA).toBe(csvB); const tplA = generateOverrideTemplateSql(baselineReport); const tplB = generateOverrideTemplateSql(shuffledReport); expect(tplA).toBe(tplB); const overrideRows: OverrideSeedRow[] = [ { source: 'qm', sourceId: 'RY:CA', validFrom: '2020-01-01', validTo: null, primaryIsin: 'CA7800871021', mic: 'XTSE', tickerRoot: 'RY', classSuffix: '', currency: 'CAD', reason: 'Manual override B', createdBy: 'director', }, { source: 'eod', sourceId: 'AAPL.US', validFrom: '1900-01-01', validTo: '2025-12-31', primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'Manual override A', createdBy: 'director', }, ]; const sqlA = generateOverrideSeedSql(overrideRows); const sqlB = generateOverrideSeedSql(shuffleWithSeed(overrideRows, 99)); expect(sqlA).toBe(sqlB); // No ISO timestamps anywhere in Markdown or SQL const isoTimestampPattern = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/; expect(mdA).not.toMatch(isoTimestampPattern); expect(sqlA).not.toMatch(isoTimestampPattern); expect(tplA).not.toMatch(isoTimestampPattern); }); }); describe('renderConflictsCsv', () => { test('emits RFC 4180 CSV with uncapped rows, proper quoting, empty Pass 6 source fields, and lossless JSON round-trip', () => { const conflicts: UnifiedConflictRow[] = []; // 205 synthetic conflicts (> DEFAULT_MAX_CONFLICT_ROWS=200) to prove CSV has no cap for (let i = 0; i < 205; i++) { conflicts.push({ pass: 'stage_b', source: 'qm', sourceId: `SYM_${String(i).padStart(3, '0')}`, conflictKind: 'ambiguous_ticker_span', detail: { zKey: i, aKey: `row-${i}` }, }); } // Special characters requiring RFC 4180 quoting: comma, double quotes, CR/LF conflicts.push({ pass: 'stage_a', source: 'eod', sourceId: 'ODD,"ID"\nLINE2', conflictKind: 'isin_cusip_mismatch', detail: { zeta: 'a,b,"c"\r\nd', alpha: 42, }, }); // Pass 6 conflict with null source / sourceId conflicts.push({ pass: 'pass6', source: null, sourceId: null, conflictKind: 'ambiguous_otc_continuation', detail: { primaryIsin: 'US0378331005', reason: 'multiple_otc_candidates' }, }); const report: MatchReport = { ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), conflicts, }; const csv = renderConflictsCsv(report); const parsed = parseRfc4180Csv(csv); expect(parsed[0]).toEqual(['pass', 'source', 'source_id', 'conflict_kind', 'detail_json']); expect(parsed.length).toBe(1 + conflicts.length); const oddRow = parsed.find(r => r[0] === 'stage_a'); expect(oddRow).toBeDefined(); expect(oddRow?.[1]).toBe('eod'); expect(oddRow?.[2]).toBe('ODD,"ID"\nLINE2'); expect(oddRow?.[3]).toBe('isin_cusip_mismatch'); // Stable key order: alpha before zeta expect(oddRow?.[4]).toBe('{"alpha":42,"zeta":"a,b,\\"c\\"\\r\\nd"}'); expect(JSON.parse(oddRow?.[4] ?? '{}')).toEqual({ alpha: 42, zeta: 'a,b,"c"\r\nd', }); const pass6Row = parsed.find(r => r[0] === 'pass6'); expect(pass6Row).toEqual([ 'pass6', '', '', 'ambiguous_otc_continuation', '{"primaryIsin":"US0378331005","reason":"multiple_otc_candidates"}', ]); }); }); describe('renderMatchReportMarkdown', () => { test('escapes pipes and newlines, caps conflict sample with remaining count, and renders valid empty tables', () => { const conflicts: UnifiedConflictRow[] = [ { pass: 'stage_a', source: 'eod', sourceId: 'A|B\nC\\D', conflictKind: 'isin_cusip_mismatch', detail: { note: 'line1\r\nline2|pipe' }, }, { pass: 'stage_b', source: 'ib', sourceId: 'IB_1', conflictKind: 'ambiguous_ib_listing', detail: { primaryIsin: 'US0378331005' }, }, { pass: 'pass4', source: 'ceo', sourceId: 'ceo:RY', conflictKind: 'price_ratio_mismatch', detail: { medianRatio: 2 }, }, { pass: 'pass6', source: null, sourceId: null, conflictKind: 'invalid_listing_dates', detail: { reason: 'listed_to_before_listed_from' }, }, ]; const report: MatchReport = { ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), conflicts, }; const mdAll = renderMatchReportMarkdown(report, { maxConflictRows: 10 }); expect(mdAll).toContain('A\\|B C\\\\D'); expect(mdAll).toContain('{"note":"line1\\\\r\\\\nline2\\|pipe"}'); expect(mdAll).toContain('Showing 4 of 4 conflicts.'); const md = renderMatchReportMarkdown(report, { maxConflictRows: 2 }); expect(md).toContain('Showing 2 of 4 conflicts (2 more in CSV).'); // Verify table rows in Conflict Sample have no broken newlines const sampleSection = md.split('## Conflict Sample')[1] ?? ''; const tableLines = sampleSection .split('\n') .filter(line => line.startsWith('|')); // header + separator + 2 data rows = 4 lines expect(tableLines.length).toBe(4); // maxConflictRows: 0 still shows remaining count const mdZeroCap = renderMatchReportMarkdown(report, { maxConflictRows: 0 }); expect(mdZeroCap).toContain('Showing 0 of 4 conflicts (4 more in CSV).'); // Empty report renders valid tables with zero counts const emptyReport = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB(), }); const emptyMd = renderMatchReportMarkdown(emptyReport); expect(emptyMd).toContain('| 0 | 0 | 0 | N/A |'); expect(emptyMd).toContain('| eod | 0 | 0 | 0 | 0 | 0 | 0 | N/A | N/A |'); expect(emptyMd).toContain('| confirmed | 0 |'); expect(emptyMd).toContain('| active | 0 |'); expect(emptyMd).toContain('No open conflicts (0 total).'); // Invalid maxConflictRows throws expect(() => renderMatchReportMarkdown(emptyReport, { maxConflictRows: -1 })).toThrow(); expect(() => renderMatchReportMarkdown(emptyReport, { maxConflictRows: 1.5 })).toThrow(); }); }); describe('generateOverrideSeedSql & generateOverrideTemplateSql', () => { const validRow: OverrideSeedRow = { source: 'eod', sourceId: 'AAPL.US', validFrom: '2020-01-15', validTo: '2025-12-31', primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: "O'Brien fix", createdBy: 'director', }; test('emits portable natural-key INSERT ... SELECT ... ON CONFLICT DO NOTHING, escapes quotes, deduplicates exact duplicates, and handles empty input', () => { const emptySql = generateOverrideSeedSql([]); expect(emptySql.trim().length).toBeGreaterThan(0); expect(emptySql).not.toContain('INSERT INTO'); for (const line of emptySql.split('\n')) { if (line.trim().length > 0) { expect(line.startsWith('--')).toBe(true); } } const sql = generateOverrideSeedSql([validRow, { ...validRow }]); const insertMatches = sql.match(/INSERT INTO override/g) ?? []; expect(insertMatches.length).toBe(1); expect(sql).toContain("'O''Brien fix'"); expect(sql).toContain("DATE '2020-01-15'"); expect(sql).toContain("DATE '2025-12-31'"); expect(sql).toContain('FROM listing l'); expect(sql).toContain('JOIN instrument i ON i.instrument_id = l.instrument_id'); expect(sql).toContain("WHERE i.primary_isin = 'US0378331005'"); expect(sql).toContain("AND l.mic = 'XNAS'"); expect(sql).toContain("AND l.ticker_root = 'AAPL'"); expect(sql).toContain("AND l.class_suffix = ''"); expect(sql).toContain("AND l.currency = 'USD'"); expect(sql).toContain('WHERE matched.listing_id IS NOT NULL'); expect(sql).not.toContain('ORDER BY l.listing_id'); expect(sql).not.toContain('LIMIT 1'); expect(sql).toContain('ON CONFLICT (source, source_id, valid_from) DO NOTHING;'); // Default validFrom and null validTo const defaultDatesSql = generateOverrideSeedSql([ { ...validRow, validFrom: undefined, validTo: undefined }, ]); expect(defaultDatesSql).toContain("DATE '1900-01-01'"); expect(defaultDatesSql).toContain('\n NULL,\n'); }); test('throws clear validation errors on invalid fields, dates, NUL bytes, and conflicting duplicates', () => { expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: '' }])).toThrow(/sourceId/); expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: ' ' }])).toThrow(/sourceId/); expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: 'x'.repeat(65) }])).toThrow( /sourceId/ ); expect(() => generateOverrideSeedSql([{ ...validRow, source: '' }])).toThrow(/source/); expect(() => generateOverrideSeedSql([{ ...validRow, source: 's'.repeat(17) }])).toThrow( /source/ ); expect(() => generateOverrideSeedSql([{ ...validRow, reason: '' }])).toThrow(/reason/); expect(() => generateOverrideSeedSql([{ ...validRow, createdBy: ' ' }])).toThrow(/createdBy/); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-02-30' }])).toThrow( /validFrom/ ); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2023-02-29' }])).toThrow( /validFrom/ ); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-1-01' }])).toThrow( /validFrom/ ); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '0000-01-01' }])).toThrow( /validFrom/ ); expect(() => generateOverrideSeedSql([{ ...validRow, validTo: '2024-02-30' }])).toThrow( /validTo/ ); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-06-01', validTo: '2024-05-31' }]) ).toThrow(/validTo/); expect(() => generateOverrideSeedSql([{ ...validRow, reason: 'bad\0nul' }])).toThrow(/NUL/); expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: 'A\0B' }])).toThrow(/NUL/); expect(() => generateOverrideSeedSql([{ ...validRow, primaryIsin: 'X'.repeat(13) }])).toThrow( /primaryIsin/ ); expect(() => generateOverrideSeedSql([{ ...validRow, mic: 'X'.repeat(11) }])).toThrow(/mic/); expect(() => generateOverrideSeedSql([{ ...validRow, tickerRoot: 'X'.repeat(25) }])).toThrow( /tickerRoot/ ); expect(() => generateOverrideSeedSql([{ ...validRow, classSuffix: 'X'.repeat(13) }])).toThrow( /classSuffix/ ); expect(() => generateOverrideSeedSql([{ ...validRow, currency: 'USDD' }])).toThrow(/currency/); // Conflicting duplicate on (source, sourceId, validFrom) expect(() => generateOverrideSeedSql([validRow, { ...validRow, reason: 'Different reason' }]) ).toThrow(/Conflicting duplicate/); }); test('generateOverrideTemplateSql comments out every non-blank line, preserves CR/LF via E-string literals, warns on unstorable IDs, and omits Pass 6 conflicts', () => { const conflicts: UnifiedConflictRow[] = [ { pass: 'stage_a', source: 'eod', sourceId: "BAD\r\nDROP'\\TABLE override;--", conflictKind: 'isin_cusip_mismatch', detail: {}, }, { pass: 'stage_a', source: 'eod', sourceId: 'UNSTORABLE\0ID', conflictKind: 'isin_cusip_mismatch', detail: {}, }, { pass: 'stage_b', source: 'ib', sourceId: '12345', conflictKind: 'ambiguous_ib_listing', detail: {}, }, { pass: 'pass4', source: 'ceo', sourceId: 'ceo:RY', conflictKind: 'price_ratio_mismatch', detail: {}, }, // Pass 6 conflict without source/sourceId must NOT emit a template statement { pass: 'pass6', source: null, sourceId: null, conflictKind: 'ambiguous_otc_continuation', detail: {}, }, ]; const report: MatchReport = { ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), conflicts, }; const templateSql = generateOverrideTemplateSql(report); for (const line of templateSql.split('\n')) { if (line.trim().length > 0) { expect(line.startsWith('--')).toBe(true); } } const commentedInserts = templateSql.match(/-- INSERT INTO override/g) ?? []; expect(commentedInserts.length).toBe(4); expect(templateSql).not.toContain('ambiguous_otc_continuation'); expect(templateSql).not.toContain('ORDER BY l.listing_id'); expect(templateSql).not.toContain('LIMIT 1'); expect(templateSql).toContain('-- WHERE matched.listing_id IS NOT NULL'); // CR/LF source_id is preserved via a single-line PostgreSQL E'...' literal expect(templateSql).toContain("-- E'BAD\\r\\nDROP''\\\\TABLE override;--',"); // Unstorable NUL-byte source_id gets a diagnostic warning and non-insertable NULL marker instead of silent mangling expect(templateSql).toContain( '-- WARNING: Cannot store raw source_id in PostgreSQL (contains NUL byte); correct source_id before applying.' ); expect(templateSql).toContain('-- NULL /* TODO: replace with valid source_id */,'); expect(templateSql).not.toContain('TODO_CORRECT_SOURCE_ID'); // Empty conflicts report still produces only comments const emptyTemplate = generateOverrideTemplateSql( buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }) ); for (const line of emptyTemplate.split('\n')) { if (line.trim().length > 0) { expect(line.startsWith('--')).toBe(true); } } expect(emptyTemplate).toContain('No source-attributed open conflicts'); }); test('renderMatchReportMarkdown emits Status: skipped when priceCrossCheck is null and omits it when supplied', () => { const reportWithoutPass4 = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB(), }); expect(reportWithoutPass4.priceCrossCheck).toBeNull(); const mdSkipped = renderMatchReportMarkdown(reportWithoutPass4); expect(mdSkipped).toContain( '## Pass 4 Price Cross-Check Verdicts\n\n- Status: skipped (no sample closes supplied)\n- Pairs In: 0' ); const pass4 = crossCheckPrices({ pairs: [], closes: [], usdCadByDate: [], }); const reportWithPass4 = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB(), priceCrossCheck: pass4, }); expect(reportWithPass4.priceCrossCheck).not.toBeNull(); const mdExecuted = renderMatchReportMarkdown(reportWithPass4); expect(mdExecuted).not.toContain('Status: skipped'); expect(mdExecuted).toContain('## Pass 4 Price Cross-Check Verdicts\n\n- Pairs In: 0'); }); });