diff --git a/apps/stock/data-pipeline/src/security-master/persist.ts b/apps/stock/data-pipeline/src/security-master/persist.ts index b3a65caa..e5f29add 100644 --- a/apps/stock/data-pipeline/src/security-master/persist.ts +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -43,6 +43,8 @@ export const MAX_PERSIST_CHUNK_SIZE = 5000; */ export const SECURITY_MASTER_PERSIST_LOCK_NAMESPACE = 0x534d5053; +const activePersistClients = new WeakSet(); + /** * Fixed confidence scores written to `provider_mapping.confidence` (`NUMERIC(4, 3)`). * `design/DATA-CONTRACTS.md` does not specify numeric values for `tier1_isin` / `tier2_cusip` / @@ -191,10 +193,23 @@ interface UpsertFlagRow { inserted: boolean; } +interface SymbolHistoryUpsertCountsRow { + inserted_count: number; + updated_count: number; +} + +interface ProviderMappingUpsertRow { + source: string; + source_id: string; + valid_from: string; + inserted: boolean; +} + interface OverrideEnforceRow { - total_overrides: number; - inserted_overrides: number; - updated_overrides: number; + source: string; + source_id: string; + valid_from: string; + inserted: boolean | null; } interface ExistingConflictRow { @@ -243,6 +258,7 @@ interface PreparedSymbolHistoryRow { readonly validFrom: string; readonly validTo: string | null; readonly source: string; + readonly previousValidFrom: string | null; } interface PreparedProviderMapping { @@ -1019,13 +1035,15 @@ async function persistWithinTransaction( listingsUpdated += slice.length; } - // listing_symbol_history for all persisted listings + // listing_symbol_history for all persisted listings (replaces loader-generated interval + // when listed_from changes while preserving unrelated historical aliases). const symbolHistoryRows: PreparedSymbolHistoryRow[] = []; for (const item of preparedListings) { const listingId = listingIdByKey.get(item.naturalKey); if (listingId === undefined) { continue; } + const existing = existingByDbKey.get(item.dbNaturalKey); const ticker = item.classSuffix.length > 0 ? `${item.tickerRoot}.${item.classSuffix}` : item.tickerRoot; symbolHistoryRows.push({ @@ -1034,48 +1052,88 @@ async function persistWithinTransaction( validFrom: item.listedFrom ?? DEFAULT_VALID_FROM, validTo: item.listedTo, source: 'eod', + previousValidFrom: + existing !== undefined ? (existing.listed_from ?? DEFAULT_VALID_FROM) : null, }); } for (let offset = 0; offset < symbolHistoryRows.length; offset += chunkSize) { const slice = symbolHistoryRows.slice(offset, offset + chunkSize); - const res = await client.query( - `INSERT INTO listing_symbol_history ( - listing_id, - ticker, - valid_from, - valid_to, - source + const res = await client.query( + `WITH incoming AS ( + SELECT * + FROM UNNEST( + $1::int4[], + $2::varchar[], + $3::date[], + $4::date[], + $5::varchar[], + $6::date[] + ) AS u(listing_id, ticker, valid_from, valid_to, source, prev_valid_from) + ), + deleted_stale AS ( + DELETE FROM listing_symbol_history AS lsh + USING incoming AS i + WHERE lsh.listing_id = i.listing_id + AND lsh.ticker = i.ticker + AND lsh.source = i.source + AND i.prev_valid_from IS NOT NULL + AND lsh.valid_from = i.prev_valid_from + AND lsh.valid_from IS DISTINCT FROM i.valid_from + RETURNING lsh.listing_id, lsh.ticker + ), + upserted AS ( + INSERT INTO listing_symbol_history ( + listing_id, + ticker, + valid_from, + valid_to, + source + ) + SELECT + i.listing_id, + i.ticker, + i.valid_from, + i.valid_to, + i.source + FROM incoming AS i + ON CONFLICT (listing_id, ticker, valid_from) DO UPDATE SET + valid_to = EXCLUDED.valid_to + WHERE listing_symbol_history.valid_to IS DISTINCT FROM EXCLUDED.valid_to + RETURNING listing_id, ticker, (xmax = 0) AS inserted ) - SELECT * - FROM UNNEST( - $1::int4[], - $2::varchar[], - $3::date[], - $4::date[], - $5::varchar[] - ) - ON CONFLICT (listing_id, ticker, valid_from) DO UPDATE SET - valid_to = EXCLUDED.valid_to - WHERE listing_symbol_history.valid_to IS DISTINCT FROM EXCLUDED.valid_to - RETURNING (xmax = 0) AS inserted`, + SELECT + ( + SELECT count(*)::int + FROM upserted u + WHERE u.inserted + AND NOT EXISTS ( + SELECT 1 + FROM deleted_stale d + WHERE d.listing_id = u.listing_id + AND d.ticker = u.ticker + ) + ) AS inserted_count, + ( + SELECT count(*)::int + FROM ( + SELECT listing_id, ticker FROM upserted WHERE NOT inserted + UNION + SELECT listing_id, ticker FROM deleted_stale + ) AS updated_keys + ) AS updated_count`, [ slice.map(row => row.listingId), slice.map(row => row.ticker), slice.map(row => row.validFrom), slice.map(row => row.validTo), slice.map(row => row.source), + slice.map(row => row.previousValidFrom), ] ); - let chunkInserted = 0; - let chunkUpdated = 0; - for (const row of res.rows) { - if (row.inserted) { - chunkInserted += 1; - } else { - chunkUpdated += 1; - } - } + const counts = res.rows[0]; + const chunkInserted = Number(counts?.inserted_count ?? 0); + const chunkUpdated = Number(counts?.updated_count ?? 0); listingSymbolHistoryInserted += chunkInserted; listingSymbolHistoryUpdated += chunkUpdated; listingSymbolHistoryUnchanged += slice.length - chunkInserted - chunkUpdated; @@ -1116,9 +1174,14 @@ async function persistWithinTransaction( }); } + const mappingOutcomeByKey = new Map(); + for (const row of preparedMappings) { + mappingOutcomeByKey.set(`${row.source}\u0000${row.sourceId}\u0000${row.validFrom}`, 'unchanged'); + } + for (let offset = 0; offset < preparedMappings.length; offset += chunkSize) { const slice = preparedMappings.slice(offset, offset + chunkSize); - const res = await client.query( + const res = await client.query( `INSERT INTO provider_mapping ( source, source_id, @@ -1169,7 +1232,11 @@ async function persistWithinTransaction( OR provider_mapping.method IS DISTINCT FROM EXCLUDED.method OR provider_mapping.confidence IS DISTINCT FROM EXCLUDED.confidence ) - RETURNING (xmax = 0) AS inserted`, + RETURNING + source, + source_id, + to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + (xmax = 0) AS inserted`, [ slice.map(row => row.source), slice.map(row => row.sourceId), @@ -1180,21 +1247,14 @@ async function persistWithinTransaction( slice.map(row => row.confidence), ] ); - let chunkInserted = 0; - let chunkUpdated = 0; for (const row of res.rows) { - if (row.inserted) { - chunkInserted += 1; - } else { - chunkUpdated += 1; - } + const key = `${row.source}\u0000${row.source_id}\u0000${row.valid_from}`; + mappingOutcomeByKey.set(key, row.inserted ? 'inserted' : 'updated'); } - providerMappingsInserted += chunkInserted; - providerMappingsUpdated += chunkUpdated; - providerMappingsUnchanged += slice.length - chunkInserted - chunkUpdated; } - // Enforce override precedence unconditionally across all rows in `override`. + // Enforce override precedence unconditionally across all rows in `override` and count each + // mapping key once according to its final insert/update/unchanged outcome across matcher + override. const overrideRes = await client.query( `WITH enforced AS ( INSERT INTO provider_mapping ( @@ -1228,16 +1288,47 @@ async function persistWithinTransaction( OR provider_mapping.method IS DISTINCT FROM 'override' OR provider_mapping.confidence IS DISTINCT FROM 1.000 OR provider_mapping.price_corr IS NOT NULL - RETURNING (xmax = 0) AS inserted + RETURNING + source, + source_id, + valid_from, + (xmax = 0) AS inserted ) SELECT - (SELECT count(*)::int FROM override) AS total_overrides, - (SELECT count(*) FILTER (WHERE inserted)::int FROM enforced) AS inserted_overrides, - (SELECT count(*) FILTER (WHERE NOT inserted)::int FROM enforced) AS updated_overrides` + o.source, + o.source_id, + to_char(o.valid_from, 'YYYY-MM-DD') AS valid_from, + e.inserted + FROM override o + LEFT JOIN enforced e + ON e.source = o.source + AND e.source_id = o.source_id + AND e.valid_from = o.valid_from` ); - const overrideStats = overrideRes.rows[0]; - const overridesApplied = Number(overrideStats?.total_overrides ?? 0); - providerMappingsInserted += Number(overrideStats?.inserted_overrides ?? 0); + const overridesApplied = overrideRes.rows.length; + for (const row of overrideRes.rows) { + const key = `${row.source}\u0000${row.source_id}\u0000${row.valid_from}`; + const prev = mappingOutcomeByKey.get(key); + if (row.inserted === true) { + mappingOutcomeByKey.set(key, 'inserted'); + } else if (row.inserted === false) { + if (prev !== 'inserted') { + mappingOutcomeByKey.set(key, 'updated'); + } + } else if (prev === undefined) { + mappingOutcomeByKey.set(key, 'unchanged'); + } + } + + for (const outcome of mappingOutcomeByKey.values()) { + if (outcome === 'inserted') { + providerMappingsInserted += 1; + } else if (outcome === 'updated') { + providerMappingsUpdated += 1; + } else { + providerMappingsUnchanged += 1; + } + } // --------------------------------------------------------------------------- // 4. Pass 5 resolution_conflict (all statuses preserved; no duplicate open rows) @@ -1479,22 +1570,33 @@ export async function persistSecurityMaster( const chunkSize = validateChunkSize(options.chunkSize); const { outcomeByListingKey } = validateInputsAndIndexPass6(input); - await client.query('BEGIN'); - try { - await client.query( - 'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))', - [SECURITY_MASTER_PERSIST_LOCK_NAMESPACE] + if (activePersistClients.has(client)) { + throw new Error( + 'persistSecurityMaster does not allow overlapping calls on the same client; use a dedicated PoolClient per concurrent call' ); - const result = await persistWithinTransaction(client, input, chunkSize, outcomeByListingKey); - await client.query('COMMIT'); - return result; - } catch (error) { + } + activePersistClients.add(client); + + try { + await client.query('BEGIN'); try { - await client.query('ROLLBACK'); - } catch { - // Preserve the original failure when ROLLBACK itself errors on a broken session. + await client.query( + 'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))', + [SECURITY_MASTER_PERSIST_LOCK_NAMESPACE] + ); + const result = await persistWithinTransaction(client, input, chunkSize, outcomeByListingKey); + await client.query('COMMIT'); + return result; + } catch (error) { + try { + await client.query('ROLLBACK'); + } catch { + // Preserve the original failure when ROLLBACK itself errors on a broken session. + } + throw error; } - throw error; + } finally { + activePersistClients.delete(client); } } diff --git a/test/postgres/security-master-persist.test.ts b/test/postgres/security-master-persist.test.ts index 3c547b93..65d6f009 100644 --- a/test/postgres/security-master-persist.test.ts +++ b/test/postgres/security-master-persist.test.ts @@ -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([['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([['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 () => { diff --git a/test/unit/security-master-persist.test.ts b/test/unit/security-master-persist.test.ts index 79c60815..c6f098ba 100644 --- a/test/unit/security-master-persist.test.ts +++ b/test/unit/security-master-persist.test.ts @@ -119,11 +119,26 @@ function createMockClient( })), } as unknown as SecurityMasterQueryResult; } - 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; + } + 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; + } + 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; } return { rows: [] } as SecurityMasterQueryResult; @@ -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(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([['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 + }); });