1841 lines
63 KiB
TypeScript
1841 lines
63 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,
|
|
DEFAULT_VALID_FROM,
|
|
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
|
|
expect(runWithOverrides.providerMappingsUpdated).toBe(1); // AAPL.US redirected by override
|
|
expect(runWithOverrides.providerMappingsUnchanged).toBe(9); // remaining 9 matcher mappings
|
|
|
|
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);
|
|
expect(secondRun.providerMappingsUnchanged).toBe(11);
|
|
});
|
|
|
|
test('replaces loader-generated listing_symbol_history interval when listed_from changes while preserving unrelated aliases', async () => {
|
|
const f = await createIsolatedFixture();
|
|
|
|
const stageA = matchInstrumentsStageA([
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Apple Inc.',
|
|
},
|
|
]);
|
|
const aaplKey = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const securityTypeByIsin = new Map<string, SecurityType>([['US0378331005', 'common']]);
|
|
|
|
// Load 1: no bar span yet -> listedFrom = null -> symbol history starts at 1900-01-01
|
|
const stageBNoSpan = matchListingsStageB({
|
|
instruments: stageA.instruments,
|
|
eodListings: [
|
|
{
|
|
sourceId: 'AAPL.US',
|
|
ticker: 'AAPL',
|
|
mic: 'XNAS',
|
|
role: 'primary_venue',
|
|
currency: 'USD',
|
|
span: null,
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
});
|
|
|
|
const run1 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, { stageA, stageB: stageBNoSpan, securityTypeByIsin })
|
|
);
|
|
const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(aaplKey))!;
|
|
expect(run1.listingSymbolHistoryInserted).toBe(1);
|
|
|
|
// Seed two unrelated historical aliases on the same listing that must be preserved.
|
|
await f.pool.query(
|
|
`INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source)
|
|
VALUES
|
|
($1, 'OLDT', DATE '1978-01-01', DATE '1980-12-11', 'eod'),
|
|
($1, 'AAPL', DATE '1979-06-01', DATE '1980-06-01', 'manual')`,
|
|
[aaplListingId]
|
|
);
|
|
|
|
// Load 2: actual first bar date is supplied -> listed_from updates from NULL to 1980-12-12
|
|
const stageBWithSpan = 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' },
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
});
|
|
|
|
const run2 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, { stageA, stageB: stageBWithSpan, securityTypeByIsin })
|
|
);
|
|
expect(run2.listingIdByKey.get(formatListingNaturalKey(aaplKey))).toBe(aaplListingId);
|
|
expect(run2.listingsInserted).toBe(0);
|
|
expect(run2.listingsUpdated).toBe(1);
|
|
expect(run2.listingSymbolHistoryInserted).toBe(0);
|
|
expect(run2.listingSymbolHistoryUpdated).toBe(1);
|
|
|
|
const historyRows = (
|
|
await f.pool.query<{
|
|
ticker: string;
|
|
valid_from: string;
|
|
valid_to: string | null;
|
|
source: string;
|
|
}>(
|
|
`SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
|
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source
|
|
FROM listing_symbol_history
|
|
WHERE listing_id = $1
|
|
ORDER BY ticker, valid_from, source`,
|
|
[aaplListingId]
|
|
)
|
|
).rows;
|
|
expect(historyRows).toEqual([
|
|
{ ticker: 'AAPL', valid_from: '1979-06-01', valid_to: '1980-06-01', source: 'manual' },
|
|
{ ticker: 'AAPL', valid_from: '1980-12-12', valid_to: '2026-11-27', source: 'eod' },
|
|
{ ticker: 'OLDT', valid_from: '1978-01-01', valid_to: '1980-12-11', source: 'eod' },
|
|
]);
|
|
|
|
// Load 3: identical re-run is a no-op
|
|
const run3 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, { stageA, stageB: stageBWithSpan, securityTypeByIsin })
|
|
);
|
|
expect(run3.listingSymbolHistoryInserted).toBe(0);
|
|
expect(run3.listingSymbolHistoryUpdated).toBe(0);
|
|
expect(run3.listingSymbolHistoryUnchanged).toBe(1);
|
|
});
|
|
|
|
test('removes stale 1900-01-01 provider_mapping fallback on dated rerun and is idempotent thereafter', async () => {
|
|
const f = await createIsolatedFixture();
|
|
|
|
const stageA = matchInstrumentsStageA([
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'FB.US',
|
|
isin: 'US30303M1027',
|
|
cusip: '30303M102',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Meta Platforms Inc.',
|
|
},
|
|
]);
|
|
const fbKey = {
|
|
primaryIsin: 'US30303M1027',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'FB',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const securityTypeByIsin = new Map<string, SecurityType>([['US30303M1027', 'common']]);
|
|
|
|
const makeStageB = (validFrom: string | null): StageBMatchResult => ({
|
|
listings: [
|
|
{
|
|
...fbKey,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: validFrom,
|
|
listedTo: null,
|
|
},
|
|
],
|
|
providerMappings: [
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'FB.US',
|
|
listingKey: fbKey,
|
|
method: 'tier1_isin',
|
|
validFrom,
|
|
validTo: null,
|
|
},
|
|
],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: {
|
|
totalListings: 1,
|
|
totalProviderMappings: 1,
|
|
listingsWithIbConid: 0,
|
|
excludedFunds: 0,
|
|
bySource: {
|
|
eod: { total: 1, matched: 1, 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 },
|
|
},
|
|
},
|
|
});
|
|
|
|
// Run 1: validFrom null -> writes 1900-01-01 fallback row
|
|
const run1 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, { stageA, stageB: makeStageB(null), securityTypeByIsin })
|
|
);
|
|
const fbListingId = run1.listingIdByKey.get(formatListingNaturalKey(fbKey))!;
|
|
expect(run1.providerMappingsInserted).toBe(1);
|
|
expect(run1.providerMappingsUpdated).toBe(0);
|
|
expect(run1.providerMappingsUnchanged).toBe(0);
|
|
expect(run1.providerMappingsDeletedStaleFallback).toBe(0);
|
|
|
|
const rowsAfterRun1 = (
|
|
await f.pool.query<{ valid_from: string; listing_id: number }>(
|
|
`SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
|
FROM provider_mapping
|
|
WHERE source = 'eod' AND source_id = 'FB.US'
|
|
ORDER BY valid_from`
|
|
)
|
|
).rows;
|
|
expect(rowsAfterRun1).toEqual([{ valid_from: DEFAULT_VALID_FROM, listing_id: fbListingId }]);
|
|
|
|
// Run 2: real validFrom supplied -> deletes 1900-01-01 fallback and keeps only 2012-05-18
|
|
const run2 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: makeStageB('2012-05-18'),
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
expect(run2.providerMappingsInserted).toBe(1);
|
|
expect(run2.providerMappingsUpdated).toBe(0);
|
|
expect(run2.providerMappingsUnchanged).toBe(0);
|
|
expect(run2.providerMappingsDeletedStaleFallback).toBe(1);
|
|
|
|
const rowsAfterRun2 = (
|
|
await f.pool.query<{ valid_from: string; listing_id: number }>(
|
|
`SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
|
FROM provider_mapping
|
|
WHERE source = 'eod' AND source_id = 'FB.US'
|
|
ORDER BY valid_from`
|
|
)
|
|
).rows;
|
|
expect(rowsAfterRun2).toEqual([{ valid_from: '2012-05-18', listing_id: fbListingId }]);
|
|
|
|
// Run 3: identical dated rerun -> idempotent (0 deletes, 1 unchanged)
|
|
const run3 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: makeStageB('2012-05-18'),
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
expect(run3.providerMappingsInserted).toBe(0);
|
|
expect(run3.providerMappingsUpdated).toBe(0);
|
|
expect(run3.providerMappingsUnchanged).toBe(1);
|
|
expect(run3.providerMappingsDeletedStaleFallback).toBe(0);
|
|
|
|
const rowsAfterRun3 = (
|
|
await f.pool.query<{ valid_from: string; listing_id: number }>(
|
|
`SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
|
FROM provider_mapping
|
|
WHERE source = 'eod' AND source_id = 'FB.US'
|
|
ORDER BY valid_from`
|
|
)
|
|
).rows;
|
|
expect(rowsAfterRun3).toEqual([{ valid_from: '2012-05-18', listing_id: fbListingId }]);
|
|
});
|
|
|
|
test('preserves override-protected 1900-01-01 provider_mapping rows on dated rerun', async () => {
|
|
const f = await createIsolatedFixture();
|
|
|
|
const stageA = matchInstrumentsStageA([
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'A.US',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Listing A Corp',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'B.US',
|
|
isin: 'US30303M1027',
|
|
cusip: '30303M102',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Listing B Corp',
|
|
},
|
|
]);
|
|
const keyA = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAA',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const keyB = {
|
|
primaryIsin: 'US30303M1027',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'BBB',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const securityTypeByIsin = new Map<string, SecurityType>([
|
|
['US0378331005', 'common'],
|
|
['US30303M1027', 'common'],
|
|
]);
|
|
|
|
const listings = [
|
|
{ ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2012-05-18', listedTo: null },
|
|
{ ...keyB, ibConid: null, ibPrimaryExchange: null, listedFrom: '2012-05-18', listedTo: null },
|
|
];
|
|
const emptyStats = {
|
|
totalListings: 2,
|
|
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 },
|
|
},
|
|
};
|
|
|
|
// Run 1: seed listings and three 1900-01-01 fallback mappings pointing at listing A.
|
|
const run1 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: {
|
|
listings,
|
|
providerMappings: [
|
|
{ source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
{ source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
{ source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: emptyStats,
|
|
},
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
const listingAId = run1.listingIdByKey.get(formatListingNaturalKey(keyA))!;
|
|
const listingBId = run1.listingIdByKey.get(formatListingNaturalKey(keyB))!;
|
|
|
|
// Materialize override for OVR_MAT.US via a persist run before the dated rerun.
|
|
await f.pool.query(
|
|
`INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)
|
|
VALUES ('eod', 'OVR_MAT.US', DATE '1900-01-01', NULL, $1, 'already materialized override', 'director')`,
|
|
[listingBId]
|
|
);
|
|
await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: {
|
|
listings,
|
|
providerMappings: [
|
|
{ source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
{ source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
{ source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: emptyStats,
|
|
},
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
|
|
// Newly insert override for OVR_NEW.US (still method='tier1_isin' in provider_mapping) and
|
|
// directly mark OVR_METHOD_ONLY.US as method='override' (no row in override table).
|
|
await f.pool.query(
|
|
`INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)
|
|
VALUES ('eod', 'OVR_NEW.US', DATE '1900-01-01', NULL, $1, 'unmaterialized override', 'director')`,
|
|
[listingBId]
|
|
);
|
|
await f.pool.query(
|
|
`UPDATE provider_mapping
|
|
SET method = 'override', confidence = 1.000, listing_id = $1
|
|
WHERE source = 'eod' AND source_id = 'OVR_METHOD_ONLY.US' AND valid_from = DATE '1900-01-01'`,
|
|
[listingBId]
|
|
);
|
|
|
|
// Run 2: dated rerun for all three source IDs -> none of the 1900-01-01 rows may be deleted.
|
|
const run2 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: {
|
|
listings,
|
|
providerMappings: [
|
|
{ source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
|
{ source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
|
{ source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
|
],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: emptyStats,
|
|
},
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
expect(run2.providerMappingsDeletedStaleFallback).toBe(0);
|
|
expect(run2.overridesApplied).toBe(2);
|
|
|
|
const rows = (
|
|
await f.pool.query<{
|
|
source_id: string;
|
|
valid_from: string;
|
|
listing_id: number;
|
|
method: string;
|
|
confidence: string;
|
|
}>(
|
|
`SELECT source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id, method, confidence::text
|
|
FROM provider_mapping
|
|
WHERE source = 'eod'
|
|
ORDER BY source_id, valid_from`
|
|
)
|
|
).rows;
|
|
|
|
expect(rows).toEqual([
|
|
{ source_id: 'OVR_MAT.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' },
|
|
{ source_id: 'OVR_MAT.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' },
|
|
{ source_id: 'OVR_METHOD_ONLY.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' },
|
|
{ source_id: 'OVR_METHOD_ONLY.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' },
|
|
{ source_id: 'OVR_NEW.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' },
|
|
{ source_id: 'OVR_NEW.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' },
|
|
]);
|
|
});
|
|
|
|
test('stale-fallback cleanup preserves absent pairs, other sources, dated rows, and mixed runs while removing cross-listing fallbacks', async () => {
|
|
const f = await createIsolatedFixture();
|
|
|
|
const stageA = matchInstrumentsStageA([
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'A.US',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Listing A Corp',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'B.US',
|
|
isin: 'US30303M1027',
|
|
cusip: '30303M102',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Listing B Corp',
|
|
},
|
|
]);
|
|
const keyA = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAA',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const keyB = {
|
|
primaryIsin: 'US30303M1027',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'BBB',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const securityTypeByIsin = new Map<string, SecurityType>([
|
|
['US0378331005', 'common'],
|
|
['US30303M1027', 'common'],
|
|
]);
|
|
const listings = [
|
|
{ ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2010-01-04', listedTo: null },
|
|
{ ...keyB, ibConid: null, ibPrimaryExchange: null, listedFrom: '2018-06-01', listedTo: null },
|
|
];
|
|
const baseStats = {
|
|
totalListings: 2,
|
|
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 },
|
|
},
|
|
};
|
|
|
|
// Run 1: seed initial rows covering all preservation boundaries + cross-listing fallback.
|
|
const run1 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: {
|
|
listings,
|
|
providerMappings: [
|
|
// Absent from Run 2 -> must be kept
|
|
{ source: 'eod', sourceId: 'ABSENT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
// Same source_id under a different source ('qm') -> must be kept when 'eod' reruns dated
|
|
{ source: 'qm', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier3_ticker_span', validFrom: null, validTo: null },
|
|
{ source: 'eod', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
// Existing dated row -> must never be deleted when another dated row is added
|
|
{ source: 'eod', sourceId: 'DATED_KEEP.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2010-01-04', validTo: '2019-12-31' },
|
|
// Mixed run (both 1900-01-01 and dated in Run 2) -> both must be kept
|
|
{ source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: '2014-12-31' },
|
|
// Cross-listing reassignment: 1900-01-01 points at listing A, Run 2 maps dated to listing B
|
|
{ source: 'eod', sourceId: 'REASSIGN.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
|
],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: baseStats,
|
|
},
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
const listingAId = run1.listingIdByKey.get(formatListingNaturalKey(keyA))!;
|
|
const listingBId = run1.listingIdByKey.get(formatListingNaturalKey(keyB))!;
|
|
expect(run1.providerMappingsDeletedStaleFallback).toBe(0);
|
|
|
|
// Run 2:
|
|
// - ABSENT.US omitted
|
|
// - (eod, SHARED.ID) dated -> deletes only (eod, SHARED.ID, 1900-01-01), keeps (qm, SHARED.ID, 1900-01-01)
|
|
// - (eod, DATED_KEEP.US) adds a second dated row -> keeps 2010-01-04
|
|
// - (eod, MIXED.US) supplies both 1900-01-01 and 2015-01-01 -> keeps both
|
|
// - (eod, REASSIGN.US) dated to listing B -> deletes stale 1900-01-01 pointing at listing A
|
|
const run2 = await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: {
|
|
listings,
|
|
providerMappings: [
|
|
{ source: 'eod', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
|
{ source: 'eod', sourceId: 'DATED_KEEP.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2020-01-02', validTo: null },
|
|
{ source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: DEFAULT_VALID_FROM, validTo: '2014-12-31' },
|
|
{ source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2015-01-01', validTo: null },
|
|
{ source: 'eod', sourceId: 'REASSIGN.US', listingKey: keyB, method: 'tier1_isin', validFrom: '2018-06-01', validTo: null },
|
|
],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: baseStats,
|
|
},
|
|
securityTypeByIsin,
|
|
})
|
|
);
|
|
|
|
// Exactly 2 stale fallbacks removed: (eod, SHARED.ID) and (eod, REASSIGN.US)
|
|
expect(run2.providerMappingsDeletedStaleFallback).toBe(2);
|
|
expect(run2.providerMappingsInserted).toBe(4);
|
|
expect(run2.providerMappingsUpdated).toBe(0);
|
|
expect(run2.providerMappingsUnchanged).toBe(1); // (eod, MIXED.US, 1900-01-01)
|
|
|
|
const allRows = (
|
|
await f.pool.query<{
|
|
source: string;
|
|
source_id: string;
|
|
valid_from: string;
|
|
listing_id: number;
|
|
}>(
|
|
`SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
|
FROM provider_mapping
|
|
ORDER BY source, source_id, valid_from`
|
|
)
|
|
).rows;
|
|
|
|
expect(allRows).toEqual([
|
|
{ source: 'eod', source_id: 'ABSENT.US', valid_from: '1900-01-01', listing_id: listingAId },
|
|
{ source: 'eod', source_id: 'DATED_KEEP.US', valid_from: '2010-01-04', listing_id: listingAId },
|
|
{ source: 'eod', source_id: 'DATED_KEEP.US', valid_from: '2020-01-02', listing_id: listingAId },
|
|
{ source: 'eod', source_id: 'MIXED.US', valid_from: '1900-01-01', listing_id: listingAId },
|
|
{ source: 'eod', source_id: 'MIXED.US', valid_from: '2015-01-01', listing_id: listingAId },
|
|
{ source: 'eod', source_id: 'REASSIGN.US', valid_from: '2018-06-01', listing_id: listingBId },
|
|
{ source: 'eod', source_id: 'SHARED.ID', valid_from: '2012-05-18', listing_id: listingAId },
|
|
{ source: 'qm', source_id: 'SHARED.ID', valid_from: '1900-01-01', listing_id: listingAId },
|
|
]);
|
|
});
|
|
|
|
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 late CHECK constraint violation after earlier phases wrote changes', async () => {
|
|
const f = await createIsolatedFixture();
|
|
const fixture = buildExitCriterionFixture();
|
|
|
|
// Seed all 7 tables so both updates to existing rows and new inserts are exercised.
|
|
await withClient(f.pool, client => persistSecurityMaster(client, fixture));
|
|
|
|
const snapshotSevenTables = async () => ({
|
|
instrument: (
|
|
await f.pool.query(
|
|
`SELECT instrument_id, btrim(primary_isin) AS primary_isin, btrim(primary_cusip) AS primary_cusip,
|
|
canonical_name, security_type, btrim(issuer_country) AS issuer_country
|
|
FROM instrument ORDER BY instrument_id`
|
|
)
|
|
).rows,
|
|
instrument_identifier_history: (
|
|
await f.pool.query(
|
|
`SELECT instrument_id, id_type, id_value, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
|
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source
|
|
FROM instrument_identifier_history ORDER BY id_type, id_value, valid_from`
|
|
)
|
|
).rows,
|
|
listing: (
|
|
await f.pool.query(
|
|
`SELECT listing_id, instrument_id, mic, ticker_root, class_suffix, btrim(currency) AS currency,
|
|
ib_conid, ib_primary_exchange, to_char(listed_from, 'YYYY-MM-DD') AS listed_from,
|
|
to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, terminal_return
|
|
FROM listing ORDER BY listing_id`
|
|
)
|
|
).rows,
|
|
listing_symbol_history: (
|
|
await f.pool.query(
|
|
`SELECT listing_id, ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
|
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source
|
|
FROM listing_symbol_history ORDER BY listing_id, ticker, valid_from`
|
|
)
|
|
).rows,
|
|
provider_mapping: (
|
|
await f.pool.query(
|
|
`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 ORDER BY source, source_id, valid_from`
|
|
)
|
|
).rows,
|
|
resolution_conflict: (
|
|
await f.pool.query(
|
|
`SELECT conflict_id, source, source_id, conflict_kind, detail, status
|
|
FROM resolution_conflict ORDER BY conflict_id`
|
|
)
|
|
).rows,
|
|
corporate_action_continuity: (
|
|
await f.pool.query(
|
|
`SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind
|
|
FROM corporate_action_continuity ORDER BY from_listing_id, effective_date`
|
|
)
|
|
).rows,
|
|
});
|
|
|
|
const before = await snapshotSevenTables();
|
|
|
|
// Mutate phases 1-6 (update existing instrument/listing, add new instrument/listing/mapping/conflict),
|
|
// then fail in phase 7 (corporate_action_continuity.kind CHECK constraint).
|
|
const newIsin = 'US0846707026';
|
|
const newKey = {
|
|
primaryIsin: newIsin,
|
|
mic: 'XNYS',
|
|
tickerRoot: 'BRK',
|
|
classSuffix: 'B',
|
|
currency: 'USD',
|
|
};
|
|
const mutatedStageA: StageAMatchResult = {
|
|
...fixture.stageA,
|
|
instruments: [
|
|
...fixture.stageA.instruments.map(inst =>
|
|
inst.primaryIsin === 'US0378331005'
|
|
? { ...inst, canonicalName: 'Apple Inc. MUTATED' }
|
|
: inst
|
|
),
|
|
{
|
|
primaryIsin: newIsin,
|
|
primaryCusip: '084670702',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Berkshire Hathaway Inc.',
|
|
members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }],
|
|
},
|
|
],
|
|
conflicts: [
|
|
...fixture.stageA.conflicts,
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'ROLLBACK_TEST.US',
|
|
conflictKind: 'isin_cusip_mismatch',
|
|
detail: { isin: newIsin, cusip: '084670702', country: 'US', derivedIsin: null },
|
|
},
|
|
],
|
|
};
|
|
const mutatedStageB: StageBMatchResult = {
|
|
...fixture.stageB,
|
|
listings: [
|
|
...fixture.stageB.listings.map(l =>
|
|
l.primaryIsin === 'CA82509L1076' && l.mic === 'XNYS'
|
|
? { ...l, ibConid: 999999, listedTo: '2026-11-28' }
|
|
: l
|
|
),
|
|
{
|
|
...newKey,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: '1996-05-09',
|
|
listedTo: null,
|
|
},
|
|
],
|
|
providerMappings: [
|
|
...fixture.stageB.providerMappings,
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'BRK-B.US',
|
|
listingKey: newKey,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: null,
|
|
},
|
|
],
|
|
};
|
|
const mutatedPass6: DelistingChainResult = {
|
|
...fixture.pass6,
|
|
continuities: [
|
|
...fixture.pass6.continuities.map(c => ({
|
|
...c,
|
|
kind: 'bogus_kind' as typeof c.kind,
|
|
})),
|
|
],
|
|
};
|
|
const mutatedTypes = new Map(fixture.securityTypeByIsin);
|
|
mutatedTypes.set(newIsin, 'common');
|
|
|
|
await expect(
|
|
withClient(f.pool, client =>
|
|
persistSecurityMaster(client, {
|
|
stageA: mutatedStageA,
|
|
stageB: mutatedStageB,
|
|
pass6: mutatedPass6,
|
|
securityTypeByIsin: mutatedTypes,
|
|
})
|
|
)
|
|
).rejects.toThrow(/corporate_action_continuity|kind/);
|
|
|
|
const after = await snapshotSevenTables();
|
|
expect(after).toEqual(before);
|
|
});
|
|
|
|
test('rejects overlapping calls on one shared PoolClient without creating duplicate listings', async () => {
|
|
const f = await createIsolatedFixture();
|
|
|
|
const stageA = matchInstrumentsStageA([
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
name: 'Apple Inc.',
|
|
},
|
|
]);
|
|
const securityTypeByIsin = new Map<string, SecurityType>([['US0378331005', 'common']]);
|
|
const emptyListingsStageB = matchListingsStageB({
|
|
instruments: stageA.instruments,
|
|
eodListings: [],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
});
|
|
const withNewListingStageB = 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' },
|
|
},
|
|
],
|
|
ibContracts: [],
|
|
tickerSources: [],
|
|
});
|
|
|
|
// Seed the existing instrument first, then overlap two loads adding the same new listing on one client.
|
|
await withClient(f.pool, client =>
|
|
persistSecurityMaster(client, { stageA, stageB: emptyListingsStageB, securityTypeByIsin })
|
|
);
|
|
|
|
const sharedClient = await f.pool.connect();
|
|
try {
|
|
const [first, second] = await Promise.allSettled([
|
|
persistSecurityMaster(sharedClient, {
|
|
stageA,
|
|
stageB: withNewListingStageB,
|
|
securityTypeByIsin,
|
|
}),
|
|
persistSecurityMaster(sharedClient, {
|
|
stageA,
|
|
stageB: withNewListingStageB,
|
|
securityTypeByIsin,
|
|
}),
|
|
]);
|
|
|
|
expect(first.status).toBe('fulfilled');
|
|
expect(second.status).toBe('rejected');
|
|
if (second.status === 'rejected') {
|
|
expect(String(second.reason)).toMatch(/overlapping calls on the same client/);
|
|
}
|
|
|
|
const counts = await getSevenTableCounts(f.pool);
|
|
expect(counts.instrument).toBe(1);
|
|
expect(counts.listing).toBe(1);
|
|
expect(counts.provider_mapping).toBe(1);
|
|
|
|
// Sequential reuse of the same PoolClient succeeds once the first call has finished.
|
|
const followUp = await persistSecurityMaster(sharedClient, {
|
|
stageA,
|
|
stageB: withNewListingStageB,
|
|
securityTypeByIsin,
|
|
});
|
|
expect(followUp.listingsInserted).toBe(0);
|
|
expect(followUp.listingsUnchanged).toBe(1);
|
|
} finally {
|
|
sharedClient.release();
|
|
}
|
|
});
|
|
|
|
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
|
|
);
|
|
});
|