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-27 23:07:15 -05:00
parent 7a8e83d22c
commit d65d3f00d5
5 changed files with 3248 additions and 0 deletions

View file

@ -63,3 +63,17 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@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.

View file

@ -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,

File diff suppressed because it is too large Load diff