import { describe, expect, test } from 'bun:test'; import { buildMatchReport, generateOverrideSeedSql, generateOverrideTemplateSql, renderConflictsCsv, renderMatchReportMarkdown, sourceCountryKey, type MatchReport, type OverrideSeedRow, type StageAMatchResult, type StageBMatchResult, type UnifiedConflictRow, } from '../../apps/stock/data-pipeline/src/security-master'; 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 reportWithConflicts(conflicts: UnifiedConflictRow[]): MatchReport { return { ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), conflicts, }; } const validRow: OverrideSeedRow = { source: 'eod', sourceId: 'BRK-B.US', validFrom: '2020-01-15', validTo: null, primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'B', currency: 'USD', reason: 'class share mapping', createdBy: 'director', }; describe('buildMatchReport edge cases', () => { test('empty exchange classification yields null mappedPct and fails exchangesMapped100', () => { const report = buildMatchReport({ exchanges: { mapped: [], unresolved: [] }, stageA: makeEmptyStageA(), stageB: makeEmptyStageB(), }); expect(report.exchangeCoverage).toEqual({ mapped: 0, unresolved: 0, total: 0, mappedPct: null }); expect(report.meetsExitThresholds.exchangesMapped100).toBe(false); }); test('one failing eligible source fails equitiesResolved95 even when others pass', () => { const stageB = makeEmptyStageB(); stageB.stats.bySource.eod = { total: 100, matched: 100, unresolved: 0, conflict: 0 }; stageB.stats.bySource.qm = { total: 100, matched: 94, unresolved: 6, conflict: 0 }; const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB }); expect(report.meetsExitThresholds.equitiesResolved95).toBe(false); expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0.94 }).meetsExitThresholds.equitiesResolved95).toBe(true); }); test('minResolvedPct boundaries 0 and 1 are accepted; 1 requires every eligible record matched', () => { const stageB = makeEmptyStageB(); stageB.stats.bySource.eod = { total: 10, matched: 10, unresolved: 0, conflict: 0 }; stageB.stats.bySource.ib = { total: 10, matched: 0, unresolved: 10, conflict: 0 }; expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0 }).meetsExitThresholds.equitiesResolved95).toBe(true); expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 1 }).meetsExitThresholds.equitiesResolved95).toBe(false); expect(() => buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: Number.POSITIVE_INFINITY })).toThrow(/minResolvedPct/); }); test('non-excluded unresolved reasons stay in the eligible denominator', () => { const stageB = makeEmptyStageB(); stageB.stats.bySource.ceo = { total: 4, matched: 2, unresolved: 2, conflict: 0 }; stageB.unresolved = [ { source: 'ceo', sourceId: 'C1', reason: 'missing_mic', primaryIsin: null }, { source: 'ceo', sourceId: 'C2', reason: 'forex_venue', primaryIsin: null }, ]; const ceo = buildMatchReport({ stageA: makeEmptyStageA(), stageB }).resolutionBySource.find(r => r.source === 'ceo'); expect(ceo?.excludedByDesign).toBe(1); expect(ceo?.eligibleTotal).toBe(3); expect(ceo?.eligibleResolvedPct).toBeCloseTo(2 / 3, 12); }); test('sourceCountries accepts a plain record, NUL-separated fallback keys, and normalizes case', () => { const stageB = makeEmptyStageB(); stageB.unresolved = [ { source: 'eod', sourceId: 'X.TO', reason: 'missing_mic', primaryIsin: null }, { source: 'qm', sourceId: 'Y:US', reason: 'excluded_fund', primaryIsin: null }, { source: 'ib', sourceId: 'UNKNOWN', reason: 'missing_mic', primaryIsin: null }, ]; const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB, sourceCountries: { [sourceCountryKey('eod', 'X.TO')]: ' ca ', 'qm\u0000Y:US': 'us', }, }); expect(report.resolutionByCountry).toEqual([ { country: 'CA', total: 1, matched: 0, unresolved: 1, conflict: 0, excludedByDesign: 0, eligibleTotal: 1, resolvedPct: 0, eligibleResolvedPct: 0 }, { country: 'US', total: 1, matched: 0, unresolved: 1, conflict: 0, excludedByDesign: 1, eligibleTotal: 0, resolvedPct: 0, eligibleResolvedPct: null }, ]); }); test('does not mutate input pass results and copies stats objects', () => { const stageA = makeEmptyStageA(); stageA.conflicts = [ { source: 'eod', sourceId: 'Z', conflictKind: 'duplicate_source_id', detail: { isin: 'B', cusip: null, country: 'US', derivedIsin: null } }, { source: 'eod', sourceId: 'A', conflictKind: 'duplicate_source_id', detail: { isin: 'A', cusip: null, country: 'US', derivedIsin: null } }, ]; const before = JSON.stringify(stageA); const report = buildMatchReport({ stageA, stageB: makeEmptyStageB() }); expect(JSON.stringify(stageA)).toBe(before); expect(report.conflicts.map(c => c.sourceId)).toEqual(['A', 'Z']); }); }); describe('render edge cases', () => { test('canonical detail JSON sorts nested keys, drops undefined, normalizes -0 identically in CSV and Markdown', () => { const a = reportWithConflicts([ { pass: 'stage_b', source: 'ib', sourceId: '1', conflictKind: 'k', detail: { z: { b: 1, a: [{ y: 2, x: -0 }] }, a: undefined } }, ]); const b = reportWithConflicts([ { pass: 'stage_b', source: 'ib', sourceId: '1', conflictKind: 'k', detail: { z: { a: [{ x: 0, y: 2 }], b: 1 } } }, ]); const csv = renderConflictsCsv(a); expect(csv).toBe(renderConflictsCsv(b)); expect(csv).toContain('"{""z"":{""a"":[{""x"":0,""y"":2}],""b"":1}}"'); expect(renderMatchReportMarkdown(a)).toBe(renderMatchReportMarkdown(b)); }); test('CSV uses CRLF terminators and an empty report is header-only', () => { expect(renderConflictsCsv(reportWithConflicts([]))).toBe('pass,source,source_id,conflict_kind,detail_json\r\n'); }); test('Markdown sample exactly at maxConflictRows reports no remaining CSV rows', () => { const rows: UnifiedConflictRow[] = [1, 2, 3].map(i => ({ pass: 'pass4', source: 'qm', sourceId: `S${i}`, conflictKind: 'k', detail: {} })); const md = renderMatchReportMarkdown(reportWithConflicts(rows), { maxConflictRows: 3 }); expect(md).toContain('Showing 3 of 3 conflicts.'); expect(md).not.toContain('more in CSV'); }); test('Markdown escapes lone CR in reason column of unresolved breakdown', () => { const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }); report.unresolvedByReason.stageB = [{ source: 'a|b', reason: 'x\ry', count: 2 }]; const md = renderMatchReportMarkdown(report); expect(md).toContain('| a\\|b | x y | 2 |'); }); }); describe('override SQL edge cases', () => { test('accepts leap day 2000-02-29 and validTo == validFrom; rejects 1900-02-29 and month 13', () => { const sql = generateOverrideSeedSql([{ ...validRow, validFrom: '2000-02-29', validTo: '2000-02-29' }]); expect(sql).toContain("DATE '2000-02-29',\n DATE '2000-02-29',"); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '1900-02-29' }])).toThrow(/validFrom/); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-13-01' }])).toThrow(/validFrom/); expect(() => generateOverrideSeedSql([{ ...validRow, validTo: '2024-01-01T00:00:00Z' }])).toThrow(/validTo/); }); test('exact boundary lengths (16-char source, 64-char sourceId) are accepted', () => { const sql = generateOverrideSeedSql([{ ...validRow, source: 's'.repeat(16), sourceId: 'i'.repeat(64) }]); expect(sql).toContain(`'${'s'.repeat(16)}'`); expect(sql).toContain(`'${'i'.repeat(64)}'`); }); test('undefined validFrom and explicit default are treated as the same key (exact dup dedup; conflicting dup throws)', () => { const explicit = { ...validRow, validFrom: '1900-01-01', validTo: undefined }; const implicit = { ...validRow, validFrom: undefined, validTo: null }; expect(generateOverrideSeedSql([explicit, implicit]).match(/INSERT INTO override/g)?.length).toBe(1); expect(() => generateOverrideSeedSql([explicit, { ...implicit, mic: 'XNAS' }])).toThrow(/Conflicting duplicate/); }); test('same source/sourceId with different validFrom yields two statements sorted by validFrom', () => { const sql = generateOverrideSeedSql([{ ...validRow, validFrom: '2022-01-01' }, { ...validRow, validFrom: '2021-01-01' }]); const first = sql.indexOf("DATE '2021-01-01'"); const second = sql.indexOf("DATE '2022-01-01'"); expect(first).toBeGreaterThan(-1); expect(second).toBeGreaterThan(first); }); test('NUL in natural-key and date fields is rejected', () => { expect(() => generateOverrideSeedSql([{ ...validRow, mic: 'XN\0S' }])).toThrow(/NUL/); expect(() => generateOverrideSeedSql([{ ...validRow, classSuffix: '\0' }])).toThrow(/NUL/); expect(() => generateOverrideSeedSql([{ ...validRow, createdBy: 'a\0' }])).toThrow(/NUL/); expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2020-01-0\0' }])).toThrow(/NUL/); }); test('template warns and emits NULL marker for overlong source, and escapes newline in conflictKind', () => { const tpl = generateOverrideTemplateSql( reportWithConflicts([{ pass: 'stage_b', source: 'x'.repeat(17), sourceId: 'ok', conflictKind: "evil\nDROP TABLE override; '", detail: {} }]) ); for (const line of tpl.split('\n')) { if (line.trim().length > 0) { expect(line.startsWith('--')).toBe(true); } } expect(tpl).toContain('-- WARNING: Cannot store raw source in PostgreSQL (length (17) exceeds 16-character limit)'); expect(tpl).toContain('-- NULL /* TODO: replace with valid source */,'); expect(tpl).toContain("-- 'ok',"); expect(tpl).not.toContain('\nDROP'); }); test('template has one candidate per source-attributed conflict including duplicates of the same sourceId', () => { const tpl = generateOverrideTemplateSql( reportWithConflicts([ { pass: 'stage_a', source: 'eod', sourceId: 'DUP', conflictKind: 'duplicate_source_id', detail: { n: 1 } }, { pass: 'stage_a', source: 'eod', sourceId: 'DUP', conflictKind: 'duplicate_source_id', detail: { n: 2 } }, { pass: 'pass6', source: null, sourceId: null, conflictKind: 'invalid_listing_dates', detail: {} }, ]) ); expect(tpl.match(/-- INSERT INTO override/g)?.length).toBe(2); }); });