T-91: M1.1o — Security-master persist: remove the stale 1900-01-01 fallback provider_mapping row when a rerun supplies a real start date

This commit is contained in:
Studio 2026-11-28 06:49:18 -05:00
parent 297a7615bb
commit 50e6da57f0
5 changed files with 864 additions and 0 deletions

View file

@ -69,6 +69,7 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/sto
- **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.
- **Stale fallback cleanup:** When a run supplies only dated `provider_mapping` rows (`validFrom !== '1900-01-01'`) for a `(source, source_id)`, any leftover `1900-01-01` fallback row for that pair is deleted in batched `UNNEST` statements within the same transaction and counted in `providerMappingsDeletedStaleFallback`. Rows with `method = 'override'`, rows protected by an `override` entry at `1900-01-01`, dated rows, and `(source, source_id)` pairs absent from the run are never deleted.
- **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:

View file

@ -145,6 +145,7 @@ export interface PersistSecurityMasterResult {
readonly providerMappingsUpdated: number;
readonly providerMappingsUnchanged: number;
readonly providerMappingsSkipped: number;
readonly providerMappingsDeletedStaleFallback: number;
readonly overridesApplied: number;
@ -219,6 +220,10 @@ interface ProviderMappingUpsertRow {
inserted: boolean;
}
interface StaleFallbackDeleteCountRow {
deleted_count: number;
}
interface OverrideEnforceRow {
source: string;
source_id: string;
@ -618,6 +623,7 @@ async function persistWithinTransaction(
let providerMappingsUpdated = 0;
let providerMappingsUnchanged = 0;
let skippedMappingMissingListing = 0;
let providerMappingsDeletedStaleFallback = 0;
let conflictsInserted = 0;
let conflictsUnchanged = 0;
@ -1297,6 +1303,58 @@ async function persistWithinTransaction(
}
}
// 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>(
@ -1593,6 +1651,7 @@ async function persistWithinTransaction(
providerMappingsUpdated,
providerMappingsUnchanged,
providerMappingsSkipped: skippedMappingMissingListing,
providerMappingsDeletedStaleFallback,
overridesApplied,
@ -1644,6 +1703,10 @@ async function persistWithinTransaction(
* 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.