1390 lines
44 KiB
TypeScript
1390 lines
44 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
canonicalizeJsonValue,
|
|
DEFAULT_VALID_FROM,
|
|
formatListingNaturalKey,
|
|
MAX_PERSIST_CHUNK_SIZE,
|
|
persistSecurityMaster,
|
|
PROVIDER_MAPPING_CONFIDENCE,
|
|
SECURITY_MASTER_PERSIST_LOCK_NAMESPACE,
|
|
stableJsonStringify,
|
|
type DelistingChainResult,
|
|
type PersistSecurityMasterInput,
|
|
type PriceCrossCheckConflictRecord,
|
|
type PriceCrossCheckResult,
|
|
type SecurityMasterQueryable,
|
|
type SecurityMasterQueryResult,
|
|
type SecurityType,
|
|
type StageAMatchResult,
|
|
type StageBMatchResult,
|
|
} from '../../apps/stock/data-pipeline/src/security-master';
|
|
|
|
interface RecordedQuery {
|
|
text: string;
|
|
values: readonly unknown[] | undefined;
|
|
}
|
|
|
|
function emptyStageA(): StageAMatchResult {
|
|
return {
|
|
instruments: [],
|
|
unresolved: [],
|
|
conflicts: [],
|
|
stats: {
|
|
totalInputRecords: 0,
|
|
totalInstruments: 0,
|
|
bySource: {
|
|
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
|
eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function emptyStageB(): StageBMatchResult {
|
|
return {
|
|
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 },
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function createMockClient(
|
|
handler?: (
|
|
text: string,
|
|
values: readonly unknown[] | undefined,
|
|
index: number
|
|
) => SecurityMasterQueryResult | Promise<SecurityMasterQueryResult>
|
|
): { client: SecurityMasterQueryable; queries: RecordedQuery[] } {
|
|
const queries: RecordedQuery[] = [];
|
|
let nextInstrumentId = 100;
|
|
let nextListingId = 1000;
|
|
|
|
const client: SecurityMasterQueryable = {
|
|
release: () => undefined,
|
|
async query<Row = Record<string, unknown>>(
|
|
text: string,
|
|
values?: readonly unknown[]
|
|
): Promise<SecurityMasterQueryResult<Row>> {
|
|
const index = queries.length;
|
|
queries.push({ text, values });
|
|
if (handler) {
|
|
return (await handler(text, values, index)) as SecurityMasterQueryResult<Row>;
|
|
}
|
|
|
|
if (text.startsWith('SELECT mic FROM exchange')) {
|
|
return {
|
|
rows: [{ mic: 'XNAS' }, { mic: 'XNYS' }, { mic: 'XTSE' }, { mic: 'OTCM' }],
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument (')) {
|
|
const isins = (values?.[0] as string[]) ?? [];
|
|
return {
|
|
rows: isins.map(isin => ({
|
|
instrument_id: nextInstrumentId++,
|
|
primary_isin: isin,
|
|
})),
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
|
const ids = (values?.[0] as number[]) ?? [];
|
|
return {
|
|
rows: ids.map(() => ({ inserted: 1 })),
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.startsWith('INSERT INTO listing (')) {
|
|
const instrumentIds = (values?.[0] as number[]) ?? [];
|
|
const mics = (values?.[1] as string[]) ?? [];
|
|
const roots = (values?.[2] as string[]) ?? [];
|
|
const suffixes = (values?.[3] as string[]) ?? [];
|
|
const currencies = (values?.[4] as string[]) ?? [];
|
|
return {
|
|
rows: instrumentIds.map((instrumentId, i) => ({
|
|
listing_id: nextListingId++,
|
|
instrument_id: instrumentId,
|
|
mic: mics[i],
|
|
ticker_root: roots[i],
|
|
class_suffix: suffixes[i],
|
|
currency: currencies[i],
|
|
})),
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.includes('INTO listing_symbol_history')) {
|
|
const firstCol = (values?.[0] as unknown[]) ?? [];
|
|
return {
|
|
rows: [{ inserted_count: firstCol.length, updated_count: 0 }],
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.startsWith('INSERT INTO provider_mapping')) {
|
|
const sources = (values?.[0] as string[]) ?? [];
|
|
const sourceIds = (values?.[1] as string[]) ?? [];
|
|
const validFroms = (values?.[2] as string[]) ?? [];
|
|
return {
|
|
rows: sources.map((source, i) => ({
|
|
source,
|
|
source_id: sourceIds[i],
|
|
valid_from: validFroms[i],
|
|
inserted: true,
|
|
})),
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.startsWith('INSERT INTO corporate_action_continuity')) {
|
|
const firstCol = (values?.[0] as unknown[]) ?? [];
|
|
return {
|
|
rows: firstCol.map(() => ({ inserted: true })),
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
if (text.includes('WITH enforced AS')) {
|
|
return {
|
|
rows: [],
|
|
} as unknown as SecurityMasterQueryResult<Row>;
|
|
}
|
|
return { rows: [] } as SecurityMasterQueryResult<Row>;
|
|
},
|
|
};
|
|
|
|
return { client, queries };
|
|
}
|
|
|
|
describe('persistSecurityMaster unit tests', () => {
|
|
test('rejects a pg.Pool-shaped object and non-queryable inputs', async () => {
|
|
const fakePool = {
|
|
totalCount: 1,
|
|
idleCount: 1,
|
|
waitingCount: 0,
|
|
query: async () => ({ rows: [] }),
|
|
} as unknown as SecurityMasterQueryable;
|
|
|
|
const emptyInput: PersistSecurityMasterInput = {
|
|
stageA: emptyStageA(),
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map(),
|
|
};
|
|
|
|
await expect(persistSecurityMaster(fakePool, emptyInput)).rejects.toThrow(/PoolClient/);
|
|
await expect(
|
|
persistSecurityMaster(null as unknown as SecurityMasterQueryable, emptyInput)
|
|
).rejects.toThrow(/query\(\)/);
|
|
});
|
|
|
|
test('validates chunkSize bounds', async () => {
|
|
const { client } = createMockClient();
|
|
const emptyInput: PersistSecurityMasterInput = {
|
|
stageA: emptyStageA(),
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map(),
|
|
};
|
|
|
|
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 0 })).rejects.toThrow(
|
|
RangeError
|
|
);
|
|
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: -5 })).rejects.toThrow(
|
|
RangeError
|
|
);
|
|
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 1.5 })).rejects.toThrow(
|
|
RangeError
|
|
);
|
|
await expect(
|
|
persistSecurityMaster(client, emptyInput, { chunkSize: MAX_PERSIST_CHUNK_SIZE + 1 })
|
|
).rejects.toThrow(RangeError);
|
|
});
|
|
|
|
test('empty input fast path runs only BEGIN, advisory lock, override CTE, and COMMIT', async () => {
|
|
const { client, queries } = createMockClient();
|
|
const result = await persistSecurityMaster(client, {
|
|
stageA: emptyStageA(),
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map(),
|
|
});
|
|
|
|
expect(queries.map(q => q.text.trim().split('\n')[0])).toEqual([
|
|
'BEGIN',
|
|
'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))',
|
|
'WITH enforced AS (',
|
|
'COMMIT',
|
|
]);
|
|
expect(queries[1]?.values).toEqual([SECURITY_MASTER_PERSIST_LOCK_NAMESPACE]);
|
|
expect(result.instrumentsInserted).toBe(0);
|
|
expect(result.listingsInserted).toBe(0);
|
|
expect(result.providerMappingsInserted).toBe(0);
|
|
expect(result.providerMappingsDeletedStaleFallback).toBe(0);
|
|
expect(result.overridesApplied).toBe(0);
|
|
});
|
|
|
|
test('parameterizes all SQL values and never interpolates untrusted strings into SQL text', async () => {
|
|
const { client, queries } = createMockClient();
|
|
const hostileName = "O'Brien Corp; DROP TABLE instrument; --";
|
|
const hostileSourceId = "BAD'ID;DELETE";
|
|
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: hostileName,
|
|
members: [{ source: 'ib', sourceId: hostileSourceId, currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
stageA.conflicts.push({
|
|
source: 'eod',
|
|
sourceId: hostileSourceId,
|
|
conflictKind: 'isin_cusip_mismatch',
|
|
detail: {
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
country: 'US',
|
|
derivedIsin: null,
|
|
},
|
|
});
|
|
|
|
const stageB = emptyStageB();
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
stageB.listings.push({
|
|
...key,
|
|
ibConid: 265598,
|
|
ibPrimaryExchange: 'NASDAQ',
|
|
listedFrom: '1980-12-12',
|
|
listedTo: null,
|
|
});
|
|
stageB.providerMappings.push({
|
|
source: 'ib',
|
|
sourceId: hostileSourceId,
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: null,
|
|
});
|
|
|
|
await persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
|
});
|
|
|
|
for (const q of queries) {
|
|
expect(q.text).not.toContain(hostileName);
|
|
expect(q.text).not.toContain(hostileSourceId);
|
|
expect(q.text).not.toContain('US0378331005');
|
|
}
|
|
|
|
const mappingInsert = queries.find(q => q.text.startsWith('INSERT INTO provider_mapping'));
|
|
expect(mappingInsert?.values?.[2]).toEqual([DEFAULT_VALID_FROM]);
|
|
expect(mappingInsert?.values?.[6]).toEqual([
|
|
PROVIDER_MAPPING_CONFIDENCE.tier1_isin.toFixed(3),
|
|
]);
|
|
});
|
|
|
|
test('statement count scales with O(ceil(N / chunkSize)) rather than O(N)', async () => {
|
|
const count = 600;
|
|
const chunkSize = 200;
|
|
const stageA = emptyStageA();
|
|
const stageB = emptyStageB();
|
|
const securityTypeByIsin = new Map<string, SecurityType>();
|
|
|
|
for (let i = 0; i < count; i++) {
|
|
const isin = `US${String(i).padStart(9, '0')}0`;
|
|
const cusip = String(i).padStart(9, '0');
|
|
stageA.instruments.push({
|
|
primaryIsin: isin,
|
|
primaryCusip: cusip,
|
|
issuerCountry: 'US',
|
|
canonicalName: `Corp ${i}`,
|
|
members: [{ source: 'eod', sourceId: `T${i}.US`, currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
securityTypeByIsin.set(isin, 'common');
|
|
const key = {
|
|
primaryIsin: isin,
|
|
mic: 'XNAS',
|
|
tickerRoot: `T${i}`,
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
stageB.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: '2020-01-01',
|
|
listedTo: null,
|
|
});
|
|
stageB.providerMappings.push({
|
|
source: 'eod',
|
|
sourceId: `T${i}.US`,
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: null,
|
|
});
|
|
stageB.providerMappings.push({
|
|
source: 'qm',
|
|
sourceId: `T${i}:US`,
|
|
listingKey: key,
|
|
method: 'tier3_ticker_span',
|
|
validFrom: '2020-01-01',
|
|
validTo: null,
|
|
});
|
|
}
|
|
|
|
const { client, queries } = createMockClient();
|
|
const result = await persistSecurityMaster(
|
|
client,
|
|
{ stageA, stageB, securityTypeByIsin },
|
|
{ chunkSize }
|
|
);
|
|
|
|
expect(result.instrumentsInserted).toBe(count);
|
|
expect(result.listingsInserted).toBe(count);
|
|
expect(result.providerMappingsInserted).toBe(count * 2);
|
|
// 3 chunks for instruments (select+insert), 6 for id_history (ISIN+CUSIP),
|
|
// 1 exchange select, 3+3+3 for listings (select+insert+symbol_history),
|
|
// 6 for provider_mapping, plus BEGIN/lock/override/COMMIT = 31 queries total << 600 rows.
|
|
expect(queries.length).toBeLessThan(40);
|
|
});
|
|
|
|
test('canonicalizes JSONB keys deterministically regardless of property insertion order', () => {
|
|
const a = { z: 1, a: { d: 2, b: [3, undefined, { y: true, x: false }] }, dropMe: undefined };
|
|
const b = { a: { b: [3, null, { x: false, y: true }], d: 2 }, z: 1 };
|
|
|
|
expect(stableJsonStringify(a)).toBe(stableJsonStringify(b));
|
|
expect(canonicalizeJsonValue(Number.NaN)).toBeNull();
|
|
});
|
|
|
|
test('selects best member source for instrument_identifier_history (tier1_isin > tier2_cusip, ib > eod)', async () => {
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push(
|
|
{
|
|
primaryIsin: 'US0000000010',
|
|
primaryCusip: null,
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Tier1 IB wins over EOD',
|
|
members: [
|
|
{ source: 'eod', sourceId: 'A.US', currency: 'USD', method: 'tier1_isin' },
|
|
{ source: 'ib', sourceId: '1', currency: 'USD', method: 'tier1_isin' },
|
|
],
|
|
},
|
|
{
|
|
primaryIsin: 'US0000000020',
|
|
primaryCusip: null,
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Tier1 EOD wins over Tier2 IB',
|
|
members: [
|
|
{ source: 'ib', sourceId: '2', currency: 'USD', method: 'tier2_cusip' },
|
|
{ source: 'eod', sourceId: 'B.US', currency: 'USD', method: 'tier1_isin' },
|
|
],
|
|
},
|
|
{
|
|
primaryIsin: 'US0000000030',
|
|
primaryCusip: null,
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Empty members falls back to eod',
|
|
members: [],
|
|
}
|
|
);
|
|
|
|
const { client, queries } = createMockClient();
|
|
await persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map<string, SecurityType>([
|
|
['US0000000010', 'common'],
|
|
['US0000000020', 'common'],
|
|
['US0000000030', 'common'],
|
|
]),
|
|
});
|
|
|
|
const idHistoryQuery = queries.find(q =>
|
|
q.text.startsWith('INSERT INTO instrument_identifier_history')
|
|
);
|
|
expect(idHistoryQuery?.values?.[4]).toEqual(['ib', 'eod', 'eod']);
|
|
});
|
|
|
|
test('rejects duplicate input natural keys and duplicate DB listing rows', async () => {
|
|
const { client } = createMockClient();
|
|
|
|
// 1. Duplicate primaryIsin
|
|
const dupIsin = emptyStageA();
|
|
dupIsin.instruments.push(
|
|
{
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple',
|
|
members: [],
|
|
},
|
|
{
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Dup',
|
|
members: [],
|
|
}
|
|
);
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA: dupIsin,
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toThrow(/Duplicate primaryIsin/);
|
|
|
|
// 2. Duplicate listing natural key
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple',
|
|
members: [],
|
|
});
|
|
const dupListing = emptyStageB();
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
dupListing.listings.push(
|
|
{ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null },
|
|
{ ...key, ibConid: 1, ibPrimaryExchange: 'NASDAQ', listedFrom: null, listedTo: null }
|
|
);
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: dupListing,
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toThrow(/Duplicate listing natural key/);
|
|
|
|
// 3. Duplicate provider_mapping PK
|
|
const dupMapping = emptyStageB();
|
|
dupMapping.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: null,
|
|
listedTo: null,
|
|
});
|
|
dupMapping.providerMappings.push(
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: null,
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: DEFAULT_VALID_FROM,
|
|
validTo: null,
|
|
}
|
|
);
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: dupMapping,
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toThrow(/Duplicate provider_mapping primary key/);
|
|
|
|
// 4. Duplicate Pass 6 listing outcome
|
|
const dupPass6: DelistingChainResult = {
|
|
continuities: [],
|
|
listingOutcomes: [
|
|
{ listingKey: key, delistReason: 'active', terminalReturn: null },
|
|
{ listingKey: key, delistReason: 'unknown_involuntary', terminalReturn: -0.3 },
|
|
],
|
|
conflicts: [],
|
|
stats: {
|
|
totalInputListings: 1,
|
|
processedListings: 1,
|
|
skippedMalformedEntries: 0,
|
|
skippedInvalidDates: 0,
|
|
skippedDuplicateKeys: 0,
|
|
continuitiesCreated: 0,
|
|
conflictsDetected: 0,
|
|
byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 0 },
|
|
},
|
|
};
|
|
const singleStageB = emptyStageB();
|
|
singleStageB.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: null,
|
|
listedTo: null,
|
|
});
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: singleStageB,
|
|
pass6: dupPass6,
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toThrow(/Duplicate listing outcome key/);
|
|
|
|
// 5. Duplicate existing DB listing rows for incoming natural key
|
|
const { client: dupDbClient, queries: dupDbQueries } = createMockClient(text => {
|
|
if (text.startsWith('SELECT') && text.includes('FROM instrument')) {
|
|
return {
|
|
rows: [
|
|
{
|
|
instrument_id: 7,
|
|
primary_isin: 'US0378331005',
|
|
primary_cusip: '037833100',
|
|
canonical_name: 'Apple',
|
|
security_type: 'common',
|
|
issuer_country: 'US',
|
|
},
|
|
],
|
|
};
|
|
}
|
|
if (text.startsWith('SELECT mic FROM exchange')) {
|
|
return { rows: [{ mic: 'XNAS' }] };
|
|
}
|
|
if (text.startsWith('SELECT') && text.includes('FROM listing')) {
|
|
return {
|
|
rows: [
|
|
{
|
|
listing_id: 1,
|
|
instrument_id: 7,
|
|
mic: 'XNAS',
|
|
ticker_root: 'AAPL',
|
|
class_suffix: '',
|
|
currency: 'USD',
|
|
ib_conid: null,
|
|
ib_primary_exchange: null,
|
|
listed_from: null,
|
|
listed_to: null,
|
|
delist_reason: null,
|
|
terminal_return: null,
|
|
},
|
|
{
|
|
listing_id: 2,
|
|
instrument_id: 7,
|
|
mic: 'XNAS',
|
|
ticker_root: 'AAPL',
|
|
class_suffix: '',
|
|
currency: 'USD',
|
|
ib_conid: null,
|
|
ib_primary_exchange: null,
|
|
listed_from: '2020-01-01',
|
|
listed_to: null,
|
|
delist_reason: null,
|
|
terminal_return: null,
|
|
},
|
|
],
|
|
};
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
await expect(
|
|
persistSecurityMaster(dupDbClient, {
|
|
stageA,
|
|
stageB: singleStageB,
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toThrow(/duplicate rows for natural key/);
|
|
expect(dupDbQueries.at(-1)?.text).toBe('ROLLBACK');
|
|
});
|
|
|
|
test('executes ROLLBACK and rethrows original error on mid-run failure (even if ROLLBACK fails)', async () => {
|
|
const boom = new Error('injected check violation');
|
|
const { client, queries } = createMockClient(text => {
|
|
if (text.startsWith('INSERT INTO instrument (')) {
|
|
throw boom;
|
|
}
|
|
if (text === 'ROLLBACK') {
|
|
throw new Error('rollback also failed');
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [],
|
|
});
|
|
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toBe(boom);
|
|
|
|
expect(queries.some(q => q.text === 'BEGIN')).toBe(true);
|
|
expect(queries.some(q => q.text === 'ROLLBACK')).toBe(true);
|
|
expect(queries.some(q => q.text === 'COMMIT')).toBe(false);
|
|
expect(formatListingNaturalKey({
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
})).toBe('US0378331005\u0000XNAS\u0000AAPL\u0000\u0000USD');
|
|
});
|
|
|
|
test('rejects overlapping calls on the same client before issuing BEGIN and allows sequential reuse', async () => {
|
|
let releaseFirstBegin!: () => void;
|
|
const firstBeginPaused = new Promise<void>(resolve => {
|
|
releaseFirstBegin = resolve;
|
|
});
|
|
let beginCount = 0;
|
|
|
|
const { client, queries } = createMockClient(async text => {
|
|
if (text === 'BEGIN') {
|
|
beginCount += 1;
|
|
if (beginCount === 1) {
|
|
await firstBeginPaused;
|
|
}
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
const emptyInput: PersistSecurityMasterInput = {
|
|
stageA: emptyStageA(),
|
|
stageB: emptyStageB(),
|
|
securityTypeByIsin: new Map(),
|
|
};
|
|
|
|
const firstCall = persistSecurityMaster(client, emptyInput);
|
|
const secondCall = persistSecurityMaster(client, emptyInput);
|
|
|
|
await expect(secondCall).rejects.toThrow(/overlapping calls on the same client/);
|
|
// Second call must reject before issuing a second BEGIN.
|
|
expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(1);
|
|
|
|
releaseFirstBegin();
|
|
const firstResult = await firstCall;
|
|
expect(firstResult.instrumentsInserted).toBe(0);
|
|
|
|
// Once the first call completes, sequential reuse of the same client succeeds.
|
|
const thirdResult = await persistSecurityMaster(client, emptyInput);
|
|
expect(thirdResult.instrumentsInserted).toBe(0);
|
|
expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(2);
|
|
});
|
|
|
|
test('counts each provider_mapping key once across matcher and override outcomes', async () => {
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const stageB = emptyStageB();
|
|
stageB.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: '1980-12-12',
|
|
listedTo: null,
|
|
});
|
|
stageB.providerMappings.push(
|
|
// Existing row skipped by matcher because override exists, then updated by override
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: '1980-12-12',
|
|
validTo: null,
|
|
},
|
|
// Fresh row inserted by matcher, then immediately updated by override -> net outcome: inserted
|
|
{
|
|
source: 'ib',
|
|
sourceId: '265598',
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: '1980-12-12',
|
|
validTo: null,
|
|
},
|
|
// Existing row unchanged by matcher and not in override -> unchanged
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'AAPL:US',
|
|
listingKey: key,
|
|
method: 'tier3_ticker_span',
|
|
validFrom: '2010-01-04',
|
|
validTo: null,
|
|
}
|
|
);
|
|
|
|
const { client } = createMockClient((text, values) => {
|
|
if (text.startsWith('SELECT mic FROM exchange')) {
|
|
return { rows: [{ mic: 'XNAS' }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument (')) {
|
|
return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
|
const ids = (values?.[0] as number[]) ?? [];
|
|
return { rows: ids.map(() => ({ inserted: 1 })) };
|
|
}
|
|
if (text.startsWith('INSERT INTO listing (')) {
|
|
return {
|
|
rows: [
|
|
{
|
|
listing_id: 10,
|
|
instrument_id: 1,
|
|
mic: 'XNAS',
|
|
ticker_root: 'AAPL',
|
|
class_suffix: '',
|
|
currency: 'USD',
|
|
},
|
|
],
|
|
};
|
|
}
|
|
if (text.includes('INTO listing_symbol_history')) {
|
|
return { rows: [{ inserted_count: 1, updated_count: 0 }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO provider_mapping')) {
|
|
// Only the fresh ib row is inserted by matcher; eod is skipped by override guard; qm unchanged.
|
|
return {
|
|
rows: [
|
|
{ source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: true },
|
|
],
|
|
};
|
|
}
|
|
if (text.includes('WITH enforced AS')) {
|
|
return {
|
|
rows: [
|
|
{ source: 'eod', source_id: 'AAPL.US', valid_from: '1980-12-12', inserted: false },
|
|
{ source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: false },
|
|
{ source: 'qm', source_id: 'OVR_NEW:US', valid_from: '2021-01-01', inserted: true },
|
|
{ source: 'qm', source_id: 'OVR_SAME:US', valid_from: '2021-01-01', inserted: null },
|
|
],
|
|
};
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
const result = await persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
|
});
|
|
|
|
expect(result.overridesApplied).toBe(4);
|
|
expect(result.providerMappingsInserted).toBe(2); // ib (fresh+overridden) + OVR_NEW
|
|
expect(result.providerMappingsUpdated).toBe(1); // eod (existing+overridden)
|
|
expect(result.providerMappingsUnchanged).toBe(2); // qm AAPL:US + OVR_SAME
|
|
});
|
|
|
|
test('pass4 omitted leaves conflict SQL and counts identical to non-Pass-4 behavior', async () => {
|
|
const stageA = emptyStageA();
|
|
stageA.conflicts.push({
|
|
source: 'eod',
|
|
sourceId: 'BAD.US',
|
|
conflictKind: 'isin_cusip_mismatch',
|
|
detail: {
|
|
isin: 'US0378331005',
|
|
cusip: '594918104',
|
|
country: 'US',
|
|
derivedIsin: 'US5949181045',
|
|
},
|
|
});
|
|
const stageB = emptyStageB();
|
|
|
|
const { client, queries } = createMockClient();
|
|
const result = await persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>(),
|
|
});
|
|
|
|
expect(result.conflictsInserted).toBe(1);
|
|
expect(result.conflictsUnchanged).toBe(0);
|
|
expect(result.conflictsDeduplicated).toBe(0);
|
|
|
|
// Must run ONLY the 3-column non-Pass-4 existence query, never the Pass 4 JSONB detail query.
|
|
const conflictSelects = queries.filter(q => q.text.includes('FROM resolution_conflict rc'));
|
|
expect(conflictSelects.length).toBe(1);
|
|
expect(conflictSelects[0]?.text).not.toContain('rc.detail = u.detail');
|
|
});
|
|
|
|
test('pass4 supplied preserves distinct pairs sharing a left endpoint, deduplicates exact duplicates, and checks rc.detail = u.detail', async () => {
|
|
const stageA = emptyStageA();
|
|
const stageB = emptyStageB();
|
|
|
|
const conflictPair1: PriceCrossCheckConflictRecord = {
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
conflictKind: 'price_ratio_mismatch',
|
|
detail: {
|
|
left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' },
|
|
right: { source: 'qm', sourceId: 'AAPL:US', currency: 'USD' },
|
|
verdict: 'ratio_mismatch',
|
|
usableDates: 5,
|
|
medianRatio: 1.5,
|
|
priceCorr: 0.99,
|
|
ratioTolerance: 0.02,
|
|
minCorrelation: 0.9,
|
|
},
|
|
};
|
|
const conflictPair2SameLeft: PriceCrossCheckConflictRecord = {
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
conflictKind: 'price_ratio_mismatch',
|
|
detail: {
|
|
left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' },
|
|
right: { source: 'ceo', sourceId: 'AAPL', currency: 'USD' },
|
|
verdict: 'ratio_mismatch',
|
|
usableDates: 5,
|
|
medianRatio: 2.0,
|
|
priceCorr: 0.98,
|
|
ratioTolerance: 0.02,
|
|
minCorrelation: 0.9,
|
|
},
|
|
};
|
|
|
|
const pass4: PriceCrossCheckResult = {
|
|
results: [],
|
|
conflicts: [conflictPair1, conflictPair2SameLeft, conflictPair1], // 1 exact duplicate
|
|
stats: {
|
|
pairsIn: 2,
|
|
invalidPairs: 0,
|
|
byVerdict: {
|
|
unsupported_currency_pair: 0,
|
|
insufficient_data: 0,
|
|
ratio_mismatch: 2,
|
|
low_correlation: 0,
|
|
confirmed: 0,
|
|
},
|
|
conflictsEmitted: 3,
|
|
droppedInvalidCloses: 0,
|
|
droppedConflictingCloses: 0,
|
|
droppedInvalidFxRates: 0,
|
|
droppedConflictingFxRates: 0,
|
|
skippedMissingFxDates: 0,
|
|
},
|
|
};
|
|
|
|
// First run: neither pair exists in DB -> both inserted, 1 exact duplicate deduplicated.
|
|
const first = createMockClient();
|
|
const firstResult = await persistSecurityMaster(first.client, {
|
|
stageA,
|
|
stageB,
|
|
pass4,
|
|
securityTypeByIsin: new Map<string, SecurityType>(),
|
|
});
|
|
|
|
expect(firstResult.conflictsInserted).toBe(2);
|
|
expect(firstResult.conflictsUnchanged).toBe(0);
|
|
expect(firstResult.conflictsDeduplicated).toBe(1);
|
|
|
|
const pass4Selects = first.queries.filter(
|
|
q => q.text.includes('FROM resolution_conflict rc') && q.text.includes('rc.detail = u.detail')
|
|
);
|
|
expect(pass4Selects.length).toBe(1);
|
|
// Regression: PostgreSQL UTF-8 text/varchar rejects NUL bytes (\u0000); Pass 4 existence check
|
|
// must pass integer row indices ($5::int4[]) rather than NUL-delimited internal keys.
|
|
expect(pass4Selects[0]?.values?.[4]).toEqual([0, 1]);
|
|
for (const param of pass4Selects[0]?.values ?? []) {
|
|
if (Array.isArray(param)) {
|
|
for (const item of param) {
|
|
if (typeof item === 'string') {
|
|
expect(item.includes('\u0000')).toBe(false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const conflictInserts = first.queries.filter(q =>
|
|
q.text.startsWith('INSERT INTO resolution_conflict')
|
|
);
|
|
expect(conflictInserts.length).toBe(1);
|
|
expect((conflictInserts[0]?.values?.[0] as string[]).length).toBe(2);
|
|
|
|
// Second run: simulate pair 1 (index 0 in sorted slice) already existing in DB -> only pair 2 inserted.
|
|
const second = createMockClient(text => {
|
|
if (text.includes('FROM resolution_conflict rc') && text.includes('rc.detail = u.detail')) {
|
|
return { rows: [{ row_idx: 0 }] };
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
const secondResult = await persistSecurityMaster(second.client, {
|
|
stageA,
|
|
stageB,
|
|
pass4,
|
|
securityTypeByIsin: new Map<string, SecurityType>(),
|
|
});
|
|
|
|
expect(secondResult.conflictsUnchanged).toBe(1);
|
|
expect(secondResult.conflictsInserted).toBe(1);
|
|
expect(secondResult.conflictsDeduplicated).toBe(1);
|
|
});
|
|
|
|
test('rejects invalid pass4.conflicts shape before BEGIN', async () => {
|
|
const { client, queries } = createMockClient();
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA: emptyStageA(),
|
|
stageB: emptyStageB(),
|
|
pass4: { conflicts: 'bad' } as unknown as PriceCrossCheckResult,
|
|
securityTypeByIsin: new Map<string, SecurityType>(),
|
|
})
|
|
).rejects.toThrow(TypeError);
|
|
expect(queries.length).toBe(0);
|
|
});
|
|
|
|
test('selects deduplicated dated-only stale-fallback targets with override guards and parameterized SQL', async () => {
|
|
const hostileSourceId = "HOSTILE'ID;DELETE";
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
const validKey = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const missingKey = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XXXX',
|
|
tickerRoot: 'MISS',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const stageB = emptyStageB();
|
|
stageB.listings.push({
|
|
...validKey,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: '2012-05-18',
|
|
listedTo: null,
|
|
});
|
|
stageB.providerMappings.push(
|
|
// Dated-only with two dated rows -> must appear ONCE in staleFallbackTargets
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'DATED_MULTI.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: '2012-05-18',
|
|
validTo: '2019-12-31',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'DATED_MULTI.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: '2020-01-01',
|
|
validTo: null,
|
|
},
|
|
// Dated-only with hostile sourceId -> must be parameterized, never interpolated
|
|
{
|
|
source: 'qm',
|
|
sourceId: hostileSourceId,
|
|
listingKey: validKey,
|
|
method: 'tier3_ticker_span',
|
|
validFrom: '2015-01-02',
|
|
validTo: null,
|
|
},
|
|
// Fallback-only (null) -> excluded
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'FALLBACK_NULL.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: null,
|
|
},
|
|
// Fallback-only (explicit DEFAULT_VALID_FROM) -> excluded
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'FALLBACK_EXPLICIT.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: DEFAULT_VALID_FROM,
|
|
validTo: null,
|
|
},
|
|
// Mixed fallback-first then dated -> excluded
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'MIXED_FB_FIRST.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: '2014-12-31',
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'MIXED_FB_FIRST.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: '2015-01-01',
|
|
validTo: null,
|
|
},
|
|
// Mixed dated-first then fallback -> excluded
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'MIXED_DATED_FIRST.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: '2015-01-01',
|
|
validTo: null,
|
|
},
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'MIXED_DATED_FIRST.US',
|
|
listingKey: validKey,
|
|
method: 'tier1_isin',
|
|
validFrom: DEFAULT_VALID_FROM,
|
|
validTo: '2014-12-31',
|
|
},
|
|
// Dated mapping whose listing is skipped (missing_listing) -> excluded
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'SKIPPED_LISTING.US',
|
|
listingKey: missingKey,
|
|
method: 'tier1_isin',
|
|
validFrom: '2018-01-01',
|
|
validTo: null,
|
|
}
|
|
);
|
|
|
|
const { client, queries } = createMockClient((text, values) => {
|
|
if (text.startsWith('SELECT mic FROM exchange')) {
|
|
return { rows: [{ mic: 'XNAS' }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument (')) {
|
|
return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
|
const ids = (values?.[0] as number[]) ?? [];
|
|
return { rows: ids.map(() => ({ inserted: 1 })) };
|
|
}
|
|
if (text.startsWith('INSERT INTO listing (')) {
|
|
return {
|
|
rows: [
|
|
{
|
|
listing_id: 10,
|
|
instrument_id: 1,
|
|
mic: 'XNAS',
|
|
ticker_root: 'AAPL',
|
|
class_suffix: '',
|
|
currency: 'USD',
|
|
},
|
|
],
|
|
};
|
|
}
|
|
if (text.includes('INTO listing_symbol_history')) {
|
|
return { rows: [{ inserted_count: 1, updated_count: 0 }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO provider_mapping')) {
|
|
const sources = (values?.[0] as string[]) ?? [];
|
|
const sourceIds = (values?.[1] as string[]) ?? [];
|
|
const validFroms = (values?.[2] as string[]) ?? [];
|
|
return {
|
|
rows: sources.map((source, i) => ({
|
|
source,
|
|
source_id: sourceIds[i],
|
|
valid_from: validFroms[i],
|
|
inserted: true,
|
|
})),
|
|
};
|
|
}
|
|
if (text.includes('DELETE FROM provider_mapping')) {
|
|
return { rows: [{ deleted_count: 2 }] };
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
const result = await persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
|
});
|
|
|
|
const deleteQueries = queries.filter(q => q.text.includes('DELETE FROM provider_mapping'));
|
|
expect(deleteQueries).toHaveLength(1);
|
|
const dq = deleteQueries[0]!;
|
|
expect(dq.text).toContain("pm.method <> 'override'");
|
|
expect(dq.text).toContain('NOT EXISTS');
|
|
expect(dq.text).toContain('FROM override o');
|
|
expect(dq.text).not.toContain(hostileSourceId);
|
|
expect(dq.values).toEqual([
|
|
['eod', 'qm'],
|
|
['DATED_MULTI.US', hostileSourceId],
|
|
DEFAULT_VALID_FROM,
|
|
]);
|
|
|
|
expect(result.providerMappingsDeletedStaleFallback).toBe(2);
|
|
expect(result.providerMappingsInserted).toBe(9);
|
|
expect(result.providerMappingsUpdated).toBe(0);
|
|
expect(result.providerMappingsUnchanged).toBe(0);
|
|
expect(result.providerMappingsSkipped).toBe(1);
|
|
});
|
|
|
|
test('batches stale-fallback deletes by chunkSize and sums counts independently of upsert totals', async () => {
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const stageB = emptyStageB();
|
|
stageB.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: '2012-05-18',
|
|
listedTo: null,
|
|
});
|
|
for (let i = 0; i < 5; i++) {
|
|
stageB.providerMappings.push({
|
|
source: 'eod',
|
|
sourceId: `S${i}.US`,
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: '2012-05-18',
|
|
validTo: null,
|
|
});
|
|
}
|
|
|
|
const chunkDeleteCounts = [1, 2, 0];
|
|
let deleteChunkIdx = 0;
|
|
const { client, queries } = createMockClient((text, values) => {
|
|
if (text.startsWith('SELECT mic FROM exchange')) {
|
|
return { rows: [{ mic: 'XNAS' }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument (')) {
|
|
return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
|
const ids = (values?.[0] as number[]) ?? [];
|
|
return { rows: ids.map(() => ({ inserted: 1 })) };
|
|
}
|
|
if (text.startsWith('INSERT INTO listing (')) {
|
|
return {
|
|
rows: [
|
|
{
|
|
listing_id: 10,
|
|
instrument_id: 1,
|
|
mic: 'XNAS',
|
|
ticker_root: 'AAPL',
|
|
class_suffix: '',
|
|
currency: 'USD',
|
|
},
|
|
],
|
|
};
|
|
}
|
|
if (text.includes('INTO listing_symbol_history')) {
|
|
return { rows: [{ inserted_count: 1, updated_count: 0 }] };
|
|
}
|
|
if (text.startsWith('INSERT INTO provider_mapping')) {
|
|
const sources = (values?.[0] as string[]) ?? [];
|
|
const sourceIds = (values?.[1] as string[]) ?? [];
|
|
const validFroms = (values?.[2] as string[]) ?? [];
|
|
return {
|
|
rows: sources.map((source, i) => ({
|
|
source,
|
|
source_id: sourceIds[i],
|
|
valid_from: validFroms[i],
|
|
inserted: true,
|
|
})),
|
|
};
|
|
}
|
|
if (text.includes('DELETE FROM provider_mapping')) {
|
|
const deleted = chunkDeleteCounts[deleteChunkIdx++] ?? 0;
|
|
return { rows: [{ deleted_count: deleted }] };
|
|
}
|
|
return { rows: [] };
|
|
});
|
|
|
|
const result = await persistSecurityMaster(
|
|
client,
|
|
{
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
|
},
|
|
{ chunkSize: 2 }
|
|
);
|
|
|
|
const deleteQueries = queries.filter(q => q.text.includes('DELETE FROM provider_mapping'));
|
|
expect(deleteQueries).toHaveLength(3);
|
|
expect(deleteQueries.map(q => (q.values?.[1] as string[]).length)).toEqual([2, 2, 1]);
|
|
expect(result.providerMappingsDeletedStaleFallback).toBe(3);
|
|
expect(result.providerMappingsInserted).toBe(5);
|
|
expect(result.providerMappingsUpdated).toBe(0);
|
|
expect(result.providerMappingsUnchanged).toBe(0);
|
|
});
|
|
|
|
test('issues zero DELETE queries when no dated-only provider_mapping pairs exist', async () => {
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const stageB = emptyStageB();
|
|
stageB.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: null,
|
|
listedTo: null,
|
|
});
|
|
stageB.providerMappings.push(
|
|
{
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: null,
|
|
validTo: null,
|
|
},
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'AAPL:US',
|
|
listingKey: key,
|
|
method: 'tier3_ticker_span',
|
|
validFrom: DEFAULT_VALID_FROM,
|
|
validTo: '2014-12-31',
|
|
},
|
|
{
|
|
source: 'qm',
|
|
sourceId: 'AAPL:US',
|
|
listingKey: key,
|
|
method: 'tier3_ticker_span',
|
|
validFrom: '2015-01-01',
|
|
validTo: null,
|
|
}
|
|
);
|
|
|
|
const { client, queries } = createMockClient();
|
|
const result = await persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
|
});
|
|
|
|
expect(queries.filter(q => q.text.includes('DELETE FROM provider_mapping'))).toHaveLength(0);
|
|
expect(result.providerMappingsDeletedStaleFallback).toBe(0);
|
|
expect(result.providerMappingsInserted).toBe(3);
|
|
});
|
|
|
|
test('rolls back instead of committing when a step after the stale-fallback DELETE fails', async () => {
|
|
const stageA = emptyStageA();
|
|
stageA.instruments.push({
|
|
primaryIsin: 'US0378331005',
|
|
primaryCusip: '037833100',
|
|
issuerCountry: 'US',
|
|
canonicalName: 'Apple Inc.',
|
|
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
|
});
|
|
const key = {
|
|
primaryIsin: 'US0378331005',
|
|
mic: 'XNAS',
|
|
tickerRoot: 'AAPL',
|
|
classSuffix: '',
|
|
currency: 'USD',
|
|
};
|
|
const stageB = emptyStageB();
|
|
stageB.listings.push({
|
|
...key,
|
|
ibConid: null,
|
|
ibPrimaryExchange: null,
|
|
listedFrom: '2012-05-18',
|
|
listedTo: null,
|
|
});
|
|
stageB.providerMappings.push({
|
|
source: 'eod',
|
|
sourceId: 'AAPL.US',
|
|
listingKey: key,
|
|
method: 'tier1_isin',
|
|
validFrom: '2012-05-18',
|
|
validTo: null,
|
|
});
|
|
|
|
const base = createMockClient();
|
|
const queries: RecordedQuery[] = [];
|
|
const client: SecurityMasterQueryable = {
|
|
release: () => undefined,
|
|
async query<Row = Record<string, unknown>>(text: string, values?: readonly unknown[]) {
|
|
if (text.includes('WITH enforced AS')) {
|
|
queries.push({ text, values });
|
|
throw new Error('override enforcement failed');
|
|
}
|
|
const res = await base.client.query<Row>(text, values);
|
|
queries.push({ text, values });
|
|
return res;
|
|
},
|
|
};
|
|
|
|
await expect(
|
|
persistSecurityMaster(client, {
|
|
stageA,
|
|
stageB,
|
|
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
|
})
|
|
).rejects.toThrow('override enforcement failed');
|
|
|
|
const texts = queries.map(q => q.text.trim());
|
|
const deleteIdx = texts.findIndex(t => t.includes('DELETE FROM provider_mapping'));
|
|
expect(texts[0]).toBe('BEGIN');
|
|
expect(deleteIdx).toBeGreaterThan(0);
|
|
expect(texts.at(-1)).toBe('ROLLBACK');
|
|
expect(texts).not.toContain('COMMIT');
|
|
});
|
|
});
|