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 (requires a unique match; 0 matches is a no-op, >1 match raises cardinality_violation); 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},`, ' matched.listing_id,', ` ${escapeSqlLiteral(row.reason)},`, ` ${escapeSqlLiteral(row.createdBy)}`, 'FROM (', ' SELECT (', ' SELECT l.listing_id', ' 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)}`, ' ) AS listing_id', ') AS matched', 'WHERE matched.listing_id IS NOT NULL', 'ON CONFLICT (source, source_id, valid_from) DO NOTHING;', ].join('\n') ); } return `${sections.join('\n\n')}\n`; } function formatTemplateCommentValue(value: string): string { return value .replaceAll('\\', '\\\\') .replaceAll('\0', '\\u0000') .replaceAll('\r', '\\r') .replaceAll('\n', '\\n'); } function formatSingleLineSqlLiteral(value: string): string { if (value.includes('\0')) { throw new Error('SQL literal value must not contain NUL bytes'); } if (!value.includes('\r') && !value.includes('\n')) { return escapeSqlLiteral(value); } const escaped = value .replaceAll('\\', '\\\\') .replaceAll("'", "''") .replaceAll('\r', '\\r') .replaceAll('\n', '\\n'); return `E'${escaped}'`; } function getUnstorableTemplateIdReasons(value: string, maxLength: number): string[] { const reasons: string[] = []; if (value.includes('\0')) { reasons.push('contains NUL byte'); } if (value.trim().length === 0) { reasons.push('is empty or whitespace-only'); } if (value.length > maxLength) { reasons.push(`length (${value.length}) exceeds ${maxLength}-character limit`); } return reasons; } 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.', '-- Requires a unique natural-key match (0 matches is a no-op, >1 match raises cardinality_violation).', '-- 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 commentSource = formatTemplateCommentValue(conflict.source); const commentSourceId = formatTemplateCommentValue(conflict.sourceId); const commentKind = formatTemplateCommentValue(conflict.conflictKind); const commentPass = formatTemplateCommentValue(conflict.pass); const sourceIssues = getUnstorableTemplateIdReasons(conflict.source, MAX_OVERRIDE_SOURCE_LENGTH); const sourceIdIssues = getUnstorableTemplateIdReasons( conflict.sourceId, MAX_OVERRIDE_SOURCE_ID_LENGTH ); const sourceSqlLiteral = sourceIssues.length === 0 ? formatSingleLineSqlLiteral(conflict.source) : 'NULL /* TODO: replace with valid source */'; const sourceIdSqlLiteral = sourceIdIssues.length === 0 ? formatSingleLineSqlLiteral(conflict.sourceId) : 'NULL /* TODO: replace with valid source_id */'; const blockLines: string[] = [ `Conflict: pass=${commentPass} kind=${commentKind} source=${commentSource} source_id=${commentSourceId}`, ]; if (sourceIssues.length > 0) { blockLines.push( `WARNING: Cannot store raw source in PostgreSQL (${sourceIssues.join('; ')}); correct source before applying.` ); } if (sourceIdIssues.length > 0) { blockLines.push( `WARNING: Cannot store raw source_id in PostgreSQL (${sourceIdIssues.join('; ')}); correct source_id before applying.` ); } blockLines.push( 'INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)', 'SELECT', ` ${sourceSqlLiteral},`, ` ${sourceIdSqlLiteral},`, ` DATE '${DEFAULT_OVERRIDE_VALID_FROM}',`, ' NULL,', ' matched.listing_id,', ` ${formatSingleLineSqlLiteral(`TODO: explain resolution for ${commentKind}`)},`, ` ${escapeSqlLiteral('TODO: reviewer')}`, 'FROM (', ' SELECT (', ' SELECT l.listing_id', ' 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'", ' ) AS listing_id', ') AS matched', 'WHERE matched.listing_id IS NOT NULL', 'ON CONFLICT (source, source_id, valid_from) DO NOTHING;' ); sections.push(commentOutSqlBlock(blockLines)); } return `${sections.join('\n\n')}\n`; }