1865 lines
62 KiB
TypeScript
1865 lines
62 KiB
TypeScript
/**
|
|
* Idempotent, single-transaction PostgreSQL loader for Pass 3 (Stage A/B), Pass 5
|
|
* (`resolution_conflict`), and Pass 6 (`delisting-chains`) security-master outputs.
|
|
*
|
|
* Recorded local benchmark baseline (`2026-11-28`, host PostgreSQL isolated `stock_bot_safety_*`
|
|
* schema, default `chunkSize = 5000`):
|
|
* - Command: `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts`
|
|
* - Workload: 20,000 instruments, 20,000 listings, 60,000 mappings (100,000 core rows; 140,000 total rows).
|
|
* - Observed end-to-end test wall time: 2.36s (2359.01ms, including schema setup, fixture generation,
|
|
* persistence, and COUNT(*) verification).
|
|
* - Throughput (lower bound over full test wall time): 42,391 core rows/s, 59,347 total rows/s.
|
|
*/
|
|
import type {
|
|
DelistingChainResult,
|
|
ListingDelistOutcome,
|
|
Pass6DelistReason,
|
|
} from './delisting-chains';
|
|
import { compareAscii } from './exchange-pass1';
|
|
import {
|
|
isSyntheticInstrumentKey,
|
|
SYNTHETIC_EOD_ISIN_PREFIX,
|
|
type StageAInstrumentCandidate,
|
|
type StageAInstrumentMember,
|
|
type StageAMatchResult,
|
|
type StageASource,
|
|
} from './instrument-stage-a';
|
|
import type {
|
|
ListingNaturalKey,
|
|
StageBListingCandidate,
|
|
StageBMatchMethod,
|
|
StageBMatchResult,
|
|
StageBProviderMappingCandidate,
|
|
} from './listing-stage-b';
|
|
import type { PriceCrossCheckResult } from './price-cross-check';
|
|
|
|
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;
|
|
|
|
const activePersistClients = new WeakSet<SecurityMasterQueryable>();
|
|
|
|
/**
|
|
* 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<StageBMatchMethod | 'override', number>;
|
|
|
|
export interface SecurityMasterQueryResult<Row = Record<string, unknown>> {
|
|
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<Row = Record<string, unknown>>(
|
|
text: string,
|
|
values?: readonly unknown[]
|
|
): Promise<SecurityMasterQueryResult<Row>>;
|
|
release?: (...args: unknown[]) => unknown;
|
|
}
|
|
|
|
export interface PersistSecurityMasterInput {
|
|
readonly stageA: StageAMatchResult;
|
|
readonly stageB: StageBMatchResult;
|
|
readonly pass4?: PriceCrossCheckResult;
|
|
readonly pass6?: DelistingChainResult;
|
|
readonly securityTypeByIsin: ReadonlyMap<string, SecurityType>;
|
|
}
|
|
|
|
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 providerMappingsDeletedStaleFallback: 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<string, number>;
|
|
readonly listingIdByKey: ReadonlyMap<string, number>;
|
|
}
|
|
|
|
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 SymbolHistoryUpsertCountsRow {
|
|
inserted_count: number;
|
|
updated_count: number;
|
|
}
|
|
|
|
interface ProviderMappingUpsertRow {
|
|
source: string;
|
|
source_id: string;
|
|
valid_from: string;
|
|
inserted: boolean;
|
|
}
|
|
|
|
interface StaleFallbackDeleteCountRow {
|
|
deleted_count: number;
|
|
}
|
|
|
|
interface OverrideEnforceRow {
|
|
source: string;
|
|
source_id: string;
|
|
valid_from: string;
|
|
inserted: boolean | null;
|
|
}
|
|
|
|
interface ExistingConflictRow {
|
|
source: string;
|
|
source_id: string;
|
|
conflict_kind: string;
|
|
}
|
|
|
|
interface ExistingPass4ConflictRow {
|
|
row_idx: number;
|
|
}
|
|
|
|
interface PreparedInstrument {
|
|
readonly primaryIsin: string;
|
|
readonly isSynthetic: boolean;
|
|
readonly syntheticSourceId: string | null;
|
|
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;
|
|
readonly previousValidFrom: string | null;
|
|
}
|
|
|
|
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;
|
|
readonly isPass4: boolean;
|
|
}
|
|
|
|
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<ListingNaturalKey>): 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<string, unknown>;
|
|
const keys = Object.keys(record).sort(compareAscii);
|
|
const out: Record<string, unknown> = {};
|
|
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<string, unknown>;
|
|
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<string, ListingDelistOutcome>;
|
|
} {
|
|
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');
|
|
}
|
|
if (input.pass4 !== undefined) {
|
|
if (
|
|
input.pass4 === null ||
|
|
typeof input.pass4 !== 'object' ||
|
|
!Array.isArray(input.pass4.conflicts)
|
|
) {
|
|
throw new TypeError('persistSecurityMaster requires pass4.conflicts to be an array');
|
|
}
|
|
}
|
|
|
|
const seenIsins = new Set<string>();
|
|
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<string>();
|
|
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<string>();
|
|
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<string, ListingDelistOutcome>();
|
|
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<string>();
|
|
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),
|
|
isPass4: false,
|
|
});
|
|
}
|
|
|
|
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),
|
|
isPass4: false,
|
|
});
|
|
}
|
|
|
|
if (input.pass4 !== undefined) {
|
|
for (const c of input.pass4.conflicts) {
|
|
raw.push({
|
|
key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}\u0000${c.detail.right.source}\u0000${c.detail.right.sourceId}`,
|
|
source: c.source,
|
|
sourceId: c.sourceId,
|
|
conflictKind: c.conflictKind,
|
|
detailJson: stableJsonStringify(c.detail),
|
|
isPass4: true,
|
|
});
|
|
}
|
|
}
|
|
|
|
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),
|
|
isPass4: false,
|
|
});
|
|
}
|
|
}
|
|
|
|
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<string>();
|
|
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<string, ListingDelistOutcome>
|
|
): Promise<PersistSecurityMasterResult> {
|
|
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 providerMappingsDeletedStaleFallback = 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<string, number>();
|
|
const listingIdByKey = new Map<string, number>();
|
|
const skippedInstrumentIsins = new Set<string>();
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 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;
|
|
}
|
|
const isSynthetic = isSyntheticInstrumentKey(candidate.primaryIsin);
|
|
const syntheticSourceId = isSynthetic
|
|
? (candidate.members.find(m => m.source === 'eod')?.sourceId ??
|
|
candidate.primaryIsin.slice(SYNTHETIC_EOD_ISIN_PREFIX.length))
|
|
: null;
|
|
preparedInstruments.push({
|
|
primaryIsin: candidate.primaryIsin,
|
|
isSynthetic,
|
|
syntheticSourceId,
|
|
primaryCusip: isSynthetic ? null : candidate.primaryCusip,
|
|
canonicalName: trimmedName,
|
|
securityType,
|
|
issuerCountry: candidate.issuerCountry,
|
|
bestSource: selectBestMemberSource(candidate.members),
|
|
});
|
|
}
|
|
|
|
if (preparedInstruments.length > 0) {
|
|
const existingByIsin = new Map<string, ExistingInstrumentRow>();
|
|
const realInstruments = preparedInstruments.filter(item => !item.isSynthetic);
|
|
const syntheticInstruments = preparedInstruments.filter(item => item.isSynthetic);
|
|
|
|
for (let offset = 0; offset < realInstruments.length; offset += chunkSize) {
|
|
const slice = realInstruments.slice(offset, offset + chunkSize);
|
|
const isins = slice.map(item => item.primaryIsin);
|
|
const res = await client.query<ExistingInstrumentRow>(
|
|
`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);
|
|
}
|
|
}
|
|
|
|
for (let offset = 0; offset < syntheticInstruments.length; offset += chunkSize) {
|
|
const slice = syntheticInstruments.slice(offset, offset + chunkSize);
|
|
const sourceIdToKey = new Map<string, string>();
|
|
const sourceIds: string[] = [];
|
|
for (const item of slice) {
|
|
if (item.syntheticSourceId !== null) {
|
|
sourceIdToKey.set(item.syntheticSourceId, item.primaryIsin);
|
|
sourceIds.push(item.syntheticSourceId);
|
|
}
|
|
}
|
|
if (sourceIds.length === 0) {
|
|
continue;
|
|
}
|
|
const res = await client.query<{
|
|
source_id: string;
|
|
instrument_id: number;
|
|
primary_cusip: string | null;
|
|
canonical_name: string;
|
|
security_type: string;
|
|
issuer_country: string | null;
|
|
}>(
|
|
`SELECT DISTINCT ON (pm.source_id)
|
|
pm.source_id,
|
|
i.instrument_id,
|
|
btrim(i.primary_cusip) AS primary_cusip,
|
|
i.canonical_name,
|
|
i.security_type,
|
|
btrim(i.issuer_country) AS issuer_country
|
|
FROM provider_mapping pm
|
|
JOIN listing l ON l.listing_id = pm.listing_id
|
|
JOIN instrument i ON i.instrument_id = l.instrument_id
|
|
WHERE pm.source = 'eod'
|
|
AND pm.source_id = ANY($1::text[])
|
|
AND i.primary_isin IS NULL
|
|
ORDER BY pm.source_id, pm.valid_from ASC`,
|
|
[sourceIds]
|
|
);
|
|
for (const row of res.rows) {
|
|
const key = sourceIdToKey.get(row.source_id);
|
|
if (key !== undefined) {
|
|
existingByIsin.set(key, {
|
|
instrument_id: row.instrument_id,
|
|
primary_isin: key,
|
|
primary_cusip: row.primary_cusip,
|
|
canonical_name: row.canonical_name,
|
|
security_type: row.security_type,
|
|
issuer_country: row.issuer_country,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
const toInsertReal: PreparedInstrument[] = [];
|
|
const toInsertSynthetic: PreparedInstrument[] = [];
|
|
const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = [];
|
|
|
|
for (const item of preparedInstruments) {
|
|
const existing = existingByIsin.get(item.primaryIsin);
|
|
if (existing === undefined) {
|
|
if (item.isSynthetic) {
|
|
toInsertSynthetic.push(item);
|
|
} else {
|
|
toInsertReal.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 < toInsertReal.length; offset += chunkSize) {
|
|
const slice = toInsertReal.slice(offset, offset + chunkSize);
|
|
const res = await client.query<InsertedInstrumentRow>(
|
|
`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 < toInsertSynthetic.length; offset += chunkSize) {
|
|
const slice = toInsertSynthetic.slice(offset, offset + chunkSize);
|
|
const res = await client.query<{ instrument_id: number }>(
|
|
`INSERT INTO instrument (
|
|
primary_isin,
|
|
primary_cusip,
|
|
canonical_name,
|
|
security_type,
|
|
issuer_country
|
|
)
|
|
SELECT NULL, NULL, u.canonical_name, u.security_type, u.issuer_country
|
|
FROM UNNEST(
|
|
$1::text[],
|
|
$2::varchar[],
|
|
$3::bpchar[]
|
|
) AS u(canonical_name, security_type, issuer_country)
|
|
RETURNING instrument_id`,
|
|
[
|
|
slice.map(item => item.canonicalName),
|
|
slice.map(item => item.securityType),
|
|
slice.map(item => item.issuerCountry),
|
|
]
|
|
);
|
|
for (let i = 0; i < res.rows.length; i++) {
|
|
const item = slice[i];
|
|
const row = res.rows[i];
|
|
if (item !== undefined && row !== undefined) {
|
|
instrumentIdByIsin.set(item.primaryIsin, 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) {
|
|
if (item.isSynthetic) {
|
|
continue;
|
|
}
|
|
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<string>(exchangeRes.rows.map(row => row.mic));
|
|
|
|
const preparedListings: PreparedListing[] = [];
|
|
const uniqueInstrumentIds = new Set<number>();
|
|
|
|
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<string, ExistingListingRow>();
|
|
const duplicateDbKeys = new Set<string>();
|
|
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<ExistingListingRow>(
|
|
`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<string, string>();
|
|
|
|
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<InsertedListingRow>(
|
|
`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 (replaces loader-generated interval
|
|
// when listed_from changes while preserving unrelated historical aliases).
|
|
const symbolHistoryRows: PreparedSymbolHistoryRow[] = [];
|
|
for (const item of preparedListings) {
|
|
const listingId = listingIdByKey.get(item.naturalKey);
|
|
if (listingId === undefined) {
|
|
continue;
|
|
}
|
|
const existing = existingByDbKey.get(item.dbNaturalKey);
|
|
const ticker =
|
|
item.classSuffix.length > 0 ? `${item.tickerRoot}.${item.classSuffix}` : item.tickerRoot;
|
|
symbolHistoryRows.push({
|
|
listingId,
|
|
ticker,
|
|
validFrom: item.listedFrom ?? DEFAULT_VALID_FROM,
|
|
validTo: item.listedTo,
|
|
source: 'eod',
|
|
previousValidFrom:
|
|
existing !== undefined ? (existing.listed_from ?? DEFAULT_VALID_FROM) : null,
|
|
});
|
|
}
|
|
|
|
for (let offset = 0; offset < symbolHistoryRows.length; offset += chunkSize) {
|
|
const slice = symbolHistoryRows.slice(offset, offset + chunkSize);
|
|
const res = await client.query<SymbolHistoryUpsertCountsRow>(
|
|
`WITH incoming AS (
|
|
SELECT *
|
|
FROM UNNEST(
|
|
$1::int4[],
|
|
$2::varchar[],
|
|
$3::date[],
|
|
$4::date[],
|
|
$5::varchar[],
|
|
$6::date[]
|
|
) AS u(listing_id, ticker, valid_from, valid_to, source, prev_valid_from)
|
|
),
|
|
deleted_stale AS (
|
|
DELETE FROM listing_symbol_history AS lsh
|
|
USING incoming AS i
|
|
WHERE lsh.listing_id = i.listing_id
|
|
AND lsh.ticker = i.ticker
|
|
AND lsh.source = i.source
|
|
AND i.prev_valid_from IS NOT NULL
|
|
AND lsh.valid_from = i.prev_valid_from
|
|
AND lsh.valid_from IS DISTINCT FROM i.valid_from
|
|
RETURNING lsh.listing_id, lsh.ticker
|
|
),
|
|
upserted AS (
|
|
INSERT INTO listing_symbol_history (
|
|
listing_id,
|
|
ticker,
|
|
valid_from,
|
|
valid_to,
|
|
source
|
|
)
|
|
SELECT
|
|
i.listing_id,
|
|
i.ticker,
|
|
i.valid_from,
|
|
i.valid_to,
|
|
i.source
|
|
FROM incoming AS i
|
|
ON CONFLICT (listing_id, ticker, valid_from) DO UPDATE SET
|
|
valid_to = EXCLUDED.valid_to
|
|
WHERE listing_symbol_history.valid_to IS DISTINCT FROM EXCLUDED.valid_to
|
|
RETURNING listing_id, ticker, (xmax = 0) AS inserted
|
|
)
|
|
SELECT
|
|
(
|
|
SELECT count(*)::int
|
|
FROM upserted u
|
|
WHERE u.inserted
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM deleted_stale d
|
|
WHERE d.listing_id = u.listing_id
|
|
AND d.ticker = u.ticker
|
|
)
|
|
) AS inserted_count,
|
|
(
|
|
SELECT count(*)::int
|
|
FROM (
|
|
SELECT listing_id, ticker FROM upserted WHERE NOT inserted
|
|
UNION
|
|
SELECT listing_id, ticker FROM deleted_stale
|
|
) AS updated_keys
|
|
) AS updated_count`,
|
|
[
|
|
slice.map(row => row.listingId),
|
|
slice.map(row => row.ticker),
|
|
slice.map(row => row.validFrom),
|
|
slice.map(row => row.validTo),
|
|
slice.map(row => row.source),
|
|
slice.map(row => row.previousValidFrom),
|
|
]
|
|
);
|
|
const counts = res.rows[0];
|
|
const chunkInserted = Number(counts?.inserted_count ?? 0);
|
|
const chunkUpdated = Number(counts?.updated_count ?? 0);
|
|
listingSymbolHistoryInserted += chunkInserted;
|
|
listingSymbolHistoryUpdated += chunkUpdated;
|
|
listingSymbolHistoryUnchanged += slice.length - chunkInserted - chunkUpdated;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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),
|
|
});
|
|
}
|
|
|
|
const mappingOutcomeByKey = new Map<string, 'inserted' | 'updated' | 'unchanged'>();
|
|
for (const row of preparedMappings) {
|
|
mappingOutcomeByKey.set(`${row.source}\u0000${row.sourceId}\u0000${row.validFrom}`, 'unchanged');
|
|
}
|
|
|
|
for (let offset = 0; offset < preparedMappings.length; offset += chunkSize) {
|
|
const slice = preparedMappings.slice(offset, offset + chunkSize);
|
|
const res = await client.query<ProviderMappingUpsertRow>(
|
|
`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
|
|
source,
|
|
source_id,
|
|
to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
|
(xmax = 0) AS inserted`,
|
|
[
|
|
slice.map(row => row.source),
|
|
slice.map(row => row.sourceId),
|
|
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),
|
|
]
|
|
);
|
|
for (const row of res.rows) {
|
|
const key = `${row.source}\u0000${row.source_id}\u0000${row.valid_from}`;
|
|
mappingOutcomeByKey.set(key, row.inserted ? 'inserted' : 'updated');
|
|
}
|
|
}
|
|
|
|
// Remove stale open-ended DEFAULT_VALID_FROM ('1900-01-01') fallback rows for any
|
|
// (source, source_id) that now has only dated mappings in this run, while preserving
|
|
// override-protected rows and untouched source IDs.
|
|
const fallbackSourceKeys = new Set<string>();
|
|
for (const row of preparedMappings) {
|
|
if (row.validFrom === DEFAULT_VALID_FROM) {
|
|
fallbackSourceKeys.add(`${row.source}\u0000${row.sourceId}`);
|
|
}
|
|
}
|
|
const staleFallbackTargets: Array<{ source: string; sourceId: string }> = [];
|
|
const seenStaleFallbackKeys = new Set<string>();
|
|
for (const row of preparedMappings) {
|
|
const pairKey = `${row.source}\u0000${row.sourceId}`;
|
|
if (fallbackSourceKeys.has(pairKey) || seenStaleFallbackKeys.has(pairKey)) {
|
|
continue;
|
|
}
|
|
seenStaleFallbackKeys.add(pairKey);
|
|
staleFallbackTargets.push({ source: row.source, sourceId: row.sourceId });
|
|
}
|
|
|
|
for (let offset = 0; offset < staleFallbackTargets.length; offset += chunkSize) {
|
|
const slice = staleFallbackTargets.slice(offset, offset + chunkSize);
|
|
const deleteRes = await client.query<StaleFallbackDeleteCountRow>(
|
|
`WITH deleted AS (
|
|
DELETE FROM provider_mapping AS pm
|
|
USING UNNEST(
|
|
$1::varchar[],
|
|
$2::varchar[]
|
|
) AS u(source, source_id)
|
|
WHERE pm.source = u.source
|
|
AND pm.source_id = u.source_id
|
|
AND pm.valid_from = $3::date
|
|
AND pm.method <> 'override'
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM override o
|
|
WHERE o.source = pm.source
|
|
AND o.source_id = pm.source_id
|
|
AND o.valid_from = pm.valid_from
|
|
)
|
|
RETURNING 1
|
|
)
|
|
SELECT count(*)::int AS deleted_count FROM deleted`,
|
|
[
|
|
slice.map(target => target.source),
|
|
slice.map(target => target.sourceId),
|
|
DEFAULT_VALID_FROM,
|
|
]
|
|
);
|
|
providerMappingsDeletedStaleFallback += Number(deleteRes.rows[0]?.deleted_count ?? 0);
|
|
}
|
|
|
|
// Enforce override precedence unconditionally across all rows in `override` and count each
|
|
// mapping key once according to its final insert/update/unchanged outcome across matcher + override.
|
|
const overrideRes = await client.query<OverrideEnforceRow>(
|
|
`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
|
|
source,
|
|
source_id,
|
|
valid_from,
|
|
(xmax = 0) AS inserted
|
|
)
|
|
SELECT
|
|
o.source,
|
|
o.source_id,
|
|
to_char(o.valid_from, 'YYYY-MM-DD') AS valid_from,
|
|
e.inserted
|
|
FROM override o
|
|
LEFT JOIN enforced e
|
|
ON e.source = o.source
|
|
AND e.source_id = o.source_id
|
|
AND e.valid_from = o.valid_from`
|
|
);
|
|
const overridesApplied = overrideRes.rows.length;
|
|
for (const row of overrideRes.rows) {
|
|
const key = `${row.source}\u0000${row.source_id}\u0000${row.valid_from}`;
|
|
const prev = mappingOutcomeByKey.get(key);
|
|
if (row.inserted === true) {
|
|
mappingOutcomeByKey.set(key, 'inserted');
|
|
} else if (row.inserted === false) {
|
|
if (prev !== 'inserted') {
|
|
mappingOutcomeByKey.set(key, 'updated');
|
|
}
|
|
} else if (prev === undefined) {
|
|
mappingOutcomeByKey.set(key, 'unchanged');
|
|
}
|
|
}
|
|
|
|
for (const outcome of mappingOutcomeByKey.values()) {
|
|
if (outcome === 'inserted') {
|
|
providerMappingsInserted += 1;
|
|
} else if (outcome === 'updated') {
|
|
providerMappingsUpdated += 1;
|
|
} else {
|
|
providerMappingsUnchanged += 1;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. Pass 5 resolution_conflict (all statuses preserved; no duplicate open rows)
|
|
// ---------------------------------------------------------------------------
|
|
const { uniqueConflicts, deduplicatedCount: conflictsDeduplicated } =
|
|
collectAndDeduplicateConflicts(input);
|
|
|
|
if (uniqueConflicts.length > 0) {
|
|
const nonPass4Conflicts: PreparedConflict[] = [];
|
|
const pass4Conflicts: PreparedConflict[] = [];
|
|
for (const conflict of uniqueConflicts) {
|
|
if (conflict.isPass4) {
|
|
pass4Conflicts.push(conflict);
|
|
} else {
|
|
nonPass4Conflicts.push(conflict);
|
|
}
|
|
}
|
|
|
|
const existingConflictKeys = new Set<string>();
|
|
for (let offset = 0; offset < nonPass4Conflicts.length; offset += chunkSize) {
|
|
const slice = nonPass4Conflicts.slice(offset, offset + chunkSize);
|
|
const res = await client.query<ExistingConflictRow>(
|
|
`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 existingPass4ConflictKeys = new Set<string>();
|
|
for (let offset = 0; offset < pass4Conflicts.length; offset += chunkSize) {
|
|
const slice = pass4Conflicts.slice(offset, offset + chunkSize);
|
|
const res = await client.query<ExistingPass4ConflictRow>(
|
|
`SELECT DISTINCT
|
|
u.row_idx
|
|
FROM resolution_conflict rc
|
|
INNER JOIN UNNEST(
|
|
$1::varchar[],
|
|
$2::varchar[],
|
|
$3::varchar[],
|
|
$4::jsonb[],
|
|
$5::int4[]
|
|
) AS u(source, source_id, conflict_kind, detail, row_idx)
|
|
ON rc.source = u.source
|
|
AND rc.source_id = u.source_id
|
|
AND rc.conflict_kind = u.conflict_kind
|
|
AND rc.detail = u.detail`,
|
|
[
|
|
slice.map(c => c.source),
|
|
slice.map(c => c.sourceId),
|
|
slice.map(c => c.conflictKind),
|
|
slice.map(c => c.detailJson),
|
|
slice.map((_, idx) => idx),
|
|
]
|
|
);
|
|
for (const row of res.rows) {
|
|
const matched = slice[row.row_idx];
|
|
if (matched !== undefined) {
|
|
existingPass4ConflictKeys.add(matched.key);
|
|
}
|
|
}
|
|
}
|
|
|
|
const toInsertConflicts: PreparedConflict[] = [];
|
|
for (const conflict of uniqueConflicts) {
|
|
const exists = conflict.isPass4
|
|
? existingPass4ConflictKeys.has(conflict.key)
|
|
: existingConflictKeys.has(conflict.key);
|
|
if (exists) {
|
|
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<UpsertFlagRow>(
|
|
`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,
|
|
providerMappingsDeletedStaleFallback,
|
|
|
|
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`).
|
|
* - Stale fallback cleanup: when a run supplies only dated `provider_mapping` rows for a
|
|
* `(source, source_id)`, any leftover `1900-01-01` (`DEFAULT_VALID_FROM`) non-override fallback
|
|
* row not protected by `override` is deleted inside the same transaction and counted in
|
|
* `providerMappingsDeletedStaleFallback`.
|
|
* - 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<PersistSecurityMasterResult> {
|
|
assertDedicatedQueryable(client);
|
|
const chunkSize = validateChunkSize(options.chunkSize);
|
|
const { outcomeByListingKey } = validateInputsAndIndexPass6(input);
|
|
|
|
if (activePersistClients.has(client)) {
|
|
throw new Error(
|
|
'persistSecurityMaster does not allow overlapping calls on the same client; use a dedicated PoolClient per concurrent call'
|
|
);
|
|
}
|
|
activePersistClients.add(client);
|
|
|
|
try {
|
|
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;
|
|
}
|
|
} finally {
|
|
activePersistClients.delete(client);
|
|
}
|
|
}
|
|
|
|
// Re-export type aliases used by callers without forcing extra imports.
|
|
export type { StageAInstrumentCandidate, StageBListingCandidate, StageBProviderMappingCandidate };
|