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:10:09 -05:00
parent e2e2bfdd6d
commit cbabb17094
4 changed files with 2392 additions and 0 deletions

View file

@ -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,

File diff suppressed because it is too large Load diff

View file

@ -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> | 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<number> {
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);
});
});

File diff suppressed because it is too large Load diff