T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence

This commit is contained in:
Studio 2026-11-28 00:05:33 -05:00
parent d68577843e
commit 3ca206150e
3 changed files with 680 additions and 80 deletions

View file

@ -718,6 +718,8 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
);
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<{
@ -766,6 +768,118 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
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('persists Stage A, Stage B, and Pass 6 conflicts once and never reopens or modifies non-open rows', async () => {
@ -978,23 +1092,237 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
expect(result.skippedByReason.continuities.missing_from_listing).toBe(1);
});
test('rolls back all 7 tables atomically on a mid-run CHECK constraint violation', async () => {
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();
const preCounts = await getSevenTableCounts(f.pool);
const badTypes = new Map(fixture.securityTypeByIsin);
// Chunk size 2 -> chunk 1 inserts 2 valid instruments, chunk 2 hits Postgres CHECK violation
badTypes.set('US78486Q1013', 'bogus_type' as SecurityType);
// 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, { ...fixture, securityTypeByIsin: badTypes }, { chunkSize: 2 })
persistSecurityMaster(client, {
stageA: mutatedStageA,
stageB: mutatedStageB,
pass6: mutatedPass6,
securityTypeByIsin: mutatedTypes,
})
)
).rejects.toThrow(/security_type/);
).rejects.toThrow(/corporate_action_continuity|kind/);
const postCounts = await getSevenTableCounts(f.pool);
expect(postCounts).toEqual(preCounts);
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 () => {

View file

@ -119,11 +119,26 @@ function createMockClient(
})),
} as unknown as SecurityMasterQueryResult<Row>;
}
if (
text.startsWith('INSERT INTO listing_symbol_history') ||
text.startsWith('INSERT INTO provider_mapping') ||
text.startsWith('INSERT INTO corporate_action_continuity')
) {
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 })),
@ -131,7 +146,7 @@ function createMockClient(
}
if (text.includes('WITH enforced AS')) {
return {
rows: [{ total_overrides: 0, inserted_overrides: 0, updated_overrides: 0 }],
rows: [],
} as unknown as SecurityMasterQueryResult<Row>;
}
return { rows: [] } as SecurityMasterQueryResult<Row>;
@ -631,4 +646,159 @@ describe('persistSecurityMaster unit tests', () => {
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
});
});