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

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

View file

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