diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index f47fe4bf..fe944432 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -110,6 +110,38 @@ export { type StageBUnresolvedRecord, } from './listing-stage-b'; +export { + buildMatchReport, + DEFAULT_MAX_CONFLICT_ROWS, + DEFAULT_MIN_RESOLVED_PCT, + DEFAULT_OVERRIDE_VALID_FROM, + EXCLUDED_BY_DESIGN_STAGE_B_REASONS, + generateOverrideSeedSql, + generateOverrideTemplateSql, + MATCH_REPORT_PASSES, + renderConflictsCsv, + renderMatchReportMarkdown, + sourceCountryKey, + type BuildMatchReportOptions, + type ConflictCountRow, + type CountryResolutionSummary, + type DelistingChainSummary, + type ExchangeCoverageSummary, + type ExcludedByDesignStageBReason, + type MatchReport, + type MatchReportExitThresholds, + type MatchReportInput, + type MatchReportPass, + type OverrideSeedRow, + type PriceCrossCheckSummary, + type RenderMatchReportMarkdownOptions, + type SourceCountryLookup, + type SourceResolutionSummary, + type UnifiedConflictRow, + type UnresolvedBreakdown, + type UnresolvedBreakdownRow, +} from './match-report'; + export { crossCheckPrices, DEFAULT_MIN_COMMON_DATES, diff --git a/apps/stock/data-pipeline/src/security-master/match-report.ts b/apps/stock/data-pipeline/src/security-master/match-report.ts new file mode 100644 index 00000000..0b6a7170 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/match-report.ts @@ -0,0 +1,1099 @@ +import type { + DelistingChainOutcomeStats, + DelistingChainResult, +} from './delisting-chains'; +import { DELIST_REASONS } from './delisting-chains'; +import { compareAscii, type ExchangeClassificationResult } from './exchange-pass1'; +import { escapeSqlLiteral } from './exchange-seed-sql'; +import type { StageAMatchResult } from './instrument-stage-a'; +import { + STAGE_B_SOURCES, + type StageBMatchResult, + type StageBSource, + type StageBUnresolvedReason, +} from './listing-stage-b'; +import { + PRICE_CROSS_CHECK_VERDICTS, + type PriceCrossCheckResult, + type PriceCrossCheckVerdictCounts, +} from './price-cross-check'; + +export const DEFAULT_MIN_RESOLVED_PCT = 0.95; +export const DEFAULT_MAX_CONFLICT_ROWS = 200; +export const DEFAULT_OVERRIDE_VALID_FROM = '1900-01-01'; + +export const EXCLUDED_BY_DESIGN_STAGE_B_REASONS = [ + 'excluded_fund', + 'composite_venue', + 'ats_routing_venue', + 'forex_venue', +] as const satisfies readonly StageBUnresolvedReason[]; + +export const MATCH_REPORT_PASSES = ['stage_a', 'stage_b', 'pass4', 'pass6'] as const; + +export type MatchReportPass = (typeof MATCH_REPORT_PASSES)[number]; +export type ExcludedByDesignStageBReason = (typeof EXCLUDED_BY_DESIGN_STAGE_B_REASONS)[number]; + +export type SourceCountryLookup = ReadonlyMap | Readonly>; + +export interface MatchReportInput { + readonly exchanges?: ExchangeClassificationResult; + readonly stageA: StageAMatchResult; + readonly stageB: StageBMatchResult; + readonly priceCrossCheck?: PriceCrossCheckResult; + readonly delistingChains?: DelistingChainResult; + readonly sourceCountries?: SourceCountryLookup; +} + +export interface BuildMatchReportOptions { + readonly minResolvedPct?: number; +} + +export interface ExchangeCoverageSummary { + mapped: number; + unresolved: number; + total: number; + mappedPct: number | null; +} + +/** + * Per-source resolution summary derived from Stage B stats and unresolved records. + * + * Formulas: + * - `resolvedPct = total > 0 ? matched / total : null` + * - `excludedByDesign`: count of Stage B unresolved records for this source whose reason is + * one of `excluded_fund`, `composite_venue`, `ats_routing_venue`, or `forex_venue`. + * - `eligibleTotal = Math.max(0, total - excludedByDesign)` + * - `eligibleResolvedPct = eligibleTotal > 0 ? matched / eligibleTotal : null` + */ +export interface SourceResolutionSummary { + source: StageBSource; + total: number; + matched: number; + unresolved: number; + conflict: number; + excludedByDesign: number; + eligibleTotal: number; + resolvedPct: number | null; + eligibleResolvedPct: number | null; +} + +export interface CountryResolutionSummary { + country: string; + total: number; + matched: number; + unresolved: number; + conflict: number; + excludedByDesign: number; + eligibleTotal: number; + resolvedPct: number | null; + eligibleResolvedPct: number | null; +} + +export interface UnresolvedBreakdownRow { + source: string; + reason: string; + count: number; +} + +export interface UnresolvedBreakdown { + stageA: UnresolvedBreakdownRow[]; + stageB: UnresolvedBreakdownRow[]; +} + +export interface UnifiedConflictRow { + pass: MatchReportPass; + source: string | null; + sourceId: string | null; + conflictKind: string; + detail: Record; +} + +export interface ConflictCountRow { + pass: MatchReportPass; + conflictKind: string; + count: number; +} + +export interface PriceCrossCheckSummary { + pairsIn: number; + invalidPairs: number; + conflictsEmitted: number; + byVerdict: PriceCrossCheckVerdictCounts; +} + +export interface DelistingChainSummary { + totalInputListings: number; + processedListings: number; + continuitiesCreated: number; + conflictsDetected: number; + byOutcome: DelistingChainOutcomeStats; +} + +export interface MatchReportExitThresholds { + exchangesMapped100: boolean; + equitiesResolved95: boolean; +} + +export interface MatchReport { + minResolvedPct: number; + exchangeCoverage: ExchangeCoverageSummary | null; + resolutionBySource: SourceResolutionSummary[]; + resolutionByCountry: CountryResolutionSummary[]; + unresolvedByReason: UnresolvedBreakdown; + conflicts: UnifiedConflictRow[]; + conflictsByPassKind: ConflictCountRow[]; + priceCrossCheck: PriceCrossCheckSummary | null; + delistingChains: DelistingChainSummary | null; + meetsExitThresholds: MatchReportExitThresholds; +} + +export interface RenderMatchReportMarkdownOptions { + readonly maxConflictRows?: number; +} + +export interface OverrideSeedRow { + readonly source: string; + readonly sourceId: string; + readonly validFrom?: string; + readonly validTo?: string | null; + readonly primaryIsin: string; + readonly mic: string; + readonly tickerRoot: string; + readonly classSuffix: string; + readonly currency: string; + readonly reason: string; + readonly createdBy: string; +} + +interface NormalizedOverrideSeedRow { + readonly source: string; + readonly sourceId: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly primaryIsin: string; + readonly mic: string; + readonly tickerRoot: string; + readonly classSuffix: string; + readonly currency: string; + readonly reason: string; + readonly createdBy: string; +} + +interface CountryAccumulator { + total: number; + matched: number; + unresolved: number; + conflict: number; + excludedByDesign: number; +} + +interface SortableUnifiedConflict { + readonly row: UnifiedConflictRow; + readonly canonicalDetailJson: string; +} + +const EXCLUDED_BY_DESIGN_SET: ReadonlySet = new Set(EXCLUDED_BY_DESIGN_STAGE_B_REASONS); +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +const MAX_OVERRIDE_SOURCE_LENGTH = 16; +const MAX_OVERRIDE_SOURCE_ID_LENGTH = 64; +const MAX_PRIMARY_ISIN_LENGTH = 12; +const MAX_MIC_LENGTH = 10; +const MAX_TICKER_ROOT_LENGTH = 24; +const MAX_CLASS_SUFFIX_LENGTH = 12; +const MAX_CURRENCY_LENGTH = 3; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +/** + * Pure-integer Gregorian calendar validator for exact `YYYY-MM-DD` strings (years 0001..9999). + * Rejects timestamps, whitespace padding, and impossible dates such as `2024-02-30` or `2023-02-29`. + */ +function isValidExactYmd(value: unknown): value is string { + if (typeof value !== 'string' || !EXACT_YMD_PATTERN.test(value)) { + return false; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + if (year < 1) { + return false; + } + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + if (month < 1 || month > 12) { + return false; + } + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + return day >= 1 && day <= maxDay; +} + +function canonicalizeJsonValue(value: unknown): unknown { + if (value === null || typeof value !== 'object') { + if (typeof value === 'number' && Object.is(value, -0)) { + return 0; + } + return value; + } + if (Array.isArray(value)) { + return value.map(item => canonicalizeJsonValue(item)); + } + const sourceObj = value as Record; + const sortedKeys = Object.keys(sourceObj).sort(compareAscii); + const result: Record = {}; + for (const key of sortedKeys) { + const entry = sourceObj[key]; + if (entry !== undefined) { + result[key] = canonicalizeJsonValue(entry); + } + } + return result; +} + +function canonicalizeDetailObject(value: unknown): Record { + const canonical = canonicalizeJsonValue(value); + if (canonical !== null && typeof canonical === 'object' && !Array.isArray(canonical)) { + return canonical as Record; + } + return {}; +} + +function stableJsonStringify(value: unknown): string { + return JSON.stringify(canonicalizeJsonValue(value)); +} + +function compareNullableAscii(a: string | null, b: string | null): number { + if (a === b) { + return 0; + } + if (a === null) { + return -1; + } + if (b === null) { + return 1; + } + return compareAscii(a, b); +} + +function sortUnifiedConflicts(rows: readonly UnifiedConflictRow[]): UnifiedConflictRow[] { + const decorated: SortableUnifiedConflict[] = rows.map(row => ({ + row, + canonicalDetailJson: stableJsonStringify(row.detail), + })); + decorated.sort( + (a, b) => + compareAscii(a.row.pass, b.row.pass) || + compareAscii(a.row.conflictKind, b.row.conflictKind) || + compareNullableAscii(a.row.source, b.row.source) || + compareNullableAscii(a.row.sourceId, b.row.sourceId) || + compareAscii(a.canonicalDetailJson, b.canonicalDetailJson) + ); + return decorated.map(entry => entry.row); +} + +function escapeMarkdownCell(value: string | null | undefined): string { + if (value === null || value === undefined || value.length === 0) { + return ''; + } + return value.replaceAll('\\', '\\\\').replaceAll('|', '\\|').replaceAll(/\r\n|\r|\n/g, ' '); +} + +function escapeCsvField(value: string): string { + if ( + value.includes(',') || + value.includes('"') || + value.includes('\r') || + value.includes('\n') + ) { + return `"${value.replaceAll('"', '""')}"`; + } + return value; +} + +export function sourceCountryKey(source: string, sourceId: string): string { + return `${source}:${sourceId}`; +} + +function lookupSourceCountry( + lookup: SourceCountryLookup | undefined, + source: string, + sourceId: string +): string | null { + if (!lookup) { + return null; + } + const primaryKey = sourceCountryKey(source, sourceId); + const fallbackKey = `${source}\u0000${sourceId}`; + + let raw: string | undefined; + if (lookup instanceof Map) { + raw = lookup.get(primaryKey) ?? lookup.get(fallbackKey); + } else { + const record = lookup as Readonly>; + if (Object.prototype.hasOwnProperty.call(record, primaryKey)) { + raw = record[primaryKey]; + } else if (Object.prototype.hasOwnProperty.call(record, fallbackKey)) { + raw = record[fallbackKey]; + } + } + if (typeof raw !== 'string') { + return null; + } + const normalized = raw.trim().toUpperCase(); + return normalized.length > 0 ? normalized : null; +} + +function buildUnresolvedBreakdown( + records: readonly { readonly source: string; readonly reason: string }[] +): UnresolvedBreakdownRow[] { + const counts = new Map(); + for (const record of records) { + const key = `${record.source}\u0000${record.reason}`; + const existing = counts.get(key); + if (existing) { + existing.count += 1; + } else { + counts.set(key, { + source: record.source, + reason: record.reason, + count: 1, + }); + } + } + return Array.from(counts.values()).sort( + (a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason) + ); +} + +function buildConflictCounts(conflicts: readonly UnifiedConflictRow[]): ConflictCountRow[] { + const counts = new Map(); + for (const row of conflicts) { + const key = `${row.pass}\u0000${row.conflictKind}`; + const existing = counts.get(key); + if (existing) { + existing.count += 1; + } else { + counts.set(key, { + pass: row.pass, + conflictKind: row.conflictKind, + count: 1, + }); + } + } + return Array.from(counts.values()).sort( + (a, b) => compareAscii(a.pass, b.pass) || compareAscii(a.conflictKind, b.conflictKind) + ); +} + +function buildCountryResolution( + stageB: StageBMatchResult, + sourceCountries: SourceCountryLookup | undefined +): CountryResolutionSummary[] { + if (!sourceCountries) { + return []; + } + + const byCountry = new Map(); + const getOrCreate = (country: string): CountryAccumulator => { + let acc = byCountry.get(country); + if (!acc) { + acc = { total: 0, matched: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 }; + byCountry.set(country, acc); + } + return acc; + }; + + for (const mapping of stageB.providerMappings) { + const country = lookupSourceCountry(sourceCountries, mapping.source, mapping.sourceId); + if (country !== null) { + const acc = getOrCreate(country); + acc.total += 1; + acc.matched += 1; + } + } + + for (const record of stageB.unresolved) { + const country = lookupSourceCountry(sourceCountries, record.source, record.sourceId); + if (country !== null) { + const acc = getOrCreate(country); + acc.total += 1; + acc.unresolved += 1; + if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) { + acc.excludedByDesign += 1; + } + } + } + + for (const conflict of stageB.conflicts) { + const country = lookupSourceCountry(sourceCountries, conflict.source, conflict.sourceId); + if (country !== null) { + const acc = getOrCreate(country); + acc.total += 1; + acc.conflict += 1; + } + } + + return Array.from(byCountry.entries()) + .sort((a, b) => compareAscii(a[0], b[0])) + .map(([country, acc]) => { + const eligibleTotal = Math.max(0, acc.total - acc.excludedByDesign); + return { + country, + total: acc.total, + matched: acc.matched, + unresolved: acc.unresolved, + conflict: acc.conflict, + excludedByDesign: acc.excludedByDesign, + eligibleTotal, + resolvedPct: acc.total > 0 ? acc.matched / acc.total : null, + eligibleResolvedPct: eligibleTotal > 0 ? acc.matched / eligibleTotal : null, + }; + }); +} + +/** + * Pure in-memory aggregator for Security Master Passes 1, 3A, 3B, 4, and 6. + * + * Resolution percentage formulas: + * - `resolvedPct = total > 0 ? matched / total : null` + * - `eligibleTotal = Math.max(0, total - excludedByDesign)` where `excludedByDesign` + * counts Stage B unresolved rows with reason in + * `['excluded_fund', 'composite_venue', 'ats_routing_venue', 'forex_venue']`. + * - `eligibleResolvedPct = eligibleTotal > 0 ? matched / eligibleTotal : null` + * Zero denominators always produce `null`, never `NaN` or `Infinity`. + */ +export function buildMatchReport( + input: MatchReportInput, + options?: BuildMatchReportOptions +): MatchReport { + const minResolvedPct = options?.minResolvedPct ?? DEFAULT_MIN_RESOLVED_PCT; + if ( + typeof minResolvedPct !== 'number' || + !Number.isFinite(minResolvedPct) || + minResolvedPct < 0 || + minResolvedPct > 1 + ) { + throw new Error( + `Invalid minResolvedPct (${String(minResolvedPct)}): must be a finite number in [0, 1]` + ); + } + + const exchangeCoverage: ExchangeCoverageSummary | null = input.exchanges + ? (() => { + const mapped = input.exchanges.mapped.length; + const unresolved = input.exchanges.unresolved.length; + const total = mapped + unresolved; + return { + mapped, + unresolved, + total, + mappedPct: total > 0 ? mapped / total : null, + }; + })() + : null; + + const excludedBySource: Record = { + eod: 0, + ib: 0, + qm: 0, + ceo: 0, + }; + for (const record of input.stageB.unresolved) { + if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) { + excludedBySource[record.source] += 1; + } + } + + const resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => { + const stats = input.stageB.stats.bySource[source]; + const excludedByDesign = excludedBySource[source]; + const eligibleTotal = Math.max(0, stats.total - excludedByDesign); + return { + source, + total: stats.total, + matched: stats.matched, + unresolved: stats.unresolved, + conflict: stats.conflict, + excludedByDesign, + eligibleTotal, + resolvedPct: stats.total > 0 ? stats.matched / stats.total : null, + eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null, + }; + }); + + const resolutionByCountry = buildCountryResolution(input.stageB, input.sourceCountries); + + const unresolvedByReason: UnresolvedBreakdown = { + stageA: buildUnresolvedBreakdown(input.stageA.unresolved), + stageB: buildUnresolvedBreakdown(input.stageB.unresolved), + }; + + const rawConflicts: UnifiedConflictRow[] = []; + for (const conflict of input.stageA.conflicts) { + rawConflicts.push({ + pass: 'stage_a', + source: conflict.source, + sourceId: conflict.sourceId, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + for (const conflict of input.stageB.conflicts) { + rawConflicts.push({ + pass: 'stage_b', + source: conflict.source, + sourceId: conflict.sourceId, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + if (input.priceCrossCheck) { + for (const conflict of input.priceCrossCheck.conflicts) { + rawConflicts.push({ + pass: 'pass4', + source: conflict.source, + sourceId: conflict.sourceId, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + } + if (input.delistingChains) { + for (const conflict of input.delistingChains.conflicts) { + rawConflicts.push({ + pass: 'pass6', + source: null, + sourceId: null, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + } + + const conflicts = sortUnifiedConflicts(rawConflicts); + const conflictsByPassKind = buildConflictCounts(conflicts); + + const priceCrossCheck: PriceCrossCheckSummary | null = input.priceCrossCheck + ? { + pairsIn: input.priceCrossCheck.stats.pairsIn, + invalidPairs: input.priceCrossCheck.stats.invalidPairs, + conflictsEmitted: input.priceCrossCheck.stats.conflictsEmitted, + byVerdict: { ...input.priceCrossCheck.stats.byVerdict }, + } + : null; + + const delistingChains: DelistingChainSummary | null = input.delistingChains + ? { + totalInputListings: input.delistingChains.stats.totalInputListings, + processedListings: input.delistingChains.stats.processedListings, + continuitiesCreated: input.delistingChains.stats.continuitiesCreated, + conflictsDetected: input.delistingChains.stats.conflictsDetected, + byOutcome: { ...input.delistingChains.stats.byOutcome }, + } + : null; + + const eligibleSources = resolutionBySource.filter(row => row.total > 0 && row.eligibleTotal > 0); + const meetsExitThresholds: MatchReportExitThresholds = { + exchangesMapped100: + exchangeCoverage !== null && exchangeCoverage.mapped > 0 && exchangeCoverage.unresolved === 0, + equitiesResolved95: + eligibleSources.length > 0 && + eligibleSources.every( + row => row.eligibleResolvedPct !== null && row.eligibleResolvedPct >= minResolvedPct + ), + }; + + return { + minResolvedPct, + exchangeCoverage, + resolutionBySource, + resolutionByCountry, + unresolvedByReason, + conflicts, + conflictsByPassKind, + priceCrossCheck, + delistingChains, + meetsExitThresholds, + }; +} + +function formatPct(value: number | null): string { + if (value === null) { + return 'N/A'; + } + return `${(value * 100).toFixed(2)}%`; +} + +export function renderMatchReportMarkdown( + report: MatchReport, + options?: RenderMatchReportMarkdownOptions +): string { + const maxConflictRows = options?.maxConflictRows ?? DEFAULT_MAX_CONFLICT_ROWS; + if ( + typeof maxConflictRows !== 'number' || + !Number.isSafeInteger(maxConflictRows) || + maxConflictRows < 0 + ) { + throw new Error( + `Invalid maxConflictRows (${String(maxConflictRows)}): must be a non-negative safe integer` + ); + } + + const lines: string[] = [ + '# Security Master Match & Conflict Report', + '', + '## Exit Thresholds', + '', + '| Criterion | Status | Target |', + '| --- | --- | --- |', + `| Exchanges Mapped | ${report.meetsExitThresholds.exchangesMapped100 ? 'PASS' : 'FAIL'} | 100.00% |`, + `| Equities Resolved (Eligible) | ${report.meetsExitThresholds.equitiesResolved95 ? 'PASS' : 'FAIL'} | >= ${formatPct(report.minResolvedPct)} |`, + '', + '## Exchange Coverage', + '', + '| Mapped | Unresolved | Total | Mapped % |', + '| --- | --- | --- | --- |', + ]; + + if (report.exchangeCoverage) { + lines.push( + `| ${report.exchangeCoverage.mapped} | ${report.exchangeCoverage.unresolved} | ${report.exchangeCoverage.total} | ${formatPct(report.exchangeCoverage.mappedPct)} |` + ); + } else { + lines.push('| 0 | 0 | 0 | N/A |'); + } + + lines.push( + '', + '## Per-Source Resolution', + '', + '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', + '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' + ); + + for (const row of report.resolutionBySource) { + lines.push( + `| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` + ); + } + + if (report.resolutionByCountry.length > 0) { + lines.push( + '', + '## Per-Country Resolution', + '', + '| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', + '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' + ); + for (const row of report.resolutionByCountry) { + lines.push( + `| ${escapeMarkdownCell(row.country)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` + ); + } + } + + lines.push( + '', + '## Unresolved by Reason', + '', + '### Stage A', + '', + '| Source | Reason | Count |', + '| --- | --- | --- |' + ); + + if (report.unresolvedByReason.stageA.length === 0) { + lines.push('| (none) | (none) | 0 |'); + } else { + const sortedStageA = [...report.unresolvedByReason.stageA].sort( + (a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason) + ); + for (const row of sortedStageA) { + lines.push( + `| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |` + ); + } + } + + lines.push('', '### Stage B', '', '| Source | Reason | Count |', '| --- | --- | --- |'); + + if (report.unresolvedByReason.stageB.length === 0) { + lines.push('| (none) | (none) | 0 |'); + } else { + const sortedStageB = [...report.unresolvedByReason.stageB].sort( + (a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason) + ); + for (const row of sortedStageB) { + lines.push( + `| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |` + ); + } + } + + lines.push( + '', + '## Conflicts by Pass & Kind', + '', + '| Pass | Conflict Kind | Count |', + '| --- | --- | --- |' + ); + + if (report.conflictsByPassKind.length === 0) { + lines.push('| (none) | (none) | 0 |'); + } else { + const sortedCounts = [...report.conflictsByPassKind].sort( + (a, b) => compareAscii(a.pass, b.pass) || compareAscii(a.conflictKind, b.conflictKind) + ); + for (const row of sortedCounts) { + lines.push( + `| ${escapeMarkdownCell(row.pass)} | ${escapeMarkdownCell(row.conflictKind)} | ${row.count} |` + ); + } + } + + lines.push( + '', + '## Pass 4 Price Cross-Check Verdicts', + '', + `- Pairs In: ${report.priceCrossCheck?.pairsIn ?? 0}`, + `- Invalid Pairs: ${report.priceCrossCheck?.invalidPairs ?? 0}`, + `- Conflicts Emitted: ${report.priceCrossCheck?.conflictsEmitted ?? 0}`, + '', + '| Verdict | Count |', + '| --- | --- |' + ); + + for (const verdict of PRICE_CROSS_CHECK_VERDICTS) { + const count = report.priceCrossCheck?.byVerdict[verdict] ?? 0; + lines.push(`| ${escapeMarkdownCell(verdict)} | ${count} |`); + } + + lines.push( + '', + '## Pass 6 Delisting Chain Outcomes', + '', + `- Total Input Listings: ${report.delistingChains?.totalInputListings ?? 0}`, + `- Processed Listings: ${report.delistingChains?.processedListings ?? 0}`, + `- Continuities Created: ${report.delistingChains?.continuitiesCreated ?? 0}`, + `- Conflicts Detected: ${report.delistingChains?.conflictsDetected ?? 0}`, + '', + '| Outcome | Count |', + '| --- | --- |' + ); + + for (const outcome of DELIST_REASONS) { + const count = report.delistingChains?.byOutcome[outcome] ?? 0; + lines.push(`| ${escapeMarkdownCell(outcome)} | ${count} |`); + } + + const sortedConflicts = sortUnifiedConflicts(report.conflicts); + const sample = sortedConflicts.slice(0, maxConflictRows); + + lines.push('', '## Conflict Sample', ''); + + if (sortedConflicts.length === 0) { + lines.push('No open conflicts (0 total).'); + } else { + lines.push( + '| Pass | Source | Source ID | Conflict Kind | Detail |', + '| --- | --- | --- | --- | --- |' + ); + for (const row of sample) { + lines.push( + `| ${escapeMarkdownCell(row.pass)} | ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.sourceId)} | ${escapeMarkdownCell(row.conflictKind)} | ${escapeMarkdownCell(stableJsonStringify(row.detail))} |` + ); + } + const remaining = sortedConflicts.length - sample.length; + lines.push(''); + if (remaining > 0) { + lines.push( + `Showing ${sample.length} of ${sortedConflicts.length} conflicts (${remaining} more in CSV).` + ); + } else { + lines.push(`Showing ${sample.length} of ${sortedConflicts.length} conflicts.`); + } + } + + lines.push(''); + return lines.join('\n'); +} + +export function renderConflictsCsv(report: MatchReport): string { + const sortedConflicts = sortUnifiedConflicts(report.conflicts); + const lines: string[] = ['pass,source,source_id,conflict_kind,detail_json']; + + for (const row of sortedConflicts) { + lines.push( + [ + escapeCsvField(row.pass), + escapeCsvField(row.source ?? ''), + escapeCsvField(row.sourceId ?? ''), + escapeCsvField(row.conflictKind), + escapeCsvField(stableJsonStringify(row.detail)), + ].join(',') + ); + } + + return `${lines.join('\r\n')}\r\n`; +} + +function assertNoNul(value: string, fieldName: string): void { + if (value.includes('\0')) { + throw new Error(`Invalid override row: ${fieldName} must not contain NUL bytes`); + } +} + +function validateRequiredStringField( + value: unknown, + fieldName: string, + maxLength?: number +): string { + if (typeof value !== 'string') { + throw new Error(`Invalid override row: ${fieldName} must be a string`); + } + assertNoNul(value, fieldName); + if (value.trim().length === 0) { + throw new Error(`Invalid override row: ${fieldName} must not be empty`); + } + if (maxLength !== undefined && value.length > maxLength) { + throw new Error( + `Invalid override row: ${fieldName} length (${value.length}) exceeds maximum of ${maxLength} characters` + ); + } + return value; +} + +function validateOptionalEmptyStringField( + value: unknown, + fieldName: string, + maxLength: number +): string { + if (typeof value !== 'string') { + throw new Error(`Invalid override row: ${fieldName} must be a string`); + } + assertNoNul(value, fieldName); + if (value.length > maxLength) { + throw new Error( + `Invalid override row: ${fieldName} length (${value.length}) exceeds maximum of ${maxLength} characters` + ); + } + return value; +} + +function validateOverrideRow(row: OverrideSeedRow): NormalizedOverrideSeedRow { + const source = validateRequiredStringField(row.source, 'source', MAX_OVERRIDE_SOURCE_LENGTH); + const sourceId = validateRequiredStringField( + row.sourceId, + 'sourceId', + MAX_OVERRIDE_SOURCE_ID_LENGTH + ); + const primaryIsin = validateRequiredStringField( + row.primaryIsin, + 'primaryIsin', + MAX_PRIMARY_ISIN_LENGTH + ); + const mic = validateRequiredStringField(row.mic, 'mic', MAX_MIC_LENGTH); + const tickerRoot = validateRequiredStringField( + row.tickerRoot, + 'tickerRoot', + MAX_TICKER_ROOT_LENGTH + ); + const classSuffix = validateOptionalEmptyStringField( + row.classSuffix, + 'classSuffix', + MAX_CLASS_SUFFIX_LENGTH + ); + const currency = validateRequiredStringField(row.currency, 'currency', MAX_CURRENCY_LENGTH); + const reason = validateRequiredStringField(row.reason, 'reason'); + const createdBy = validateRequiredStringField(row.createdBy, 'createdBy'); + + const rawValidFrom = row.validFrom ?? DEFAULT_OVERRIDE_VALID_FROM; + if (typeof rawValidFrom !== 'string') { + throw new Error('Invalid override row: validFrom must be a YYYY-MM-DD string'); + } + assertNoNul(rawValidFrom, 'validFrom'); + if (!isValidExactYmd(rawValidFrom)) { + throw new Error( + `Invalid override row: validFrom "${rawValidFrom}" must be a real YYYY-MM-DD calendar date` + ); + } + + let validTo: string | null = null; + if (row.validTo !== undefined && row.validTo !== null) { + if (typeof row.validTo !== 'string') { + throw new Error('Invalid override row: validTo must be a YYYY-MM-DD string or null'); + } + assertNoNul(row.validTo, 'validTo'); + if (!isValidExactYmd(row.validTo)) { + throw new Error( + `Invalid override row: validTo "${row.validTo}" must be a real YYYY-MM-DD calendar date` + ); + } + if (compareAscii(row.validTo, rawValidFrom) < 0) { + throw new Error( + `Invalid override row: validTo "${row.validTo}" must be >= validFrom "${rawValidFrom}"` + ); + } + validTo = row.validTo; + } + + return { + source, + sourceId, + validFrom: rawValidFrom, + validTo, + primaryIsin, + mic, + tickerRoot, + classSuffix, + currency, + reason, + createdBy, + }; +} + +function deduplicateOverrideRows(rows: readonly OverrideSeedRow[]): NormalizedOverrideSeedRow[] { + const byKey = new Map(); + for (const rawRow of rows) { + const row = validateOverrideRow(rawRow); + const key = `${row.source}\u0000${row.sourceId}\u0000${row.validFrom}`; + const existing = byKey.get(key); + if (!existing) { + byKey.set(key, row); + continue; + } + if ( + existing.validTo !== row.validTo || + existing.primaryIsin !== row.primaryIsin || + existing.mic !== row.mic || + existing.tickerRoot !== row.tickerRoot || + existing.classSuffix !== row.classSuffix || + existing.currency !== row.currency || + existing.reason !== row.reason || + existing.createdBy !== row.createdBy + ) { + throw new Error( + `Conflicting duplicate override row for (${row.source}, "${row.sourceId}", ${row.validFrom})` + ); + } + } + return Array.from(byKey.values()).sort( + (a, b) => + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.validFrom, b.validFrom) + ); +} + +export function generateOverrideSeedSql(rows: readonly OverrideSeedRow[]): string { + const normalized = deduplicateOverrideRows(rows); + + const sections: string[] = [ + [ + '-- Security master override seed (M1.1i)', + '-- Generated deterministically by apps/stock/data-pipeline/src/security-master/match-report.ts.', + '-- Resolves target listings by natural key in the active search_path; idempotent via ON CONFLICT DO NOTHING.', + ].join('\n'), + ]; + + for (const row of normalized) { + const validToSql = row.validTo === null ? 'NULL' : `DATE '${row.validTo}'`; + sections.push( + [ + 'INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)', + 'SELECT', + ` ${escapeSqlLiteral(row.source)},`, + ` ${escapeSqlLiteral(row.sourceId)},`, + ` DATE '${row.validFrom}',`, + ` ${validToSql},`, + ' l.listing_id,', + ` ${escapeSqlLiteral(row.reason)},`, + ` ${escapeSqlLiteral(row.createdBy)}`, + 'FROM listing l', + 'JOIN instrument i ON i.instrument_id = l.instrument_id', + `WHERE i.primary_isin = ${escapeSqlLiteral(row.primaryIsin)}`, + ` AND l.mic = ${escapeSqlLiteral(row.mic)}`, + ` AND l.ticker_root = ${escapeSqlLiteral(row.tickerRoot)}`, + ` AND l.class_suffix = ${escapeSqlLiteral(row.classSuffix)}`, + ` AND l.currency = ${escapeSqlLiteral(row.currency)}`, + 'ORDER BY l.listing_id', + 'LIMIT 1', + 'ON CONFLICT (source, source_id, valid_from) DO NOTHING;', + ].join('\n') + ); + } + + return `${sections.join('\n\n')}\n`; +} + +function sanitizeTemplateSingleLine(value: string): string { + return value.replaceAll('\0', '').replaceAll(/\r\n|\r|\n/g, ' '); +} + +function commentOutSqlBlock(lines: readonly string[]): string { + return lines + .flatMap(line => line.split(/\r\n|\r|\n/)) + .map(line => `-- ${line}`) + .join('\n'); +} + +export function generateOverrideTemplateSql(report: MatchReport): string { + const sortedConflicts = sortUnifiedConflicts(report.conflicts).filter( + (row): row is UnifiedConflictRow & { source: string; sourceId: string } => + row.source !== null && row.sourceId !== null + ); + + const sections: string[] = [ + [ + '-- Security master override review template (M1.1i)', + '-- Generated deterministically by apps/stock/data-pipeline/src/security-master/match-report.ts.', + '-- Review open conflicts below, uncomment a statement, and fill in the target listing natural key to apply.', + '-- Nothing in this file is auto-applied.', + ].join('\n'), + ]; + + if (sortedConflicts.length === 0) { + sections.push('-- No source-attributed open conflicts.'); + return `${sections.join('\n\n')}\n`; + } + + for (const conflict of sortedConflicts) { + const safeSource = sanitizeTemplateSingleLine(conflict.source); + const safeSourceId = sanitizeTemplateSingleLine(conflict.sourceId); + const safeKind = sanitizeTemplateSingleLine(conflict.conflictKind); + const safePass = sanitizeTemplateSingleLine(conflict.pass); + + sections.push( + commentOutSqlBlock([ + `Conflict: pass=${safePass} kind=${safeKind} source=${safeSource} source_id=${safeSourceId}`, + 'INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)', + 'SELECT', + ` ${escapeSqlLiteral(safeSource)},`, + ` ${escapeSqlLiteral(safeSourceId)},`, + ` DATE '${DEFAULT_OVERRIDE_VALID_FROM}',`, + ' NULL,', + ' l.listing_id,', + ` ${escapeSqlLiteral(`TODO: explain resolution for ${safeKind}`)},`, + ` ${escapeSqlLiteral('TODO: reviewer')}`, + 'FROM listing l', + 'JOIN instrument i ON i.instrument_id = l.instrument_id', + "WHERE i.primary_isin = 'TODO_ISIN_12'", + " AND l.mic = 'TODO_MIC'", + " AND l.ticker_root = 'TODO_TICKER'", + " AND l.class_suffix = ''", + " AND l.currency = 'USD'", + 'ORDER BY l.listing_id', + 'LIMIT 1', + 'ON CONFLICT (source, source_id, valid_from) DO NOTHING;', + ]) + ); + } + + return `${sections.join('\n\n')}\n`; +} diff --git a/test/postgres/security-master-override-seed.test.ts b/test/postgres/security-master-override-seed.test.ts new file mode 100644 index 00000000..e26647ea --- /dev/null +++ b/test/postgres/security-master-override-seed.test.ts @@ -0,0 +1,225 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + buildMatchReport, + generateOverrideSeedSql, + generateOverrideTemplateSql, + type OverrideSeedRow, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-override-seed-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'master' }); + + return { pool, schema, postgres }; +} + +async function seedSingleListing(pool: Pool): Promise { + const instrumentResult = await pool.query<{ instrument_id: number }>( + `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) + VALUES ('US0378331005', '037833100', 'Apple Inc.', 'common', 'US') + RETURNING instrument_id` + ); + const instrumentId = instrumentResult.rows[0]?.instrument_id; + if (instrumentId === undefined) { + throw new Error('Failed to insert fixture instrument'); + } + + const listingResult = await pool.query<{ listing_id: number }>( + `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) + VALUES ($1, 'XNAS', 'AAPL', '', 'USD') + RETURNING listing_id`, + [instrumentId] + ); + const listingId = listingResult.rows[0]?.listing_id; + if (listingId === undefined) { + throw new Error('Failed to insert fixture listing'); + } + return listingId; +} + +describe.skipIf(!url)('security master override seed SQL', () => { + test('inserts matching override row with resolved listing_id and is idempotent on re-run', async () => { + const f = await createIsolatedFixture(); + const expectedListingId = await seedSingleListing(f.pool); + + const row: 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', + }; + + const sql = generateOverrideSeedSql([row]); + + // First run inserts exactly one row with the resolved listing_id + await f.pool.query(sql); + + const rowsAfterFirst = ( + await f.pool.query<{ + source: string; + source_id: string; + valid_from: string; + valid_to: string | null; + listing_id: number; + reason: string; + created_by: string; + }>( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, reason, created_by + FROM override` + ) + ).rows; + + expect(rowsAfterFirst).toEqual([ + { + source: 'eod', + source_id: 'AAPL.US', + valid_from: '2020-01-15', + valid_to: '2025-12-31', + listing_id: expectedListingId, + reason: "O'Brien fix", + created_by: 'director', + }, + ]); + + // Second run is a no-op via ON CONFLICT (source, source_id, valid_from) DO NOTHING + await f.pool.query(sql); + + const countAfterSecond = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(countAfterSecond).toBe(1); + }); + + test('natural key matching no listing inserts nothing and raises no error', async () => { + const f = await createIsolatedFixture(); + await seedSingleListing(f.pool); + + const sql = generateOverrideSeedSql([ + { + source: 'qm', + sourceId: 'MISSING:US', + validFrom: '1900-01-01', + validTo: null, + primaryIsin: 'US9999999999', + mic: 'XNAS', + tickerRoot: 'MISSING', + classSuffix: '', + currency: 'USD', + reason: 'Non-existent listing test', + createdBy: 'director', + }, + ]); + + await f.pool.query(sql); + + const count = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(count).toBe(0); + }); + + test('empty seed SQL and template SQL execute cleanly without inserting rows', async () => { + const f = await createIsolatedFixture(); + await seedSingleListing(f.pool); + + const emptySql = generateOverrideSeedSql([]); + await f.pool.query(emptySql); + + const report = buildMatchReport({ + stageA: { + instruments: [], + unresolved: [], + conflicts: [ + { + source: 'eod', + sourceId: 'AAPL.US', + conflictKind: 'isin_cusip_mismatch', + detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, + }, + ], + stats: { + totalInputRecords: 1, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, + }, + }, + }, + stageB: { + 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 }, + }, + }, + }, + }); + + const templateSql = generateOverrideTemplateSql(report); + await f.pool.query(templateSql); + + const count = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(count).toBe(0); + }); +}); diff --git a/test/unit/security-master-match-report.test.ts b/test/unit/security-master-match-report.test.ts new file mode 100644 index 00000000..1e957111 --- /dev/null +++ b/test/unit/security-master-match-report.test.ts @@ -0,0 +1,1036 @@ +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('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, includes only source-attributed conflicts, and neutralizes newlines', () => { + const conflicts: UnifiedConflictRow[] = [ + { + pass: 'stage_a', + source: 'eod', + sourceId: 'BAD\nDROP TABLE override;--', + 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(3); + expect(templateSql).not.toContain('ambiguous_otc_continuation'); + + // 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'); + }); +});