stock-bot/test/postgres/security-master-persist.test.ts

1077 lines
34 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool, type PoolClient } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
DEFAULT_OTC_MICS,
formatListingNaturalKey,
linkDelistingChains,
matchInstrumentsStageA,
matchListingsStageB,
persistSecurityMaster,
type DelistingChainResult,
type SecurityMasterQueryable,
type SecurityType,
type StageAMatchResult,
type StageBMatchResult,
} from '../../apps/stock/data-pipeline/src/security-master';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('security-master-persist-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(statementTimeoutMs = 15_000) {
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=${statementTimeoutMs} -c lock_timeout=15000`,
});
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 withClient<T>(pool: Pool, fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
return await fn(client);
} finally {
client.release();
}
}
async function getSevenTableCounts(pool: Pool): Promise<Record<string, number>> {
const tables = [
'instrument',
'instrument_identifier_history',
'listing',
'listing_symbol_history',
'provider_mapping',
'resolution_conflict',
'corporate_action_continuity',
] as const;
const counts: Record<string, number> = {};
for (const table of tables) {
const res = await pool.query<{ count: number }>(`SELECT count(*)::int AS count FROM ${table}`);
counts[table] = res.rows[0]?.count ?? -1;
}
return counts;
}
/**
* Builds the canonical M1 exit-criterion fixture through the real Stage A -> Stage B -> Pass 6
* matchers:
* - AAPL (`US0378331005`) on XNAS with IB conid + EOD + QM mappings
* - FB (`US30303M1027`, 2012-2022 common) vs FB (`US4642872000`, 2025 ETF) on XNAS
* - SIVB (`US78486Q1013`) XNAS -> SIVBQ OTCM delisting continuity
* - SHOP (`CA82509L1076`) interlisted XTSE (CAD) + XNYS (USD)
* - Stage A conflict (`isin_cusip_mismatch`) + Stage B conflict (`ambiguous_ticker_span`)
*/
function buildExitCriterionFixture() {
const stageA = matchInstrumentsStageA([
{
source: 'ib',
sourceId: '265598',
isin: 'US0378331005',
cusip: '037833100',
country: 'US',
currency: 'USD',
name: 'Apple Inc.',
},
{
source: 'eod',
sourceId: 'AAPL.US',
isin: 'US0378331005',
cusip: '037833100',
country: 'US',
currency: 'USD',
name: 'Apple Inc',
},
{
source: 'eod',
sourceId: 'FB_OLD.US',
isin: 'US30303M1027',
cusip: '30303M102',
country: 'US',
currency: 'USD',
name: 'Meta Platforms Inc.',
},
{
source: 'eod',
sourceId: 'FB_ETF.US',
isin: 'US4642872000',
cusip: '464287200',
country: 'US',
currency: 'USD',
name: 'FB Thematic ETF',
},
{
source: 'eod',
sourceId: 'SIVB.US',
isin: 'US78486Q1013',
cusip: '78486Q101',
country: 'US',
currency: 'USD',
name: 'SVB Financial Group',
},
{
source: 'eod',
sourceId: 'SIVBQ.US',
isin: 'US78486Q1013',
cusip: '78486Q101',
country: 'US',
currency: 'USD',
name: 'SVB Financial Group',
},
{
source: 'eod',
sourceId: 'SHOP.TO',
isin: 'CA82509L1076',
cusip: '82509L107',
country: 'CA',
currency: 'CAD',
name: 'Shopify Inc.',
},
{
source: 'eod',
sourceId: 'SHOP.US',
isin: 'CA82509L1076',
cusip: '82509L107',
country: 'US',
currency: 'USD',
name: 'Shopify Inc.',
},
// Stage A conflict: mismatched ISIN vs CUSIP
{
source: 'eod',
sourceId: 'BAD_ISIN.US',
isin: 'US0378331005',
cusip: '30303M102',
country: 'US',
currency: 'USD',
name: 'Mismatched Corp',
},
]);
const stageB = matchListingsStageB({
instruments: stageA.instruments,
eodListings: [
{
sourceId: 'AAPL.US',
ticker: 'AAPL',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '1980-12-12', lastBarDate: '2026-11-27' },
},
{
sourceId: 'FB_OLD.US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' },
},
{
sourceId: 'FB_ETF.US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2025-01-15', lastBarDate: '2026-11-27' },
},
{
sourceId: 'SIVB.US',
ticker: 'SIVB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '1987-10-26', lastBarDate: '2023-03-10' },
},
{
sourceId: 'SIVBQ.US',
ticker: 'SIVBQ',
mic: 'OTCM',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2023-03-28', lastBarDate: '2024-11-07' },
},
{
sourceId: 'SHOP.TO',
ticker: 'SHOP',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2015-05-21', lastBarDate: '2026-11-27' },
},
{
sourceId: 'SHOP.US',
ticker: 'SHOP',
mic: 'XNYS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2015-05-21', lastBarDate: '2026-11-27' },
},
],
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: '2010-01-04', lastBarDate: '2026-11-27' },
},
{
source: 'ceo',
sourceId: 'SHOP:TSX',
ticker: 'SHOP',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2016-01-04', lastBarDate: '2026-11-27' },
},
// Stage B conflict: ambiguous_ticker_span spanning both FB listings
{
source: 'qm',
sourceId: 'FB:US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' },
},
],
});
const pass6 = linkDelistingChains(
{ listings: stageB.listings, otcMics: DEFAULT_OTC_MICS },
{ asOfDate: '2026-11-27' }
);
const securityTypeByIsin = new Map<string, SecurityType>([
['US0378331005', 'common'],
['US30303M1027', 'common'],
['US4642872000', 'etf'],
['US78486Q1013', 'common'],
['CA82509L1076', 'common'],
]);
return { stageA, stageB, pass6, securityTypeByIsin };
}
function buildSyntheticBenchmarkInput(instrumentCount: number): {
stageA: StageAMatchResult;
stageB: StageBMatchResult;
securityTypeByIsin: Map<string, SecurityType>;
} {
const instruments: StageAMatchResult['instruments'] = [];
const listings: StageBMatchResult['listings'] = [];
const providerMappings: StageBMatchResult['providerMappings'] = [];
const securityTypeByIsin = new Map<string, SecurityType>();
const mics = ['XNAS', 'XNYS', 'ARCX', 'XTSE'] as const;
for (let i = 0; i < instrumentCount; i++) {
const seq = String(i).padStart(9, '0');
const mic = mics[i % mics.length] ?? 'XNAS';
const isCanada = mic === 'XTSE';
const country = isCanada ? 'CA' : 'US';
const currency = isCanada ? 'CAD' : 'USD';
const isin = `${country}${seq}0`;
const tickerRoot = `S${i}`;
instruments.push({
primaryIsin: isin,
primaryCusip: null,
issuerCountry: country,
canonicalName: `Synthetic Issuer ${i}`,
members: [{ source: 'eod', sourceId: `${tickerRoot}.${country}`, currency, method: 'tier1_isin' }],
});
securityTypeByIsin.set(isin, i % 10 === 0 ? 'etf' : 'common');
const listingKey = {
primaryIsin: isin,
mic,
tickerRoot,
classSuffix: '',
currency,
};
listings.push({
...listingKey,
ibConid: 1_000_000 + i,
ibPrimaryExchange: isCanada ? 'TSE' : 'NASDAQ',
listedFrom: '2015-01-02',
listedTo: null,
});
// 3 provider mappings per listing -> 60,000 mappings for 20,000 instruments
providerMappings.push(
{
source: 'eod',
sourceId: `${tickerRoot}.${country}`,
listingKey,
method: 'tier1_isin',
validFrom: null,
validTo: null,
},
{
source: 'ib',
sourceId: String(1_000_000 + i),
listingKey,
method: 'tier1_isin',
validFrom: null,
validTo: null,
},
{
source: 'qm',
sourceId: `${tickerRoot}:${country}`,
listingKey,
method: 'tier3_ticker_span',
validFrom: '2015-01-02',
validTo: null,
}
);
}
return {
stageA: {
instruments,
unresolved: [],
conflicts: [],
stats: {
totalInputRecords: instrumentCount,
totalInstruments: instrumentCount,
bySource: {
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
eod: { total: instrumentCount, tier1Isin: instrumentCount, tier2Cusip: 0, unresolved: 0, conflict: 0 },
},
},
},
stageB: {
listings,
providerMappings,
unresolved: [],
conflicts: [],
stats: {
totalListings: instrumentCount,
totalProviderMappings: providerMappings.length,
listingsWithIbConid: instrumentCount,
excludedFunds: 0,
bySource: {
eod: { total: instrumentCount, matched: instrumentCount, unresolved: 0, conflict: 0 },
ib: { total: instrumentCount, matched: instrumentCount, unresolved: 0, conflict: 0 },
qm: { total: instrumentCount, matched: instrumentCount, unresolved: 0, conflict: 0 },
ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
},
},
},
securityTypeByIsin,
};
}
describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
test('happy path persists all 7 tables via real matchers and satisfies M1 exit-criterion shapes', async () => {
const f = await createIsolatedFixture();
const fixture = buildExitCriterionFixture();
const result = await withClient(f.pool, client => persistSecurityMaster(client, fixture));
const counts = await getSevenTableCounts(f.pool);
expect(result.instrumentsInserted).toBe(5);
expect(result.instrumentsSkipped).toBe(0);
expect(result.identifierHistoryInserted).toBe(10); // 5 ISIN + 5 CUSIP
expect(result.listingsInserted).toBe(7);
expect(result.listingSymbolHistoryInserted).toBe(7);
expect(result.providerMappingsInserted).toBe(10); // 7 EOD + 1 IB + 1 QM + 1 CEO
expect(result.conflictsInserted).toBe(2); // 1 Stage A + 1 Stage B
expect(result.continuitiesInserted).toBe(1); // SIVB -> SIVBQ
expect(result.overridesApplied).toBe(0);
// Returned counters reconcile exactly with SQL COUNT(*) per table.
expect(counts).toEqual({
instrument: result.instrumentsInserted,
instrument_identifier_history: result.identifierHistoryInserted,
listing: result.listingsInserted,
listing_symbol_history: result.listingSymbolHistoryInserted,
provider_mapping: result.providerMappingsInserted,
resolution_conflict: result.conflictsInserted,
corporate_action_continuity: result.continuitiesInserted,
});
// Exit criterion 1a: FB (2012-2022 common) vs FB (2025 ETF) have distinct listing_ids.
const fbOldId = result.listingIdByKey.get(
formatListingNaturalKey({
primaryIsin: 'US30303M1027',
mic: 'XNAS',
tickerRoot: 'FB',
classSuffix: '',
currency: 'USD',
})
);
const fbEtfId = result.listingIdByKey.get(
formatListingNaturalKey({
primaryIsin: 'US4642872000',
mic: 'XNAS',
tickerRoot: 'FB',
classSuffix: '',
currency: 'USD',
})
);
expect(fbOldId).toBeDefined();
expect(fbEtfId).toBeDefined();
expect(fbOldId).not.toBe(fbEtfId);
// Exit criterion 1b: SIVB -> SIVBQ continuity and delist_reason / terminal_return.
const sivbId = result.listingIdByKey.get(
formatListingNaturalKey({
primaryIsin: 'US78486Q1013',
mic: 'XNAS',
tickerRoot: 'SIVB',
classSuffix: '',
currency: 'USD',
})
);
const sivbqId = result.listingIdByKey.get(
formatListingNaturalKey({
primaryIsin: 'US78486Q1013',
mic: 'OTCM',
tickerRoot: 'SIVBQ',
classSuffix: '',
currency: 'USD',
})
);
expect(sivbId).toBeDefined();
expect(sivbqId).toBeDefined();
expect(sivbId).not.toBe(sivbqId);
const sivbRows = (
await f.pool.query<{
listing_id: number;
delist_reason: string | null;
terminal_return: string | null;
}>(
`SELECT listing_id, delist_reason, terminal_return
FROM listing
WHERE listing_id = ANY($1::int4[])
ORDER BY listing_id`,
[[sivbId, sivbqId]]
)
).rows;
expect(sivbRows.find(r => r.listing_id === sivbId)).toEqual({
listing_id: sivbId!,
delist_reason: 'moved_to_otc',
terminal_return: null,
});
expect(sivbRows.find(r => r.listing_id === sivbqId)).toEqual({
listing_id: sivbqId!,
delist_reason: 'bankruptcy_cancelled',
terminal_return: '-1.000000',
});
const continuityRows = (
await f.pool.query<{
from_listing_id: number;
to_listing_id: number;
effective_date: string;
kind: string;
}>(
`SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind
FROM corporate_action_continuity`
)
).rows;
expect(continuityRows).toEqual([
{
from_listing_id: sivbId!,
to_listing_id: sivbqId!,
effective_date: '2023-03-28',
kind: 'otc_delist_transfer',
},
]);
// Interlisted SHOP shares one instrument_id and gets two distinct listing_ids.
const shopTsxId = result.listingIdByKey.get(
formatListingNaturalKey({
primaryIsin: 'CA82509L1076',
mic: 'XTSE',
tickerRoot: 'SHOP',
classSuffix: '',
currency: 'CAD',
})
);
const shopNyseId = result.listingIdByKey.get(
formatListingNaturalKey({
primaryIsin: 'CA82509L1076',
mic: 'XNYS',
tickerRoot: 'SHOP',
classSuffix: '',
currency: 'USD',
})
);
expect(shopTsxId).toBeDefined();
expect(shopNyseId).toBeDefined();
expect(shopTsxId).not.toBe(shopNyseId);
const shopInstrumentIds = (
await f.pool.query<{ instrument_id: number }>(
`SELECT DISTINCT instrument_id FROM listing WHERE listing_id = ANY($1::int4[])`,
[[shopTsxId, shopNyseId]]
)
).rows;
expect(shopInstrumentIds).toHaveLength(1);
});
test('is idempotent on re-run and preserves permanent instrument_id / listing_id across incremental additions and updates', async () => {
const f = await createIsolatedFixture();
const fixture = buildExitCriterionFixture();
// Run 1: initial insert
const run1 = await withClient(f.pool, client => persistSecurityMaster(client, fixture));
const countsAfterRun1 = await getSevenTableCounts(f.pool);
// Run 2: identical re-run -> 0 inserted, 0 updated everywhere, identical permanent IDs
const run2 = await withClient(f.pool, client => persistSecurityMaster(client, fixture));
const countsAfterRun2 = await getSevenTableCounts(f.pool);
expect(countsAfterRun2).toEqual(countsAfterRun1);
expect(run2.instrumentsInserted).toBe(0);
expect(run2.instrumentsUpdated).toBe(0);
expect(run2.instrumentsUnchanged).toBe(5);
expect(run2.identifierHistoryInserted).toBe(0);
expect(run2.listingsInserted).toBe(0);
expect(run2.listingsUpdated).toBe(0);
expect(run2.listingsUnchanged).toBe(7);
expect(run2.listingSymbolHistoryInserted).toBe(0);
expect(run2.listingSymbolHistoryUpdated).toBe(0);
expect(run2.providerMappingsInserted).toBe(0);
expect(run2.providerMappingsUpdated).toBe(0);
expect(run2.providerMappingsUnchanged).toBe(10);
expect(run2.conflictsInserted).toBe(0);
expect(run2.conflictsUnchanged).toBe(2);
expect(run2.continuitiesInserted).toBe(0);
expect(run2.continuitiesUpdated).toBe(0);
expect(run2.continuitiesUnchanged).toBe(1);
expect(Object.fromEntries(run2.instrumentIdByIsin)).toEqual(
Object.fromEntries(run1.instrumentIdByIsin)
);
expect(Object.fromEntries(run2.listingIdByKey)).toEqual(Object.fromEntries(run1.listingIdByKey));
// Run 3: add a new listing (BRK.B) + update AAPL's listedTo and SHOP.US's ibConid
const updatedStageA: StageAMatchResult = {
...fixture.stageA,
instruments: [
...fixture.stageA.instruments,
{
primaryIsin: 'US0846707026',
primaryCusip: '084670702',
issuerCountry: 'US',
canonicalName: 'Berkshire Hathaway Inc.',
members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }],
},
],
};
const brkKey = {
primaryIsin: 'US0846707026',
mic: 'XNYS',
tickerRoot: 'BRK',
classSuffix: 'B',
currency: 'USD',
};
const updatedStageB: StageBMatchResult = {
...fixture.stageB,
listings: [
...fixture.stageB.listings.map(listing =>
listing.primaryIsin === 'CA82509L1076' && listing.mic === 'XNYS'
? { ...listing, ibConid: 199169591, ibPrimaryExchange: 'NYSE', listedTo: '2026-11-28' }
: listing
),
{
...brkKey,
ibConid: null,
ibPrimaryExchange: null,
listedFrom: '1996-05-09',
listedTo: null,
},
],
providerMappings: [
...fixture.stageB.providerMappings,
{
source: 'eod',
sourceId: 'BRK-B.US',
listingKey: brkKey,
method: 'tier1_isin',
validFrom: null,
validTo: null,
},
],
};
const updatedTypes = new Map(fixture.securityTypeByIsin);
updatedTypes.set('US0846707026', 'common');
const run3 = await withClient(f.pool, client =>
persistSecurityMaster(client, {
stageA: updatedStageA,
stageB: updatedStageB,
pass6: fixture.pass6,
securityTypeByIsin: updatedTypes,
})
);
expect(run3.instrumentsInserted).toBe(1);
expect(run3.listingsInserted).toBe(1);
expect(run3.listingsUpdated).toBe(1);
expect(run3.listingSymbolHistoryInserted).toBe(1);
expect(run3.listingSymbolHistoryUpdated).toBe(1);
// Every earlier listing_id is preserved unchanged.
for (const [key, prevId] of run1.listingIdByKey.entries()) {
expect(run3.listingIdByKey.get(key)).toBe(prevId);
}
// Class suffix formatting in listing_symbol_history: BRK.B
const brkListingId = run3.listingIdByKey.get(formatListingNaturalKey(brkKey));
const brkHistory = (
await f.pool.query<{ ticker: string; valid_from: string }>(
`SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from
FROM listing_symbol_history
WHERE listing_id = $1`,
[brkListingId]
)
).rows;
expect(brkHistory).toEqual([{ ticker: 'BRK.B', valid_from: '1996-05-09' }]);
});
test('override always wins over conflicting matcher output and inserts override-only mappings', async () => {
const f = await createIsolatedFixture();
const fixture = buildExitCriterionFixture();
// Seed initial listings so override can point at a real target listing_id.
const initial = await withClient(f.pool, client => persistSecurityMaster(client, fixture));
const aaplKey = formatListingNaturalKey({
primaryIsin: 'US0378331005',
mic: 'XNAS',
tickerRoot: 'AAPL',
classSuffix: '',
currency: 'USD',
});
const shopNyseKey = formatListingNaturalKey({
primaryIsin: 'CA82509L1076',
mic: 'XNYS',
tickerRoot: 'SHOP',
classSuffix: '',
currency: 'USD',
});
const aaplId = initial.listingIdByKey.get(aaplKey)!;
const shopNyseId = initial.listingIdByKey.get(shopNyseKey)!;
// 1) Override an existing matcher mapping (eod, AAPL.US, 1980-12-12) -> shopNyseId
// 2) Add an override-only mapping absent from matcher output (qm, MANUAL_OVR:US, 2021-01-01) -> aaplId
await f.pool.query(
`INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)
VALUES
('eod', 'AAPL.US', DATE '1980-12-12', DATE '2025-12-31', $1, 'conflict resolution', 'director'),
('qm', 'MANUAL_OVR:US', DATE '2021-01-01', NULL, $2, 'manual addition', 'director')`,
[shopNyseId, aaplId]
);
const runWithOverrides = await withClient(f.pool, client =>
persistSecurityMaster(client, fixture)
);
expect(runWithOverrides.overridesApplied).toBe(2);
expect(runWithOverrides.providerMappingsInserted).toBe(1); // the override-only mapping
const rowsAfterOverride = (
await f.pool.query<{
source: string;
source_id: string;
valid_from: string;
valid_to: string | null;
listing_id: number;
method: string;
confidence: string;
price_corr: string | null;
}>(
`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, method, confidence::text, price_corr::text
FROM provider_mapping
WHERE (source = 'eod' AND source_id = 'AAPL.US')
OR (source = 'qm' AND source_id = 'MANUAL_OVR:US')
ORDER BY source, source_id`
)
).rows;
expect(rowsAfterOverride).toEqual([
{
source: 'eod',
source_id: 'AAPL.US',
valid_from: '1980-12-12',
valid_to: '2025-12-31',
listing_id: shopNyseId,
method: 'override',
confidence: '1.000',
price_corr: null,
},
{
source: 'qm',
source_id: 'MANUAL_OVR:US',
valid_from: '2021-01-01',
valid_to: null,
listing_id: aaplId,
method: 'override',
confidence: '1.000',
price_corr: null,
},
]);
// Re-running with conflicting matcher output keeps override intact with 0 overwrites.
const secondRun = await withClient(f.pool, client => persistSecurityMaster(client, fixture));
expect(secondRun.overridesApplied).toBe(2);
expect(secondRun.providerMappingsInserted).toBe(0);
expect(secondRun.providerMappingsUpdated).toBe(0);
});
test('persists Stage A, Stage B, and Pass 6 conflicts once and never reopens or modifies non-open rows', async () => {
const f = await createIsolatedFixture();
const fixture = buildExitCriterionFixture();
const pass6WithConflict: DelistingChainResult = {
...fixture.pass6,
conflicts: [
{
conflictKind: 'ambiguous_otc_continuation',
detail: {
primaryIsin: 'US78486Q1013',
currency: 'USD',
fromListingKeys: [],
toListingKeys: [],
candidateListingKeys: [],
listedFrom: null,
listedTo: '2023-03-10',
reason: 'two OTC candidates',
},
},
],
};
const run1 = await withClient(f.pool, client =>
persistSecurityMaster(client, { ...fixture, pass6: pass6WithConflict })
);
expect(run1.conflictsInserted).toBe(3);
// Manually resolve the Pass 6 conflict row.
await f.pool.query(
`UPDATE resolution_conflict
SET status = 'resolved', resolved_at = TIMESTAMPTZ '2026-11-27T12:00:00Z'
WHERE source = 'pass6' AND source_id = 'US78486Q1013' AND conflict_kind = 'ambiguous_otc_continuation'`
);
const run2 = await withClient(f.pool, client =>
persistSecurityMaster(client, { ...fixture, pass6: pass6WithConflict })
);
expect(run2.conflictsInserted).toBe(0);
expect(run2.conflictsUnchanged).toBe(3);
const conflictRows = (
await f.pool.query<{
source: string;
source_id: string;
conflict_kind: string;
status: string;
resolved_at: Date | null;
}>(
`SELECT source, source_id, conflict_kind, status, resolved_at
FROM resolution_conflict
ORDER BY source, source_id, conflict_kind`
)
).rows;
expect(conflictRows).toHaveLength(3);
const pass6Row = conflictRows.find(r => r.source === 'pass6');
expect(pass6Row?.status).toBe('resolved');
expect(pass6Row?.resolved_at).not.toBeNull();
});
test('skips and counts instruments/listings/mappings/continuities without guessing on missing metadata or unknown MIC', async () => {
const f = await createIsolatedFixture();
const stageA = matchInstrumentsStageA([
{
source: 'eod',
sourceId: 'VALID.US',
isin: 'US0378331005',
cusip: '037833100',
country: 'US',
currency: 'USD',
name: 'Apple Inc.',
},
{
source: 'eod',
sourceId: 'NONAME.US',
isin: 'US30303M1027',
cusip: '30303M102',
country: 'US',
currency: 'USD',
name: null,
},
{
source: 'eod',
sourceId: 'NOTYPE.US',
isin: 'US78486Q1013',
cusip: '78486Q101',
country: 'US',
currency: 'USD',
name: 'No Security Type Corp',
},
]);
const validKey = {
primaryIsin: 'US0378331005',
mic: 'XNAS',
tickerRoot: 'AAPL',
classSuffix: '',
currency: 'USD',
};
const unknownMicKey = {
primaryIsin: 'US0378331005',
mic: 'XXXX',
tickerRoot: 'AAPL',
classSuffix: '',
currency: 'USD',
};
const noNameKey = {
primaryIsin: 'US30303M1027',
mic: 'XNAS',
tickerRoot: 'FB',
classSuffix: '',
currency: 'USD',
};
const noTypeKey = {
primaryIsin: 'US78486Q1013',
mic: 'XNAS',
tickerRoot: 'SIVB',
classSuffix: '',
currency: 'USD',
};
const stageB: StageBMatchResult = {
listings: [
{ ...validKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null },
{ ...unknownMicKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null },
{ ...noNameKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null },
{ ...noTypeKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null },
],
providerMappings: [
{ source: 'eod', sourceId: 'AAPL.US', listingKey: validKey, method: 'tier1_isin', validFrom: null, validTo: null },
{ source: 'eod', sourceId: 'AAPL.XX', listingKey: unknownMicKey, method: 'tier1_isin', validFrom: null, validTo: null },
{ source: 'eod', sourceId: 'FB.US', listingKey: noNameKey, method: 'tier1_isin', validFrom: null, validTo: null },
],
unresolved: [],
conflicts: [],
stats: {
totalListings: 4,
totalProviderMappings: 3,
listingsWithIbConid: 0,
excludedFunds: 0,
bySource: {
eod: { total: 3, matched: 3, 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 pass6: DelistingChainResult = {
continuities: [
{
fromListingKey: noTypeKey,
toListingKey: validKey,
effectiveDate: '2023-03-28',
kind: 'otc_delist_transfer',
},
],
listingOutcomes: [
{ listingKey: validKey, delistReason: 'active', terminalReturn: null },
{ listingKey: unknownMicKey, delistReason: 'unknown_involuntary', terminalReturn: -0.3 },
],
conflicts: [],
stats: {
totalInputListings: 2,
processedListings: 2,
skippedMalformedEntries: 0,
skippedInvalidDates: 0,
skippedDuplicateKeys: 0,
continuitiesCreated: 1,
conflictsDetected: 0,
byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 1 },
},
};
const result = await withClient(f.pool, client =>
persistSecurityMaster(client, {
stageA,
stageB,
pass6,
securityTypeByIsin: new Map<string, SecurityType>([
['US0378331005', 'common'],
['US30303M1027', 'common'],
]),
})
);
expect(result.instrumentsInserted).toBe(1);
expect(result.instrumentsSkipped).toBe(2);
expect(result.skippedByReason.instruments).toEqual({
missing_canonical_name: 1,
missing_security_type: 1,
});
expect(result.listingsInserted).toBe(1);
expect(result.listingsSkipped).toBe(3);
expect(result.skippedByReason.listings).toEqual({
skipped_instrument: 2,
missing_instrument: 0,
unknown_mic: 1,
});
expect(result.providerMappingsInserted).toBe(1);
expect(result.providerMappingsSkipped).toBe(2);
expect(result.pass6OutcomesApplied).toBe(1);
expect(result.pass6OutcomesSkipped).toBe(1);
expect(result.continuitiesInserted).toBe(0);
expect(result.continuitiesSkipped).toBe(1);
expect(result.skippedByReason.continuities.missing_from_listing).toBe(1);
});
test('rolls back all 7 tables atomically on a mid-run CHECK constraint violation', async () => {
const f = await createIsolatedFixture();
const fixture = buildExitCriterionFixture();
const preCounts = await getSevenTableCounts(f.pool);
const badTypes = new Map(fixture.securityTypeByIsin);
// Chunk size 2 -> chunk 1 inserts 2 valid instruments, chunk 2 hits Postgres CHECK violation
badTypes.set('US78486Q1013', 'bogus_type' as SecurityType);
await expect(
withClient(f.pool, client =>
persistSecurityMaster(client, { ...fixture, securityTypeByIsin: badTypes }, { chunkSize: 2 })
)
).rejects.toThrow(/security_type/);
const postCounts = await getSevenTableCounts(f.pool);
expect(postCounts).toEqual(preCounts);
});
test('serializes two concurrent writers via pg_advisory_xact_lock without duplicate listings', async () => {
const f = await createIsolatedFixture();
const fixture = buildExitCriterionFixture();
const [c1, c2] = await Promise.all([f.pool.connect(), f.pool.connect()]);
try {
const [r1, r2] = await Promise.all([
persistSecurityMaster(c1, fixture),
persistSecurityMaster(c2, fixture),
]);
expect(Object.fromEntries(r1.listingIdByKey)).toEqual(Object.fromEntries(r2.listingIdByKey));
expect(r1.listingsInserted + r2.listingsInserted).toBe(7);
const counts = await getSevenTableCounts(f.pool);
expect(counts.instrument).toBe(5);
expect(counts.listing).toBe(7);
expect(counts.provider_mapping).toBe(10);
} finally {
c1.release();
c2.release();
}
});
test('batches SQL statements in O(ceil(N / chunkSize)) round trips on a real PoolClient', async () => {
const f = await createIsolatedFixture();
const input = buildSyntheticBenchmarkInput(600);
let queryCount = 0;
const result = await withClient(f.pool, async client => {
const countingClient: SecurityMasterQueryable = {
release: () => undefined,
query: (text, values) => {
queryCount += 1;
return client.query(text, values as unknown[]);
},
};
return persistSecurityMaster(countingClient, input, { chunkSize: 200 });
});
expect(result.instrumentsInserted).toBe(600);
expect(result.listingsInserted).toBe(600);
expect(result.providerMappingsInserted).toBe(1800);
expect(queryCount).toBeLessThan(40);
});
test(
'fixed-seed throughput benchmark: persists 20,000 instruments, 20,000 listings, and 60,000 mappings',
async () => {
const f = await createIsolatedFixture(120_000);
const instrumentCount = 20_000;
const input = buildSyntheticBenchmarkInput(instrumentCount);
const t0 = performance.now();
const result = await withClient(f.pool, client => persistSecurityMaster(client, input));
const elapsedSec = (performance.now() - t0) / 1000;
const totalCoreRows =
result.instrumentsInserted + result.listingsInserted + result.providerMappingsInserted;
const totalAllRows =
totalCoreRows + result.identifierHistoryInserted + result.listingSymbolHistoryInserted;
expect(result.instrumentsInserted).toBe(instrumentCount);
expect(result.listingsInserted).toBe(instrumentCount);
expect(result.providerMappingsInserted).toBe(instrumentCount * 3);
const counts = await getSevenTableCounts(f.pool);
expect(counts.instrument).toBe(instrumentCount);
expect(counts.listing).toBe(instrumentCount);
expect(counts.provider_mapping).toBe(instrumentCount * 3);
console.info(
`[security-master-persist benchmark] ${instrumentCount} instruments, ${instrumentCount} listings, ${instrumentCount * 3} mappings (${totalAllRows} total rows) persisted in ${elapsedSec.toFixed(2)}s (${Math.round(totalCoreRows / elapsedSec)} core rows/s, ${Math.round(totalAllRows / elapsedSec)} total rows/s)`
);
},
120_000
);
});