T-74: M1.1i — Pass 3/4/6 match & conflict report: pure in-memory Markdown + CSV generator and override seed-SQL template (no DB I/O)

This commit is contained in:
Studio 2026-11-27 21:18:56 -05:00
parent cbabb17094
commit 83ec301220
3 changed files with 251 additions and 43 deletions

View file

@ -998,7 +998,7 @@ export function generateOverrideSeedSql(rows: readonly OverrideSeedRow[]): strin
[
'-- 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.',
'-- 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'),
];
@ -1012,18 +1012,22 @@ export function generateOverrideSeedSql(rows: readonly OverrideSeedRow[]): strin
` ${escapeSqlLiteral(row.sourceId)},`,
` DATE '${row.validFrom}',`,
` ${validToSql},`,
' l.listing_id,',
' matched.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',
'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')
);
@ -1032,8 +1036,41 @@ export function generateOverrideSeedSql(rows: readonly OverrideSeedRow[]): strin
return `${sections.join('\n\n')}\n`;
}
function sanitizeTemplateSingleLine(value: string): string {
return value.replaceAll('\0', '').replaceAll(/\r\n|\r|\n/g, ' ');
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 {
@ -1054,6 +1091,7 @@ export function generateOverrideTemplateSql(report: MatchReport): 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'),
];
@ -1064,35 +1102,67 @@ export function generateOverrideTemplateSql(report: MatchReport): string {
}
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);
const commentSource = formatTemplateCommentValue(conflict.source);
const commentSourceId = formatTemplateCommentValue(conflict.sourceId);
const commentKind = formatTemplateCommentValue(conflict.conflictKind);
const commentPass = formatTemplateCommentValue(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;',
])
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)
: "'TODO_CORRECT_SOURCE'";
const sourceIdSqlLiteral =
sourceIdIssues.length === 0
? formatSingleLineSqlLiteral(conflict.sourceId)
: "'TODO_CORRECT_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`;

View file

@ -166,6 +166,56 @@ describe.skipIf(!url)('security master override seed SQL', () => {
expect(count).toBe(0);
});
test('duplicate natural key raises cardinality_violation and inserts no override row', async () => {
const f = await createIsolatedFixture();
await seedSingleListing(f.pool);
// Insert a second listing row with the same natural key (e.g., different listing dates)
const instrumentResult = await f.pool.query<{ instrument_id: number }>(
`SELECT instrument_id FROM instrument WHERE primary_isin = 'US0378331005'`
);
const instrumentId = instrumentResult.rows[0]?.instrument_id;
if (instrumentId === undefined) {
throw new Error('Expected fixture instrument');
}
await f.pool.query(
`INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency, listed_from)
VALUES ($1, 'XNAS', 'AAPL', '', 'USD', DATE '2022-01-03')`,
[instrumentId]
);
const sql = generateOverrideSeedSql([
{
source: 'eod',
sourceId: 'AAPL.US',
validFrom: '2020-01-15',
validTo: null,
primaryIsin: 'US0378331005',
mic: 'XNAS',
tickerRoot: 'AAPL',
classSuffix: '',
currency: 'USD',
reason: 'Ambiguous natural key test',
createdBy: 'director',
},
]);
let caughtError: unknown;
try {
await f.pool.query(sql);
} catch (err) {
caughtError = err;
}
expect(caughtError).toBeDefined();
expect((caughtError as { code?: string }).code).toBe('21000');
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);
@ -222,4 +272,71 @@ describe.skipIf(!url)('security master override seed SQL', () => {
).rows[0]?.count;
expect(count).toBe(0);
});
test('uncommented template candidate with CR/LF source_id preserves the exact ID in PostgreSQL', async () => {
const f = await createIsolatedFixture();
const expectedListingId = await seedSingleListing(f.pool);
const rawSourceId = "AAPL\r\nLINE2'\\END";
const report = buildMatchReport({
stageA: {
instruments: [],
unresolved: [],
conflicts: [
{
source: 'eod',
sourceId: rawSourceId,
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);
const candidateLines = templateSql
.split('\n')
.slice(templateSql.split('\n').findIndex(line => line === '-- INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)'))
.filter(line => line.startsWith('-- '))
.map(line => line.slice(3))
.join('\n')
.replace("'TODO_ISIN_12'", "'US0378331005'")
.replace("'TODO_MIC'", "'XNAS'")
.replace("'TODO_TICKER'", "'AAPL'");
await f.pool.query(candidateLines);
const inserted = (
await f.pool.query<{ source_id: string; listing_id: number }>(
'SELECT source_id, listing_id FROM override'
)
).rows;
expect(inserted).toEqual([{ source_id: rawSourceId, listing_id: expectedListingId }]);
});
});

View file

@ -913,6 +913,9 @@ describe('generateOverrideSeedSql & generateOverrideTemplateSql', () => {
expect(sql).toContain("AND l.ticker_root = 'AAPL'");
expect(sql).toContain("AND l.class_suffix = ''");
expect(sql).toContain("AND l.currency = 'USD'");
expect(sql).toContain('WHERE matched.listing_id IS NOT NULL');
expect(sql).not.toContain('ORDER BY l.listing_id');
expect(sql).not.toContain('LIMIT 1');
expect(sql).toContain('ON CONFLICT (source, source_id, valid_from) DO NOTHING;');
// Default validFrom and null validTo
@ -973,12 +976,19 @@ describe('generateOverrideSeedSql & generateOverrideTemplateSql', () => {
).toThrow(/Conflicting duplicate/);
});
test('generateOverrideTemplateSql comments out every non-blank line, includes only source-attributed conflicts, and neutralizes newlines', () => {
test('generateOverrideTemplateSql comments out every non-blank line, preserves CR/LF via E-string literals, warns on unstorable IDs, and omits Pass 6 conflicts', () => {
const conflicts: UnifiedConflictRow[] = [
{
pass: 'stage_a',
source: 'eod',
sourceId: 'BAD\nDROP TABLE override;--',
sourceId: "BAD\r\nDROP'\\TABLE override;--",
conflictKind: 'isin_cusip_mismatch',
detail: {},
},
{
pass: 'stage_a',
source: 'eod',
sourceId: 'UNSTORABLE\0ID',
conflictKind: 'isin_cusip_mismatch',
detail: {},
},
@ -1019,8 +1029,19 @@ describe('generateOverrideSeedSql & generateOverrideTemplateSql', () => {
}
const commentedInserts = templateSql.match(/-- INSERT INTO override/g) ?? [];
expect(commentedInserts.length).toBe(3);
expect(commentedInserts.length).toBe(4);
expect(templateSql).not.toContain('ambiguous_otc_continuation');
expect(templateSql).not.toContain('ORDER BY l.listing_id');
expect(templateSql).not.toContain('LIMIT 1');
expect(templateSql).toContain('-- WHERE matched.listing_id IS NOT NULL');
// CR/LF source_id is preserved via a single-line PostgreSQL E'...' literal
expect(templateSql).toContain("-- E'BAD\\r\\nDROP''\\\\TABLE override;--',");
// Unstorable NUL-byte source_id gets a diagnostic warning and placeholder instead of silent mangling
expect(templateSql).toContain(
'-- WARNING: Cannot store raw source_id in PostgreSQL (contains NUL byte); correct source_id before applying.'
);
expect(templateSql).toContain("-- 'TODO_CORRECT_SOURCE_ID',");
// Empty conflicts report still produces only comments
const emptyTemplate = generateOverrideTemplateSql(