diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index febcbba3..47446bcb 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -63,3 +63,17 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto - **Return correlation:** Computes two-pass centered Pearson correlation of consecutive log returns in a canonical common currency (converting CAD closes to USD via `cadClose / usdCad` for `CAD`/`USD` pairs so correlation is orientation-symmetric and unaffected by FX moves on flat USD prices), rounded to `4` decimal places (`provider_mapping.price_corr NUMERIC(5,4)`). Returns `null` when fewer than `3` returns exist or either series has zero variance. - **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside inclusive `[1 - 0.02, 1 + 0.02]`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`. - **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload. + +## Security Master Persistence (`persistSecurityMaster`) +`apps/stock/data-pipeline/src/security-master/persist.ts` persists in-memory Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 (`delisting-chains`) results into the `master` track PostgreSQL tables inside a single transaction guarded by `pg_advisory_xact_lock(0x534d5053, hashtext(current_schema()))`: + +- **Permanent IDs & idempotency:** Upserts `instrument` by `primary_isin` and resolves `listing` by `(instrument_id, mic, ticker_root, class_suffix, currency)` without ever changing or deleting an existing `instrument_id` or `listing_id`. +- **Override precedence:** After upserting `provider_mapping` (`tier1_isin = 0.990`, `tier2_cusip = 0.950`, `tier3_ticker_span = 0.800`), unconditionally enforces every row in `override` (`method = 'override'`, `confidence = 1.000`, `price_corr = NULL`) so re-runs with conflicting matcher output cannot overwrite director overrides. +- **No guessing:** Instruments with null/blank `canonicalName` or absent from `securityTypeByIsin`, and listings with an unknown `mic`, are skipped and counted per reason along with all dependent listings, mappings, Pass 6 outcomes, and continuities. +- **Batched writes & local benchmark:** All bulk reads/writes use parameterised `UNNEST` batches (default/max chunk size `5000`). Run the PostgreSQL integration suite and fixed-seed 20,000-instrument / 20,000-listing / 60,000-mapping benchmark against an isolated `stock_bot_safety_*` schema with: + +```bash +bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts +``` + +The benchmark logs measured core and total rows/s directly to stdout during unsandboxed host test runs. diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index fe944432..51d424f9 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -142,6 +142,26 @@ export { type UnresolvedBreakdownRow, } from './match-report'; +export { + canonicalizeJsonValue, + DEFAULT_PERSIST_CHUNK_SIZE, + DEFAULT_VALID_FROM, + formatListingNaturalKey, + MAX_PERSIST_CHUNK_SIZE, + persistSecurityMaster, + PROVIDER_MAPPING_CONFIDENCE, + SECURITY_MASTER_PERSIST_LOCK_NAMESPACE, + SECURITY_TYPES, + stableJsonStringify, + type PersistSecurityMasterInput, + type PersistSecurityMasterOptions, + type PersistSecurityMasterResult, + type PersistSecurityMasterSkippedByReason, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, + type SecurityType, +} from './persist'; + export { crossCheckPrices, DEFAULT_MIN_COMMON_DATES, diff --git a/apps/stock/data-pipeline/src/security-master/persist.ts b/apps/stock/data-pipeline/src/security-master/persist.ts new file mode 100644 index 00000000..b3a65caa --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -0,0 +1,1502 @@ +import type { + DelistingChainResult, + ListingDelistOutcome, + Pass6DelistReason, +} from './delisting-chains'; +import { compareAscii } from './exchange-pass1'; +import type { + StageAInstrumentCandidate, + StageAInstrumentMember, + StageAMatchResult, + StageASource, +} from './instrument-stage-a'; +import type { + ListingNaturalKey, + StageBListingCandidate, + StageBMatchMethod, + StageBMatchResult, + StageBProviderMappingCandidate, +} from './listing-stage-b'; + +export const SECURITY_TYPES = [ + 'common', + 'preferred', + 'unit', + 'warrant', + 'right', + 'etf', + 'cdr', + 'fx', +] as const; + +export type SecurityType = (typeof SECURITY_TYPES)[number]; + +export const DEFAULT_VALID_FROM = '1900-01-01' as const; + +export const DEFAULT_PERSIST_CHUNK_SIZE = 5000; +export const MAX_PERSIST_CHUNK_SIZE = 5000; + +/** + * Transaction-scoped PostgreSQL advisory lock namespace (`'SMPS'` = Security Master PerSist). + * Paired with `hashtext(current_schema())` so concurrent runs against the same schema serialize + * while isolated schemas (e.g. parallel `stock_bot_safety_*` tests) never contend. + */ +export const SECURITY_MASTER_PERSIST_LOCK_NAMESPACE = 0x534d5053; + +/** + * 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` / + * `tier3_ticker_span`; these constants are this module's deterministic interpretation, while + * `override` is always forced to `1.000`. + */ +export const PROVIDER_MAPPING_CONFIDENCE = { + tier1_isin: 0.99, + tier2_cusip: 0.95, + tier3_ticker_span: 0.8, + override: 1.0, +} as const satisfies Record; + +export interface SecurityMasterQueryResult> { + readonly rows: readonly Row[]; + readonly rowCount?: number | null; +} + +/** + * Structural `pg.PoolClient`-like interface so `persistSecurityMaster` has zero runtime dependency + * on `pg` and accepts any dedicated single-session PostgreSQL client. + */ +export interface SecurityMasterQueryable { + query>( + text: string, + values?: readonly unknown[] + ): Promise>; + release?: (...args: unknown[]) => unknown; +} + +export interface PersistSecurityMasterInput { + readonly stageA: StageAMatchResult; + readonly stageB: StageBMatchResult; + readonly pass6?: DelistingChainResult; + readonly securityTypeByIsin: ReadonlyMap; +} + +export interface PersistSecurityMasterOptions { + readonly chunkSize?: number; +} + +export interface PersistSecurityMasterSkippedByReason { + readonly instruments: { + readonly missing_canonical_name: number; + readonly missing_security_type: number; + }; + readonly listings: { + readonly skipped_instrument: number; + readonly missing_instrument: number; + readonly unknown_mic: number; + }; + readonly providerMappings: { + readonly missing_listing: number; + }; + readonly pass6Outcomes: { + readonly missing_listing: number; + }; + readonly continuities: { + readonly missing_from_listing: number; + readonly missing_to_listing: number; + readonly missing_both_listings: number; + }; +} + +export interface PersistSecurityMasterResult { + readonly instrumentsInserted: number; + readonly instrumentsUpdated: number; + readonly instrumentsUnchanged: number; + readonly instrumentsSkipped: number; + + readonly identifierHistoryInserted: number; + readonly identifierHistoryUnchanged: number; + + readonly listingsInserted: number; + readonly listingsUpdated: number; + readonly listingsUnchanged: number; + readonly listingsSkipped: number; + + readonly listingSymbolHistoryInserted: number; + readonly listingSymbolHistoryUpdated: number; + readonly listingSymbolHistoryUnchanged: number; + + readonly providerMappingsInserted: number; + readonly providerMappingsUpdated: number; + readonly providerMappingsUnchanged: number; + readonly providerMappingsSkipped: number; + + readonly overridesApplied: number; + + readonly conflictsInserted: number; + readonly conflictsUnchanged: number; + readonly conflictsDeduplicated: number; + + readonly pass6OutcomesApplied: number; + readonly pass6OutcomesSkipped: number; + + readonly continuitiesInserted: number; + readonly continuitiesUpdated: number; + readonly continuitiesUnchanged: number; + readonly continuitiesSkipped: number; + + readonly skippedByReason: PersistSecurityMasterSkippedByReason; + readonly instrumentIdByIsin: ReadonlyMap; + readonly listingIdByKey: ReadonlyMap; +} + +interface ExistingInstrumentRow { + instrument_id: number; + primary_isin: string; + primary_cusip: string | null; + canonical_name: string; + security_type: string; + issuer_country: string | null; +} + +interface InsertedInstrumentRow { + instrument_id: number; + primary_isin: string; +} + +interface ExistingListingRow { + listing_id: number; + instrument_id: number; + mic: string; + ticker_root: string; + class_suffix: string; + currency: string; + ib_conid: number | string | null; + ib_primary_exchange: string | null; + listed_from: string | null; + listed_to: string | null; + delist_reason: string | null; + terminal_return: number | string | null; +} + +interface InsertedListingRow { + listing_id: number; + instrument_id: number; + mic: string; + ticker_root: string; + class_suffix: string; + currency: string; +} + +interface UpsertFlagRow { + inserted: boolean; +} + +interface OverrideEnforceRow { + total_overrides: number; + inserted_overrides: number; + updated_overrides: number; +} + +interface ExistingConflictRow { + source: string; + source_id: string; + conflict_kind: string; +} + +interface PreparedInstrument { + readonly primaryIsin: string; + readonly primaryCusip: string | null; + readonly canonicalName: string; + readonly securityType: SecurityType; + readonly issuerCountry: string; + readonly bestSource: StageASource; +} + +interface PreparedListing { + readonly naturalKey: string; + readonly dbNaturalKey: string; + readonly instrumentId: number; + readonly mic: string; + readonly tickerRoot: string; + readonly classSuffix: string; + readonly currency: string; + readonly ibConid: number | null; + readonly ibPrimaryExchange: string | null; + readonly listedFrom: string | null; + readonly listedTo: string | null; + readonly outcome: ListingDelistOutcome | undefined; +} + +interface ListingUpdatePayload { + readonly listingId: number; + readonly ibConid: number | null; + readonly ibPrimaryExchange: string | null; + readonly listedFrom: string | null; + readonly listedTo: string | null; + readonly delistReason: Pass6DelistReason | string | null; + readonly terminalReturn: string | null; +} + +interface PreparedSymbolHistoryRow { + readonly listingId: number; + readonly ticker: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly source: string; +} + +interface PreparedProviderMapping { + readonly source: string; + readonly sourceId: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly listingId: number; + readonly method: StageBMatchMethod; + readonly confidence: string; +} + +interface PreparedConflict { + readonly key: string; + readonly source: string; + readonly sourceId: string; + readonly conflictKind: string; + readonly detailJson: string; +} + +interface PreparedContinuity { + readonly fromListingId: number; + readonly toListingId: number; + readonly effectiveDate: string; + readonly kind: string; +} + +/** + * Formats a `ListingNaturalKey` using NUL separators, matching `listing-stage-b.ts` and + * `delisting-chains.ts` so callers can look up permanent `listing_id`s from `listingIdByKey`. + */ +export function formatListingNaturalKey(key: Readonly): string { + return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}`; +} + +function formatDbListingNaturalKey( + instrumentId: number, + mic: string, + tickerRoot: string, + classSuffix: string, + currency: string +): string { + return `${instrumentId}\u0000${mic}\u0000${tickerRoot}\u0000${classSuffix}\u0000${currency}`; +} + +/** + * Recursively produces a JSON-compatible value with ASCII-sorted object keys so `detail` JSONB + * payloads are byte-for-byte deterministic regardless of JS property insertion order. + */ +export function canonicalizeJsonValue(value: unknown): unknown { + if (value === null || typeof value === 'boolean' || typeof value === 'string') { + return value; + } + if (typeof value === 'number') { + return Number.isFinite(value) ? value : null; + } + if (Array.isArray(value)) { + return value.map(item => (item === undefined ? null : canonicalizeJsonValue(item))); + } + if (typeof value === 'object') { + const record = value as Record; + const keys = Object.keys(record).sort(compareAscii); + const out: Record = {}; + for (const key of keys) { + const prop = record[key]; + if (prop !== undefined) { + out[key] = canonicalizeJsonValue(prop); + } + } + return out; + } + return null; +} + +export function stableJsonStringify(value: unknown): string { + return JSON.stringify(canonicalizeJsonValue(value)); +} + +function assertDedicatedQueryable(client: SecurityMasterQueryable): void { + if ( + client === null || + client === undefined || + typeof client !== 'object' || + typeof client.query !== 'function' + ) { + throw new TypeError( + 'persistSecurityMaster requires a PoolClient-like queryable with a query() method' + ); + } + const candidate = client as unknown as Record; + const looksLikePool = + typeof candidate.totalCount === 'number' && + typeof candidate.idleCount === 'number' && + typeof candidate.release !== 'function'; + if (looksLikePool) { + throw new TypeError( + 'persistSecurityMaster requires a dedicated PoolClient connection, not a pg.Pool (BEGIN/COMMIT must stay on one session)' + ); + } +} + +function validateChunkSize(chunkSize: number | undefined): number { + const resolved = chunkSize ?? DEFAULT_PERSIST_CHUNK_SIZE; + if (!Number.isInteger(resolved) || resolved < 1 || resolved > MAX_PERSIST_CHUNK_SIZE) { + throw new RangeError( + `chunkSize must be an integer between 1 and ${MAX_PERSIST_CHUNK_SIZE}, got ${String(resolved)}` + ); + } + return resolved; +} + +function selectBestMemberSource(members: readonly StageAInstrumentMember[]): StageASource { + let bestSource: StageASource = 'eod'; + let bestRank = Number.POSITIVE_INFINITY; + for (const member of members) { + const methodRank = member.method === 'tier1_isin' ? 0 : 2; + const sourceRank = member.source === 'ib' ? 0 : 1; + const rank = methodRank + sourceRank; + if (rank < bestRank) { + bestRank = rank; + bestSource = member.source; + if (bestRank === 0) { + break; + } + } + } + return bestSource; +} + +function normalizeNullableBigInt(value: number | string | null | undefined): number | null { + if (value === null || value === undefined) { + return null; + } + return Number(value); +} + +function normalizeNullableNumeric6(value: number | string | null | undefined): string | null { + if (value === null || value === undefined) { + return null; + } + const parsed = typeof value === 'number' ? value : Number(value); + return parsed.toFixed(6); +} + +function validateInputsAndIndexPass6(input: PersistSecurityMasterInput): { + outcomeByListingKey: Map; +} { + if (input === null || input === undefined || typeof input !== 'object') { + throw new TypeError('persistSecurityMaster requires an input object'); + } + if (!input.stageA || !Array.isArray(input.stageA.instruments)) { + throw new TypeError('persistSecurityMaster requires stageA.instruments'); + } + if (!input.stageB || !Array.isArray(input.stageB.listings)) { + throw new TypeError('persistSecurityMaster requires stageB.listings'); + } + if (!(input.securityTypeByIsin instanceof Map) && typeof input.securityTypeByIsin?.get !== 'function') { + throw new TypeError('persistSecurityMaster requires a securityTypeByIsin Map'); + } + + const seenIsins = new Set(); + for (const inst of input.stageA.instruments) { + if (seenIsins.has(inst.primaryIsin)) { + throw new Error(`Duplicate primaryIsin in stageA.instruments: "${inst.primaryIsin}"`); + } + seenIsins.add(inst.primaryIsin); + } + + const seenListingKeys = new Set(); + for (const listing of input.stageB.listings) { + const key = formatListingNaturalKey(listing); + if (seenListingKeys.has(key)) { + throw new Error( + `Duplicate listing natural key in stageB.listings: ${listing.primaryIsin}/${listing.mic}/${listing.tickerRoot}/${listing.classSuffix}/${listing.currency}` + ); + } + seenListingKeys.add(key); + } + + const seenMappingKeys = new Set(); + for (const mapping of input.stageB.providerMappings) { + const validFrom = mapping.validFrom ?? DEFAULT_VALID_FROM; + const pk = `${mapping.source}\u0000${mapping.sourceId}\u0000${validFrom}`; + if (seenMappingKeys.has(pk)) { + throw new Error( + `Duplicate provider_mapping primary key in stageB.providerMappings: (${mapping.source}, ${mapping.sourceId}, ${validFrom})` + ); + } + seenMappingKeys.add(pk); + } + + const outcomeByListingKey = new Map(); + if (input.pass6 !== undefined) { + for (const outcome of input.pass6.listingOutcomes) { + const key = formatListingNaturalKey(outcome.listingKey); + if (outcomeByListingKey.has(key)) { + throw new Error( + `Duplicate listing outcome key in pass6.listingOutcomes: ${outcome.listingKey.primaryIsin}/${outcome.listingKey.mic}/${outcome.listingKey.tickerRoot}/${outcome.listingKey.classSuffix}/${outcome.listingKey.currency}` + ); + } + outcomeByListingKey.set(key, outcome); + } + + const seenContinuityKeys = new Set(); + for (const continuity of input.pass6.continuities) { + const pk = `${formatListingNaturalKey(continuity.fromListingKey)}\u0000${continuity.effectiveDate}`; + if (seenContinuityKeys.has(pk)) { + throw new Error( + `Duplicate corporate_action_continuity key in pass6.continuities: ${continuity.fromListingKey.primaryIsin}/${continuity.fromListingKey.mic}/${continuity.fromListingKey.tickerRoot} @ ${continuity.effectiveDate}` + ); + } + seenContinuityKeys.add(pk); + } + } + + return { outcomeByListingKey }; +} + +function collectAndDeduplicateConflicts(input: PersistSecurityMasterInput): { + uniqueConflicts: PreparedConflict[]; + deduplicatedCount: number; +} { + const raw: PreparedConflict[] = []; + + for (const c of input.stageA.conflicts) { + raw.push({ + key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}`, + source: c.source, + sourceId: c.sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + }); + } + + for (const c of input.stageB.conflicts) { + raw.push({ + key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}`, + source: c.source, + sourceId: c.sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + }); + } + + if (input.pass6 !== undefined) { + for (const c of input.pass6.conflicts) { + const sourceId = c.detail.primaryIsin; + raw.push({ + key: `pass6\u0000${sourceId}\u0000${c.conflictKind}`, + source: 'pass6', + sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + }); + } + } + + if (raw.length === 0) { + return { uniqueConflicts: [], deduplicatedCount: 0 }; + } + + raw.sort( + (a, b) => + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.conflictKind, b.conflictKind) || + compareAscii(a.detailJson, b.detailJson) + ); + + const uniqueConflicts: PreparedConflict[] = []; + const seen = new Set(); + let deduplicatedCount = 0; + + for (const item of raw) { + if (seen.has(item.key)) { + deduplicatedCount += 1; + continue; + } + seen.add(item.key); + uniqueConflicts.push(item); + } + + return { uniqueConflicts, deduplicatedCount }; +} + +async function persistWithinTransaction( + client: SecurityMasterQueryable, + input: PersistSecurityMasterInput, + chunkSize: number, + outcomeByListingKey: ReadonlyMap +): Promise { + let instrumentsInserted = 0; + let instrumentsUpdated = 0; + let instrumentsUnchanged = 0; + let skippedMissingCanonicalName = 0; + let skippedMissingSecurityType = 0; + + let identifierHistoryInserted = 0; + let identifierHistoryUnchanged = 0; + + let listingsInserted = 0; + let listingsUpdated = 0; + let listingsUnchanged = 0; + let skippedListingInstrument = 0; + let skippedListingMissingInstrument = 0; + let skippedListingUnknownMic = 0; + + let listingSymbolHistoryInserted = 0; + let listingSymbolHistoryUpdated = 0; + let listingSymbolHistoryUnchanged = 0; + + let providerMappingsInserted = 0; + let providerMappingsUpdated = 0; + let providerMappingsUnchanged = 0; + let skippedMappingMissingListing = 0; + + let conflictsInserted = 0; + let conflictsUnchanged = 0; + + let pass6OutcomesApplied = 0; + let pass6OutcomesSkippedMissingListing = 0; + + let continuitiesInserted = 0; + let continuitiesUpdated = 0; + let continuitiesUnchanged = 0; + let skippedContinuityMissingFrom = 0; + let skippedContinuityMissingTo = 0; + let skippedContinuityMissingBoth = 0; + + const instrumentIdByIsin = new Map(); + const listingIdByKey = new Map(); + const skippedInstrumentIsins = new Set(); + + // --------------------------------------------------------------------------- + // 1. Instruments + instrument_identifier_history + // --------------------------------------------------------------------------- + const preparedInstruments: PreparedInstrument[] = []; + for (const candidate of input.stageA.instruments) { + const trimmedName = + typeof candidate.canonicalName === 'string' ? candidate.canonicalName.trim() : ''; + if (trimmedName.length === 0) { + skippedMissingCanonicalName += 1; + skippedInstrumentIsins.add(candidate.primaryIsin); + continue; + } + const securityType = input.securityTypeByIsin.get(candidate.primaryIsin); + if (securityType === undefined) { + skippedMissingSecurityType += 1; + skippedInstrumentIsins.add(candidate.primaryIsin); + continue; + } + preparedInstruments.push({ + primaryIsin: candidate.primaryIsin, + primaryCusip: candidate.primaryCusip, + canonicalName: trimmedName, + securityType, + issuerCountry: candidate.issuerCountry, + bestSource: selectBestMemberSource(candidate.members), + }); + } + + if (preparedInstruments.length > 0) { + const existingByIsin = new Map(); + for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) { + const slice = preparedInstruments.slice(offset, offset + chunkSize); + const isins = slice.map(item => item.primaryIsin); + const res = await client.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 + WHERE primary_isin = ANY($1::bpchar[])`, + [isins] + ); + for (const row of res.rows) { + existingByIsin.set(row.primary_isin, row); + } + } + + const toInsert: PreparedInstrument[] = []; + const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = []; + + for (const item of preparedInstruments) { + const existing = existingByIsin.get(item.primaryIsin); + if (existing === undefined) { + toInsert.push(item); + continue; + } + instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id); + const changed = + existing.primary_cusip !== item.primaryCusip || + existing.canonical_name !== item.canonicalName || + existing.security_type !== item.securityType || + existing.issuer_country !== item.issuerCountry; + if (changed) { + toUpdate.push({ instrumentId: existing.instrument_id, item }); + } else { + instrumentsUnchanged += 1; + } + } + + for (let offset = 0; offset < toInsert.length; offset += chunkSize) { + const slice = toInsert.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO instrument ( + primary_isin, + primary_cusip, + canonical_name, + security_type, + issuer_country + ) + SELECT * + FROM UNNEST( + $1::bpchar[], + $2::bpchar[], + $3::text[], + $4::varchar[], + $5::bpchar[] + ) + RETURNING instrument_id, btrim(primary_isin) AS primary_isin`, + [ + slice.map(item => item.primaryIsin), + slice.map(item => item.primaryCusip), + slice.map(item => item.canonicalName), + slice.map(item => item.securityType), + slice.map(item => item.issuerCountry), + ] + ); + for (const row of res.rows) { + instrumentIdByIsin.set(row.primary_isin, row.instrument_id); + } + instrumentsInserted += res.rows.length; + } + + for (let offset = 0; offset < toUpdate.length; offset += chunkSize) { + const slice = toUpdate.slice(offset, offset + chunkSize); + await client.query( + `UPDATE instrument AS i + SET + primary_cusip = u.primary_cusip, + canonical_name = u.canonical_name, + security_type = u.security_type, + issuer_country = u.issuer_country + FROM UNNEST( + $1::int4[], + $2::bpchar[], + $3::text[], + $4::varchar[], + $5::bpchar[] + ) AS u(instrument_id, primary_cusip, canonical_name, security_type, issuer_country) + WHERE i.instrument_id = u.instrument_id`, + [ + slice.map(entry => entry.instrumentId), + slice.map(entry => entry.item.primaryCusip), + slice.map(entry => entry.item.canonicalName), + slice.map(entry => entry.item.securityType), + slice.map(entry => entry.item.issuerCountry), + ] + ); + instrumentsUpdated += slice.length; + } + + // Populate instrument_identifier_history for all persisted instruments + const idHistoryRows: Array<{ + instrumentId: number; + idType: 'ISIN' | 'CUSIP'; + idValue: string; + validFrom: string; + source: StageASource; + }> = []; + for (const item of preparedInstruments) { + const instrumentId = instrumentIdByIsin.get(item.primaryIsin); + if (instrumentId === undefined) { + continue; + } + idHistoryRows.push({ + instrumentId, + idType: 'ISIN', + idValue: item.primaryIsin, + validFrom: DEFAULT_VALID_FROM, + source: item.bestSource, + }); + if (item.primaryCusip !== null) { + idHistoryRows.push({ + instrumentId, + idType: 'CUSIP', + idValue: item.primaryCusip, + validFrom: DEFAULT_VALID_FROM, + source: item.bestSource, + }); + } + } + + for (let offset = 0; offset < idHistoryRows.length; offset += chunkSize) { + const slice = idHistoryRows.slice(offset, offset + chunkSize); + const res = await client.query<{ inserted: number }>( + `INSERT INTO instrument_identifier_history ( + instrument_id, + id_type, + id_value, + valid_from, + source + ) + SELECT * + FROM UNNEST( + $1::int4[], + $2::varchar[], + $3::varchar[], + $4::date[], + $5::varchar[] + ) + ON CONFLICT (id_type, id_value, valid_from) DO NOTHING + RETURNING 1 AS inserted`, + [ + slice.map(row => row.instrumentId), + slice.map(row => row.idType), + slice.map(row => row.idValue), + slice.map(row => row.validFrom), + slice.map(row => row.source), + ] + ); + identifierHistoryInserted += res.rows.length; + identifierHistoryUnchanged += slice.length - res.rows.length; + } + } + + // --------------------------------------------------------------------------- + // 2. Listings + Pass 6 outcome folding + listing_symbol_history + // --------------------------------------------------------------------------- + if (input.stageB.listings.length > 0) { + const exchangeRes = await client.query<{ mic: string }>('SELECT mic FROM exchange'); + const knownMics = new Set(exchangeRes.rows.map(row => row.mic)); + + const preparedListings: PreparedListing[] = []; + const uniqueInstrumentIds = new Set(); + + for (const listing of input.stageB.listings) { + const instrumentId = instrumentIdByIsin.get(listing.primaryIsin); + if (instrumentId === undefined) { + if (skippedInstrumentIsins.has(listing.primaryIsin)) { + skippedListingInstrument += 1; + } else { + skippedListingMissingInstrument += 1; + } + continue; + } + if (!knownMics.has(listing.mic)) { + skippedListingUnknownMic += 1; + continue; + } + + const naturalKey = formatListingNaturalKey(listing); + const dbNaturalKey = formatDbListingNaturalKey( + instrumentId, + listing.mic, + listing.tickerRoot, + listing.classSuffix, + listing.currency + ); + preparedListings.push({ + naturalKey, + dbNaturalKey, + instrumentId, + mic: listing.mic, + tickerRoot: listing.tickerRoot, + classSuffix: listing.classSuffix, + currency: listing.currency, + ibConid: listing.ibConid, + ibPrimaryExchange: listing.ibPrimaryExchange, + listedFrom: listing.listedFrom, + listedTo: listing.listedTo, + outcome: outcomeByListingKey.get(naturalKey), + }); + uniqueInstrumentIds.add(instrumentId); + } + + if (preparedListings.length > 0) { + const existingByDbKey = new Map(); + const duplicateDbKeys = new Set(); + const instrumentIdList = Array.from(uniqueInstrumentIds); + + for (let offset = 0; offset < instrumentIdList.length; offset += chunkSize) { + const slice = instrumentIdList.slice(offset, offset + chunkSize); + const res = await client.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 + WHERE instrument_id = ANY($1::int4[])`, + [slice] + ); + for (const row of res.rows) { + const dbKey = formatDbListingNaturalKey( + row.instrument_id, + row.mic, + row.ticker_root, + row.class_suffix, + row.currency + ); + if (existingByDbKey.has(dbKey)) { + duplicateDbKeys.add(dbKey); + } else { + existingByDbKey.set(dbKey, row); + } + } + } + + const toInsert: PreparedListing[] = []; + const toUpdate: ListingUpdatePayload[] = []; + const naturalKeyByDbKey = new Map(); + + for (const item of preparedListings) { + naturalKeyByDbKey.set(item.dbNaturalKey, item.naturalKey); + if (duplicateDbKeys.has(item.dbNaturalKey)) { + throw new Error( + `Existing listing table contains duplicate rows for natural key (instrument_id=${item.instrumentId}, mic=${item.mic}, ticker_root=${item.tickerRoot}, class_suffix=${item.classSuffix}, currency=${item.currency})` + ); + } + + const existing = existingByDbKey.get(item.dbNaturalKey); + if (existing === undefined) { + toInsert.push(item); + continue; + } + + listingIdByKey.set(item.naturalKey, existing.listing_id); + + const existingIbConid = normalizeNullableBigInt(existing.ib_conid); + const existingTerminalReturn = normalizeNullableNumeric6(existing.terminal_return); + const targetDelistReason = + item.outcome !== undefined ? item.outcome.delistReason : existing.delist_reason; + const targetTerminalReturn = + item.outcome !== undefined + ? normalizeNullableNumeric6(item.outcome.terminalReturn) + : existingTerminalReturn; + + const changed = + existingIbConid !== item.ibConid || + existing.ib_primary_exchange !== item.ibPrimaryExchange || + existing.listed_from !== item.listedFrom || + existing.listed_to !== item.listedTo || + existing.delist_reason !== targetDelistReason || + existingTerminalReturn !== targetTerminalReturn; + + if (changed) { + toUpdate.push({ + listingId: existing.listing_id, + ibConid: item.ibConid, + ibPrimaryExchange: item.ibPrimaryExchange, + listedFrom: item.listedFrom, + listedTo: item.listedTo, + delistReason: targetDelistReason, + terminalReturn: targetTerminalReturn, + }); + } else { + listingsUnchanged += 1; + } + } + + for (let offset = 0; offset < toInsert.length; offset += chunkSize) { + const slice = toInsert.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO listing ( + instrument_id, + mic, + ticker_root, + class_suffix, + currency, + ib_conid, + ib_primary_exchange, + listed_from, + listed_to, + delist_reason, + terminal_return + ) + SELECT * + FROM UNNEST( + $1::int4[], + $2::varchar[], + $3::varchar[], + $4::varchar[], + $5::bpchar[], + $6::int8[], + $7::varchar[], + $8::date[], + $9::date[], + $10::varchar[], + $11::numeric[] + ) + RETURNING + listing_id, + instrument_id, + mic, + ticker_root, + class_suffix, + btrim(currency) AS currency`, + [ + slice.map(item => item.instrumentId), + slice.map(item => item.mic), + slice.map(item => item.tickerRoot), + slice.map(item => item.classSuffix), + slice.map(item => item.currency), + slice.map(item => item.ibConid), + slice.map(item => item.ibPrimaryExchange), + slice.map(item => item.listedFrom), + slice.map(item => item.listedTo), + slice.map(item => (item.outcome !== undefined ? item.outcome.delistReason : null)), + slice.map(item => + item.outcome !== undefined ? normalizeNullableNumeric6(item.outcome.terminalReturn) : null + ), + ] + ); + for (const row of res.rows) { + const dbKey = formatDbListingNaturalKey( + row.instrument_id, + row.mic, + row.ticker_root, + row.class_suffix, + row.currency + ); + const naturalKey = naturalKeyByDbKey.get(dbKey); + if (naturalKey !== undefined) { + listingIdByKey.set(naturalKey, row.listing_id); + } + } + listingsInserted += res.rows.length; + } + + for (let offset = 0; offset < toUpdate.length; offset += chunkSize) { + const slice = toUpdate.slice(offset, offset + chunkSize); + await client.query( + `UPDATE listing AS l + SET + ib_conid = u.ib_conid, + ib_primary_exchange = u.ib_primary_exchange, + listed_from = u.listed_from, + listed_to = u.listed_to, + delist_reason = u.delist_reason, + terminal_return = u.terminal_return + FROM UNNEST( + $1::int4[], + $2::int8[], + $3::varchar[], + $4::date[], + $5::date[], + $6::varchar[], + $7::numeric[] + ) AS u(listing_id, ib_conid, ib_primary_exchange, listed_from, listed_to, delist_reason, terminal_return) + WHERE l.listing_id = u.listing_id`, + [ + slice.map(entry => entry.listingId), + slice.map(entry => entry.ibConid), + slice.map(entry => entry.ibPrimaryExchange), + slice.map(entry => entry.listedFrom), + slice.map(entry => entry.listedTo), + slice.map(entry => entry.delistReason), + slice.map(entry => entry.terminalReturn), + ] + ); + listingsUpdated += slice.length; + } + + // listing_symbol_history for all persisted listings + const symbolHistoryRows: PreparedSymbolHistoryRow[] = []; + for (const item of preparedListings) { + const listingId = listingIdByKey.get(item.naturalKey); + if (listingId === undefined) { + continue; + } + const ticker = + item.classSuffix.length > 0 ? `${item.tickerRoot}.${item.classSuffix}` : item.tickerRoot; + symbolHistoryRows.push({ + listingId, + ticker, + validFrom: item.listedFrom ?? DEFAULT_VALID_FROM, + validTo: item.listedTo, + source: 'eod', + }); + } + + 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 + ) + 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`, + [ + 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), + ] + ); + let chunkInserted = 0; + let chunkUpdated = 0; + for (const row of res.rows) { + if (row.inserted) { + chunkInserted += 1; + } else { + chunkUpdated += 1; + } + } + listingSymbolHistoryInserted += chunkInserted; + listingSymbolHistoryUpdated += chunkUpdated; + listingSymbolHistoryUnchanged += slice.length - chunkInserted - chunkUpdated; + } + } + } + + // Reconcile Pass 6 listing outcome counts + if (input.pass6 !== undefined) { + for (const outcome of input.pass6.listingOutcomes) { + const key = formatListingNaturalKey(outcome.listingKey); + if (listingIdByKey.has(key)) { + pass6OutcomesApplied += 1; + } else { + pass6OutcomesSkippedMissingListing += 1; + } + } + } + + // --------------------------------------------------------------------------- + // 3. provider_mapping upsert + override precedence + // --------------------------------------------------------------------------- + const preparedMappings: PreparedProviderMapping[] = []; + for (const candidate of input.stageB.providerMappings) { + const listingId = listingIdByKey.get(formatListingNaturalKey(candidate.listingKey)); + if (listingId === undefined) { + skippedMappingMissingListing += 1; + continue; + } + preparedMappings.push({ + source: candidate.source, + sourceId: candidate.sourceId, + validFrom: candidate.validFrom ?? DEFAULT_VALID_FROM, + validTo: candidate.validTo, + listingId, + method: candidate.method, + confidence: PROVIDER_MAPPING_CONFIDENCE[candidate.method].toFixed(3), + }); + } + + for (let offset = 0; offset < preparedMappings.length; offset += chunkSize) { + const slice = preparedMappings.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO provider_mapping ( + source, + source_id, + valid_from, + valid_to, + listing_id, + method, + confidence, + price_corr + ) + SELECT + u.source, + u.source_id, + u.valid_from, + u.valid_to, + u.listing_id, + u.method, + u.confidence, + NULL::numeric(5, 4) + FROM UNNEST( + $1::varchar[], + $2::varchar[], + $3::date[], + $4::date[], + $5::int4[], + $6::varchar[], + $7::numeric[] + ) AS u(source, source_id, valid_from, valid_to, listing_id, method, confidence) + ON CONFLICT (source, source_id, valid_from) DO UPDATE SET + valid_to = EXCLUDED.valid_to, + listing_id = EXCLUDED.listing_id, + method = EXCLUDED.method, + confidence = EXCLUDED.confidence, + price_corr = CASE + WHEN provider_mapping.listing_id = EXCLUDED.listing_id THEN provider_mapping.price_corr + ELSE NULL + END + WHERE NOT EXISTS ( + SELECT 1 + FROM override o + WHERE o.source = provider_mapping.source + AND o.source_id = provider_mapping.source_id + AND o.valid_from = provider_mapping.valid_from + ) + AND ( + provider_mapping.valid_to IS DISTINCT FROM EXCLUDED.valid_to + OR provider_mapping.listing_id IS DISTINCT FROM EXCLUDED.listing_id + OR provider_mapping.method IS DISTINCT FROM EXCLUDED.method + OR provider_mapping.confidence IS DISTINCT FROM EXCLUDED.confidence + ) + RETURNING (xmax = 0) AS inserted`, + [ + slice.map(row => row.source), + slice.map(row => row.sourceId), + slice.map(row => row.validFrom), + slice.map(row => row.validTo), + slice.map(row => row.listingId), + slice.map(row => row.method), + 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; + } + } + providerMappingsInserted += chunkInserted; + providerMappingsUpdated += chunkUpdated; + providerMappingsUnchanged += slice.length - chunkInserted - chunkUpdated; + } + + // Enforce override precedence unconditionally across all rows in `override`. + const overrideRes = await client.query( + `WITH enforced AS ( + INSERT INTO provider_mapping ( + source, + source_id, + valid_from, + valid_to, + listing_id, + method, + confidence, + price_corr + ) + SELECT + o.source, + o.source_id, + o.valid_from, + o.valid_to, + o.listing_id, + 'override', + 1.000, + NULL::numeric(5, 4) + FROM override o + ON CONFLICT (source, source_id, valid_from) DO UPDATE SET + listing_id = EXCLUDED.listing_id, + valid_to = EXCLUDED.valid_to, + method = 'override', + confidence = 1.000, + price_corr = NULL + WHERE provider_mapping.listing_id IS DISTINCT FROM EXCLUDED.listing_id + OR provider_mapping.valid_to IS DISTINCT FROM EXCLUDED.valid_to + 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 + ) + 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` + ); + const overrideStats = overrideRes.rows[0]; + const overridesApplied = Number(overrideStats?.total_overrides ?? 0); + providerMappingsInserted += Number(overrideStats?.inserted_overrides ?? 0); + + // --------------------------------------------------------------------------- + // 4. Pass 5 resolution_conflict (all statuses preserved; no duplicate open rows) + // --------------------------------------------------------------------------- + const { uniqueConflicts, deduplicatedCount: conflictsDeduplicated } = + collectAndDeduplicateConflicts(input); + + if (uniqueConflicts.length > 0) { + const existingConflictKeys = new Set(); + for (let offset = 0; offset < uniqueConflicts.length; offset += chunkSize) { + const slice = uniqueConflicts.slice(offset, offset + chunkSize); + const res = await client.query( + `SELECT DISTINCT + rc.source, + rc.source_id, + rc.conflict_kind + FROM resolution_conflict rc + INNER JOIN UNNEST( + $1::varchar[], + $2::varchar[], + $3::varchar[] + ) AS u(source, source_id, conflict_kind) + ON rc.source = u.source + AND rc.source_id = u.source_id + AND rc.conflict_kind = u.conflict_kind`, + [ + slice.map(c => c.source), + slice.map(c => c.sourceId), + slice.map(c => c.conflictKind), + ] + ); + for (const row of res.rows) { + existingConflictKeys.add(`${row.source}\u0000${row.source_id}\u0000${row.conflict_kind}`); + } + } + + const toInsertConflicts: PreparedConflict[] = []; + for (const conflict of uniqueConflicts) { + if (existingConflictKeys.has(conflict.key)) { + conflictsUnchanged += 1; + } else { + toInsertConflicts.push(conflict); + } + } + + for (let offset = 0; offset < toInsertConflicts.length; offset += chunkSize) { + const slice = toInsertConflicts.slice(offset, offset + chunkSize); + await client.query( + `INSERT INTO resolution_conflict ( + source, + source_id, + conflict_kind, + detail, + status + ) + SELECT + u.source, + u.source_id, + u.conflict_kind, + u.detail, + 'open' + FROM UNNEST( + $1::varchar[], + $2::varchar[], + $3::varchar[], + $4::jsonb[] + ) AS u(source, source_id, conflict_kind, detail)`, + [ + slice.map(c => c.source), + slice.map(c => c.sourceId), + slice.map(c => c.conflictKind), + slice.map(c => c.detailJson), + ] + ); + conflictsInserted += slice.length; + } + } + + // --------------------------------------------------------------------------- + // 5. Pass 6 corporate_action_continuity + // --------------------------------------------------------------------------- + if (input.pass6 !== undefined && input.pass6.continuities.length > 0) { + const preparedContinuities: PreparedContinuity[] = []; + for (const continuity of input.pass6.continuities) { + const fromListingId = listingIdByKey.get(formatListingNaturalKey(continuity.fromListingKey)); + const toListingId = listingIdByKey.get(formatListingNaturalKey(continuity.toListingKey)); + if (fromListingId === undefined && toListingId === undefined) { + skippedContinuityMissingBoth += 1; + continue; + } + if (fromListingId === undefined) { + skippedContinuityMissingFrom += 1; + continue; + } + if (toListingId === undefined) { + skippedContinuityMissingTo += 1; + continue; + } + preparedContinuities.push({ + fromListingId, + toListingId, + effectiveDate: continuity.effectiveDate, + kind: continuity.kind, + }); + } + + for (let offset = 0; offset < preparedContinuities.length; offset += chunkSize) { + const slice = preparedContinuities.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO corporate_action_continuity ( + from_listing_id, + to_listing_id, + effective_date, + kind + ) + SELECT * + FROM UNNEST( + $1::int4[], + $2::int4[], + $3::date[], + $4::varchar[] + ) + ON CONFLICT (from_listing_id, effective_date) DO UPDATE SET + to_listing_id = EXCLUDED.to_listing_id, + kind = EXCLUDED.kind + WHERE corporate_action_continuity.to_listing_id IS DISTINCT FROM EXCLUDED.to_listing_id + OR corporate_action_continuity.kind IS DISTINCT FROM EXCLUDED.kind + RETURNING (xmax = 0) AS inserted`, + [ + slice.map(row => row.fromListingId), + slice.map(row => row.toListingId), + slice.map(row => row.effectiveDate), + slice.map(row => row.kind), + ] + ); + let chunkInserted = 0; + let chunkUpdated = 0; + for (const row of res.rows) { + if (row.inserted) { + chunkInserted += 1; + } else { + chunkUpdated += 1; + } + } + continuitiesInserted += chunkInserted; + continuitiesUpdated += chunkUpdated; + continuitiesUnchanged += slice.length - chunkInserted - chunkUpdated; + } + } + + return { + instrumentsInserted, + instrumentsUpdated, + instrumentsUnchanged, + instrumentsSkipped: skippedMissingCanonicalName + skippedMissingSecurityType, + + identifierHistoryInserted, + identifierHistoryUnchanged, + + listingsInserted, + listingsUpdated, + listingsUnchanged, + listingsSkipped: + skippedListingInstrument + skippedListingMissingInstrument + skippedListingUnknownMic, + + listingSymbolHistoryInserted, + listingSymbolHistoryUpdated, + listingSymbolHistoryUnchanged, + + providerMappingsInserted, + providerMappingsUpdated, + providerMappingsUnchanged, + providerMappingsSkipped: skippedMappingMissingListing, + + overridesApplied, + + conflictsInserted, + conflictsUnchanged, + conflictsDeduplicated, + + pass6OutcomesApplied, + pass6OutcomesSkipped: pass6OutcomesSkippedMissingListing, + + continuitiesInserted, + continuitiesUpdated, + continuitiesUnchanged, + continuitiesSkipped: + skippedContinuityMissingFrom + skippedContinuityMissingTo + skippedContinuityMissingBoth, + + skippedByReason: { + instruments: { + missing_canonical_name: skippedMissingCanonicalName, + missing_security_type: skippedMissingSecurityType, + }, + listings: { + skipped_instrument: skippedListingInstrument, + missing_instrument: skippedListingMissingInstrument, + unknown_mic: skippedListingUnknownMic, + }, + providerMappings: { + missing_listing: skippedMappingMissingListing, + }, + pass6Outcomes: { + missing_listing: pass6OutcomesSkippedMissingListing, + }, + continuities: { + missing_from_listing: skippedContinuityMissingFrom, + missing_to_listing: skippedContinuityMissingTo, + missing_both_listings: skippedContinuityMissingBoth, + }, + }, + instrumentIdByIsin, + listingIdByKey, + }; +} + +/** + * Idempotently persists Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 + * (`delisting-chains`) in-memory results into the PostgreSQL security master tables inside a + * single transaction guarded by a schema-scoped `pg_advisory_xact_lock`. + * + * Guarantees: + * - Permanent `instrument_id` and `listing_id` values across re-runs and incremental additions. + * - Unconditional `override` precedence (`method = 'override'`, `confidence = 1.000`). + * - No guessing: instruments missing `canonicalName` or `securityTypeByIsin` and listings with + * unknown MICs are skipped and counted along with all dependent rows. + * - Batched `UNNEST` writes (default/max chunk size `5000`) using parameterised SQL only. + * + * Benchmark: run `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` + * against an isolated `stock_bot_safety_*` schema to execute the fixed-seed 20,000-instrument / + * 20,000-listing / 60,000-mapping throughput benchmark. + */ +export async function persistSecurityMaster( + client: SecurityMasterQueryable, + input: PersistSecurityMasterInput, + options: PersistSecurityMasterOptions = {} +): Promise { + assertDedicatedQueryable(client); + 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] + ); + 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; + } +} + +// Re-export type aliases used by callers without forcing extra imports. +export type { StageAInstrumentCandidate, StageBListingCandidate, StageBProviderMappingCandidate }; diff --git a/test/postgres/security-master-persist.test.ts b/test/postgres/security-master-persist.test.ts new file mode 100644 index 00000000..7c0f3262 --- /dev/null +++ b/test/postgres/security-master-persist.test.ts @@ -0,0 +1,1078 @@ +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)[] = []; +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(pool: Pool, fn: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + return await fn(client); + } finally { + client.release(); + } +} + +async function getSevenTableCounts(pool: Pool): Promise> { + const tables = [ + 'instrument', + 'instrument_identifier_history', + 'listing', + 'listing_symbol_history', + 'provider_mapping', + 'resolution_conflict', + 'corporate_action_continuity', + ] as const; + const counts: Record = {}; + 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([ + ['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; +} { + const instruments: StageAMatchResult['instruments'] = []; + const listings: StageBMatchResult['listings'] = []; + const providerMappings: StageBMatchResult['providerMappings'] = []; + const securityTypeByIsin = new Map(); + + 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, 1900-01-01) -> 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 '1900-01-01', DATE '2025-12-31', $1, 'conflict resolution', 'director'), + ('qm', 'MANUAL_OVR:US', DATE '2021-01-01', NULL, $2, 'manual addition', 'director')`, + [shopNyseId, aaplId] + ); + + const runWithOverrides = await withClient(f.pool, client => + persistSecurityMaster(client, fixture) + ); + expect(runWithOverrides.overridesApplied).toBe(2); + expect(runWithOverrides.providerMappingsInserted).toBe(1); // the override-only mapping + + const rowsAfterOverride = ( + await f.pool.query<{ + source: string; + source_id: string; + valid_from: string; + valid_to: string | null; + listing_id: number; + method: string; + confidence: string; + price_corr: string | null; + }>( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, method, confidence::text, price_corr::text + FROM provider_mapping + WHERE (source = 'eod' AND source_id = 'AAPL.US') + OR (source = 'qm' AND source_id = 'MANUAL_OVR:US') + ORDER BY source, source_id` + ) + ).rows; + expect(rowsAfterOverride).toEqual([ + { + source: 'eod', + source_id: 'AAPL.US', + valid_from: DEFAULT_VALID_FROM, + valid_to: '2025-12-31', + listing_id: shopNyseId, + method: 'override', + confidence: '1.000', + price_corr: null, + }, + { + source: 'qm', + source_id: 'MANUAL_OVR:US', + valid_from: '2021-01-01', + valid_to: null, + listing_id: aaplId, + method: 'override', + confidence: '1.000', + price_corr: null, + }, + ]); + + // Re-running with conflicting matcher output keeps override intact with 0 overwrites. + const secondRun = await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + expect(secondRun.overridesApplied).toBe(2); + expect(secondRun.providerMappingsInserted).toBe(0); + expect(secondRun.providerMappingsUpdated).toBe(0); + }); + + test('persists Stage A, Stage B, and Pass 6 conflicts once and never reopens or modifies non-open rows', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + const pass6WithConflict: DelistingChainResult = { + ...fixture.pass6, + conflicts: [ + { + conflictKind: 'ambiguous_otc_continuation', + detail: { + primaryIsin: 'US78486Q1013', + currency: 'USD', + fromListingKeys: [], + toListingKeys: [], + candidateListingKeys: [], + listedFrom: null, + listedTo: '2023-03-10', + reason: 'two OTC candidates', + }, + }, + ], + }; + + const run1 = await withClient(f.pool, client => + persistSecurityMaster(client, { ...fixture, pass6: pass6WithConflict }) + ); + expect(run1.conflictsInserted).toBe(3); + + // Manually resolve the Pass 6 conflict row. + await f.pool.query( + `UPDATE resolution_conflict + SET status = 'resolved', resolved_at = TIMESTAMPTZ '2026-11-27T12:00:00Z' + WHERE source = 'pass6' AND source_id = 'US78486Q1013' AND conflict_kind = 'ambiguous_otc_continuation'` + ); + + const run2 = await withClient(f.pool, client => + persistSecurityMaster(client, { ...fixture, pass6: pass6WithConflict }) + ); + expect(run2.conflictsInserted).toBe(0); + expect(run2.conflictsUnchanged).toBe(3); + + const conflictRows = ( + await f.pool.query<{ + source: string; + source_id: string; + conflict_kind: string; + status: string; + resolved_at: Date | null; + }>( + `SELECT source, source_id, conflict_kind, status, resolved_at + FROM resolution_conflict + ORDER BY source, source_id, conflict_kind` + ) + ).rows; + expect(conflictRows).toHaveLength(3); + const pass6Row = conflictRows.find(r => r.source === 'pass6'); + expect(pass6Row?.status).toBe('resolved'); + expect(pass6Row?.resolved_at).not.toBeNull(); + }); + + test('skips and counts instruments/listings/mappings/continuities without guessing on missing metadata or unknown MIC', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'VALID.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'NONAME.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: null, + }, + { + source: 'eod', + sourceId: 'NOTYPE.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'No Security Type Corp', + }, + ]); + + const validKey = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const unknownMicKey = { + primaryIsin: 'US0378331005', + mic: 'XXXX', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const noNameKey = { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }; + const noTypeKey = { + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }; + + const stageB: StageBMatchResult = { + listings: [ + { ...validKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + { ...unknownMicKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + { ...noNameKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + { ...noTypeKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + ], + providerMappings: [ + { source: 'eod', sourceId: 'AAPL.US', listingKey: validKey, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'AAPL.XX', listingKey: unknownMicKey, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'FB.US', listingKey: noNameKey, method: 'tier1_isin', validFrom: null, validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: { + totalListings: 4, + totalProviderMappings: 3, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 3, matched: 3, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; + + const pass6: DelistingChainResult = { + continuities: [ + { + fromListingKey: noTypeKey, + toListingKey: validKey, + effectiveDate: '2023-03-28', + kind: 'otc_delist_transfer', + }, + ], + listingOutcomes: [ + { listingKey: validKey, delistReason: 'active', terminalReturn: null }, + { listingKey: unknownMicKey, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, + ], + conflicts: [], + stats: { + totalInputListings: 2, + processedListings: 2, + skippedMalformedEntries: 0, + skippedInvalidDates: 0, + skippedDuplicateKeys: 0, + continuitiesCreated: 1, + conflictsDetected: 0, + byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 1 }, + }, + }; + + const result = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB, + pass6, + securityTypeByIsin: new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ]), + }) + ); + + expect(result.instrumentsInserted).toBe(1); + expect(result.instrumentsSkipped).toBe(2); + expect(result.skippedByReason.instruments).toEqual({ + missing_canonical_name: 1, + missing_security_type: 1, + }); + expect(result.listingsInserted).toBe(1); + expect(result.listingsSkipped).toBe(3); + expect(result.skippedByReason.listings).toEqual({ + skipped_instrument: 2, + missing_instrument: 0, + unknown_mic: 1, + }); + expect(result.providerMappingsInserted).toBe(1); + expect(result.providerMappingsSkipped).toBe(2); + expect(result.pass6OutcomesApplied).toBe(1); + expect(result.pass6OutcomesSkipped).toBe(1); + expect(result.continuitiesInserted).toBe(0); + expect(result.continuitiesSkipped).toBe(1); + expect(result.skippedByReason.continuities.missing_from_listing).toBe(1); + }); + + test('rolls back all 7 tables atomically on a mid-run CHECK constraint violation', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + const preCounts = await getSevenTableCounts(f.pool); + const badTypes = new Map(fixture.securityTypeByIsin); + // Chunk size 2 -> chunk 1 inserts 2 valid instruments, chunk 2 hits Postgres CHECK violation + badTypes.set('US78486Q1013', 'bogus_type' as SecurityType); + + await expect( + withClient(f.pool, client => + persistSecurityMaster(client, { ...fixture, securityTypeByIsin: badTypes }, { chunkSize: 2 }) + ) + ).rejects.toThrow(/security_type/); + + const postCounts = await getSevenTableCounts(f.pool); + expect(postCounts).toEqual(preCounts); + }); + + test('serializes two concurrent writers via pg_advisory_xact_lock without duplicate listings', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + const [c1, c2] = await Promise.all([f.pool.connect(), f.pool.connect()]); + try { + const [r1, r2] = await Promise.all([ + persistSecurityMaster(c1, fixture), + persistSecurityMaster(c2, fixture), + ]); + + expect(Object.fromEntries(r1.listingIdByKey)).toEqual(Object.fromEntries(r2.listingIdByKey)); + expect(r1.listingsInserted + r2.listingsInserted).toBe(7); + + const counts = await getSevenTableCounts(f.pool); + expect(counts.instrument).toBe(5); + expect(counts.listing).toBe(7); + expect(counts.provider_mapping).toBe(10); + } finally { + c1.release(); + c2.release(); + } + }); + + test('batches SQL statements in O(ceil(N / chunkSize)) round trips on a real PoolClient', async () => { + const f = await createIsolatedFixture(); + const input = buildSyntheticBenchmarkInput(600); + + let queryCount = 0; + const result = await withClient(f.pool, async client => { + const countingClient: SecurityMasterQueryable = { + release: () => undefined, + query: (text, values) => { + queryCount += 1; + return client.query(text, values as unknown[]); + }, + }; + return persistSecurityMaster(countingClient, input, { chunkSize: 200 }); + }); + + expect(result.instrumentsInserted).toBe(600); + expect(result.listingsInserted).toBe(600); + expect(result.providerMappingsInserted).toBe(1800); + expect(queryCount).toBeLessThan(40); + }); + + test( + 'fixed-seed throughput benchmark: persists 20,000 instruments, 20,000 listings, and 60,000 mappings', + async () => { + const f = await createIsolatedFixture(120_000); + const instrumentCount = 20_000; + const input = buildSyntheticBenchmarkInput(instrumentCount); + + const t0 = performance.now(); + const result = await withClient(f.pool, client => persistSecurityMaster(client, input)); + const elapsedSec = (performance.now() - t0) / 1000; + + const totalCoreRows = + result.instrumentsInserted + result.listingsInserted + result.providerMappingsInserted; + const totalAllRows = + totalCoreRows + result.identifierHistoryInserted + result.listingSymbolHistoryInserted; + + expect(result.instrumentsInserted).toBe(instrumentCount); + expect(result.listingsInserted).toBe(instrumentCount); + expect(result.providerMappingsInserted).toBe(instrumentCount * 3); + + const counts = await getSevenTableCounts(f.pool); + expect(counts.instrument).toBe(instrumentCount); + expect(counts.listing).toBe(instrumentCount); + expect(counts.provider_mapping).toBe(instrumentCount * 3); + + console.info( + `[security-master-persist benchmark] ${instrumentCount} instruments, ${instrumentCount} listings, ${instrumentCount * 3} mappings (${totalAllRows} total rows) persisted in ${elapsedSec.toFixed(2)}s (${Math.round(totalCoreRows / elapsedSec)} core rows/s, ${Math.round(totalAllRows / elapsedSec)} total rows/s)` + ); + }, + 120_000 + ); +}); diff --git a/test/unit/security-master-persist.test.ts b/test/unit/security-master-persist.test.ts new file mode 100644 index 00000000..79c60815 --- /dev/null +++ b/test/unit/security-master-persist.test.ts @@ -0,0 +1,634 @@ +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 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 +): { client: SecurityMasterQueryable; queries: RecordedQuery[] } { + const queries: RecordedQuery[] = []; + let nextInstrumentId = 100; + let nextListingId = 1000; + + const client: SecurityMasterQueryable = { + release: () => undefined, + async query>( + text: string, + values?: readonly unknown[] + ): Promise> { + const index = queries.length; + queries.push({ text, values }); + if (handler) { + return (await handler(text, values, index)) as SecurityMasterQueryResult; + } + + if (text.startsWith('SELECT mic FROM exchange')) { + return { + rows: [{ mic: 'XNAS' }, { mic: 'XNYS' }, { mic: 'XTSE' }, { mic: 'OTCM' }], + } as unknown as SecurityMasterQueryResult; + } + 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; + } + if (text.startsWith('INSERT INTO instrument_identifier_history')) { + const ids = (values?.[0] as number[]) ?? []; + return { + rows: ids.map(() => ({ inserted: 1 })), + } as unknown as SecurityMasterQueryResult; + } + 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; + } + if ( + text.startsWith('INSERT INTO listing_symbol_history') || + text.startsWith('INSERT INTO provider_mapping') || + text.startsWith('INSERT INTO corporate_action_continuity') + ) { + const firstCol = (values?.[0] as unknown[]) ?? []; + return { + rows: firstCol.map(() => ({ inserted: true })), + } as unknown as SecurityMasterQueryResult; + } + if (text.includes('WITH enforced AS')) { + return { + rows: [{ total_overrides: 0, inserted_overrides: 0, updated_overrides: 0 }], + } as unknown as SecurityMasterQueryResult; + } + return { rows: [] } as SecurityMasterQueryResult; + }, + }; + + 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.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([['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(); + + 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([ + ['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'); + }); +});