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:
parent
297a7615bb
commit
50e6da57f0
5 changed files with 864 additions and 0 deletions
|
|
@ -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:
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import {
|
||||
DEFAULT_OTC_MICS,
|
||||
DEFAULT_VALID_FROM,
|
||||
formatListingNaturalKey,
|
||||
linkDelistingChains,
|
||||
matchInstrumentsStageA,
|
||||
|
|
@ -882,6 +883,441 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
|
|||
expect(run3.listingSymbolHistoryUnchanged).toBe(1);
|
||||
});
|
||||
|
||||
test('removes stale 1900-01-01 provider_mapping fallback on dated rerun and is idempotent thereafter', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const stageA = matchInstrumentsStageA([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'FB.US',
|
||||
isin: 'US30303M1027',
|
||||
cusip: '30303M102',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Meta Platforms Inc.',
|
||||
},
|
||||
]);
|
||||
const fbKey = {
|
||||
primaryIsin: 'US30303M1027',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'FB',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const securityTypeByIsin = new Map<string, SecurityType>([['US30303M1027', 'common']]);
|
||||
|
||||
const makeStageB = (validFrom: string | null): StageBMatchResult => ({
|
||||
listings: [
|
||||
{
|
||||
...fbKey,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: validFrom,
|
||||
listedTo: null,
|
||||
},
|
||||
],
|
||||
providerMappings: [
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'FB.US',
|
||||
listingKey: fbKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom,
|
||||
validTo: null,
|
||||
},
|
||||
],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalListings: 1,
|
||||
totalProviderMappings: 1,
|
||||
listingsWithIbConid: 0,
|
||||
excludedFunds: 0,
|
||||
bySource: {
|
||||
eod: { total: 1, matched: 1, 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 },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Run 1: validFrom null -> writes 1900-01-01 fallback row
|
||||
const run1 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, { stageA, stageB: makeStageB(null), securityTypeByIsin })
|
||||
);
|
||||
const fbListingId = run1.listingIdByKey.get(formatListingNaturalKey(fbKey))!;
|
||||
expect(run1.providerMappingsInserted).toBe(1);
|
||||
expect(run1.providerMappingsUpdated).toBe(0);
|
||||
expect(run1.providerMappingsUnchanged).toBe(0);
|
||||
expect(run1.providerMappingsDeletedStaleFallback).toBe(0);
|
||||
|
||||
const rowsAfterRun1 = (
|
||||
await f.pool.query<{ valid_from: string; listing_id: number }>(
|
||||
`SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
||||
FROM provider_mapping
|
||||
WHERE source = 'eod' AND source_id = 'FB.US'
|
||||
ORDER BY valid_from`
|
||||
)
|
||||
).rows;
|
||||
expect(rowsAfterRun1).toEqual([{ valid_from: DEFAULT_VALID_FROM, listing_id: fbListingId }]);
|
||||
|
||||
// Run 2: real validFrom supplied -> deletes 1900-01-01 fallback and keeps only 2012-05-18
|
||||
const run2 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: makeStageB('2012-05-18'),
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
expect(run2.providerMappingsInserted).toBe(1);
|
||||
expect(run2.providerMappingsUpdated).toBe(0);
|
||||
expect(run2.providerMappingsUnchanged).toBe(0);
|
||||
expect(run2.providerMappingsDeletedStaleFallback).toBe(1);
|
||||
|
||||
const rowsAfterRun2 = (
|
||||
await f.pool.query<{ valid_from: string; listing_id: number }>(
|
||||
`SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
||||
FROM provider_mapping
|
||||
WHERE source = 'eod' AND source_id = 'FB.US'
|
||||
ORDER BY valid_from`
|
||||
)
|
||||
).rows;
|
||||
expect(rowsAfterRun2).toEqual([{ valid_from: '2012-05-18', listing_id: fbListingId }]);
|
||||
|
||||
// Run 3: identical dated rerun -> idempotent (0 deletes, 1 unchanged)
|
||||
const run3 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: makeStageB('2012-05-18'),
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
expect(run3.providerMappingsInserted).toBe(0);
|
||||
expect(run3.providerMappingsUpdated).toBe(0);
|
||||
expect(run3.providerMappingsUnchanged).toBe(1);
|
||||
expect(run3.providerMappingsDeletedStaleFallback).toBe(0);
|
||||
|
||||
const rowsAfterRun3 = (
|
||||
await f.pool.query<{ valid_from: string; listing_id: number }>(
|
||||
`SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
||||
FROM provider_mapping
|
||||
WHERE source = 'eod' AND source_id = 'FB.US'
|
||||
ORDER BY valid_from`
|
||||
)
|
||||
).rows;
|
||||
expect(rowsAfterRun3).toEqual([{ valid_from: '2012-05-18', listing_id: fbListingId }]);
|
||||
});
|
||||
|
||||
test('preserves override-protected 1900-01-01 provider_mapping rows on dated rerun', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const stageA = matchInstrumentsStageA([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'A.US',
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Listing A Corp',
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'B.US',
|
||||
isin: 'US30303M1027',
|
||||
cusip: '30303M102',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Listing B Corp',
|
||||
},
|
||||
]);
|
||||
const keyA = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAA',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const keyB = {
|
||||
primaryIsin: 'US30303M1027',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'BBB',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const securityTypeByIsin = new Map<string, SecurityType>([
|
||||
['US0378331005', 'common'],
|
||||
['US30303M1027', 'common'],
|
||||
]);
|
||||
|
||||
const listings = [
|
||||
{ ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2012-05-18', listedTo: null },
|
||||
{ ...keyB, ibConid: null, ibPrimaryExchange: null, listedFrom: '2012-05-18', listedTo: null },
|
||||
];
|
||||
const emptyStats = {
|
||||
totalListings: 2,
|
||||
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 },
|
||||
},
|
||||
};
|
||||
|
||||
// Run 1: seed listings and three 1900-01-01 fallback mappings pointing at listing A.
|
||||
const run1 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: {
|
||||
listings,
|
||||
providerMappings: [
|
||||
{ source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
{ source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
{ source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: emptyStats,
|
||||
},
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
const listingAId = run1.listingIdByKey.get(formatListingNaturalKey(keyA))!;
|
||||
const listingBId = run1.listingIdByKey.get(formatListingNaturalKey(keyB))!;
|
||||
|
||||
// Materialize override for OVR_MAT.US via a persist run before the dated rerun.
|
||||
await f.pool.query(
|
||||
`INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'OVR_MAT.US', DATE '1900-01-01', NULL, $1, 'already materialized override', 'director')`,
|
||||
[listingBId]
|
||||
);
|
||||
await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: {
|
||||
listings,
|
||||
providerMappings: [
|
||||
{ source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
{ source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
{ source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: emptyStats,
|
||||
},
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
|
||||
// Newly insert override for OVR_NEW.US (still method='tier1_isin' in provider_mapping) and
|
||||
// directly mark OVR_METHOD_ONLY.US as method='override' (no row in override table).
|
||||
await f.pool.query(
|
||||
`INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'OVR_NEW.US', DATE '1900-01-01', NULL, $1, 'unmaterialized override', 'director')`,
|
||||
[listingBId]
|
||||
);
|
||||
await f.pool.query(
|
||||
`UPDATE provider_mapping
|
||||
SET method = 'override', confidence = 1.000, listing_id = $1
|
||||
WHERE source = 'eod' AND source_id = 'OVR_METHOD_ONLY.US' AND valid_from = DATE '1900-01-01'`,
|
||||
[listingBId]
|
||||
);
|
||||
|
||||
// Run 2: dated rerun for all three source IDs -> none of the 1900-01-01 rows may be deleted.
|
||||
const run2 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: {
|
||||
listings,
|
||||
providerMappings: [
|
||||
{ source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
||||
{ source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
||||
{ source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
||||
],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: emptyStats,
|
||||
},
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
expect(run2.providerMappingsDeletedStaleFallback).toBe(0);
|
||||
expect(run2.overridesApplied).toBe(2);
|
||||
|
||||
const rows = (
|
||||
await f.pool.query<{
|
||||
source_id: string;
|
||||
valid_from: string;
|
||||
listing_id: number;
|
||||
method: string;
|
||||
confidence: string;
|
||||
}>(
|
||||
`SELECT source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id, method, confidence::text
|
||||
FROM provider_mapping
|
||||
WHERE source = 'eod'
|
||||
ORDER BY source_id, valid_from`
|
||||
)
|
||||
).rows;
|
||||
|
||||
expect(rows).toEqual([
|
||||
{ source_id: 'OVR_MAT.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' },
|
||||
{ source_id: 'OVR_MAT.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' },
|
||||
{ source_id: 'OVR_METHOD_ONLY.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' },
|
||||
{ source_id: 'OVR_METHOD_ONLY.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' },
|
||||
{ source_id: 'OVR_NEW.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' },
|
||||
{ source_id: 'OVR_NEW.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('stale-fallback cleanup preserves absent pairs, other sources, dated rows, and mixed runs while removing cross-listing fallbacks', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const stageA = matchInstrumentsStageA([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'A.US',
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Listing A Corp',
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'B.US',
|
||||
isin: 'US30303M1027',
|
||||
cusip: '30303M102',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Listing B Corp',
|
||||
},
|
||||
]);
|
||||
const keyA = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAA',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const keyB = {
|
||||
primaryIsin: 'US30303M1027',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'BBB',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const securityTypeByIsin = new Map<string, SecurityType>([
|
||||
['US0378331005', 'common'],
|
||||
['US30303M1027', 'common'],
|
||||
]);
|
||||
const listings = [
|
||||
{ ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2010-01-04', listedTo: null },
|
||||
{ ...keyB, ibConid: null, ibPrimaryExchange: null, listedFrom: '2018-06-01', listedTo: null },
|
||||
];
|
||||
const baseStats = {
|
||||
totalListings: 2,
|
||||
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 },
|
||||
},
|
||||
};
|
||||
|
||||
// Run 1: seed initial rows covering all preservation boundaries + cross-listing fallback.
|
||||
const run1 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: {
|
||||
listings,
|
||||
providerMappings: [
|
||||
// Absent from Run 2 -> must be kept
|
||||
{ source: 'eod', sourceId: 'ABSENT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
// Same source_id under a different source ('qm') -> must be kept when 'eod' reruns dated
|
||||
{ source: 'qm', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier3_ticker_span', validFrom: null, validTo: null },
|
||||
{ source: 'eod', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
// Existing dated row -> must never be deleted when another dated row is added
|
||||
{ source: 'eod', sourceId: 'DATED_KEEP.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2010-01-04', validTo: '2019-12-31' },
|
||||
// Mixed run (both 1900-01-01 and dated in Run 2) -> both must be kept
|
||||
{ source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: '2014-12-31' },
|
||||
// Cross-listing reassignment: 1900-01-01 points at listing A, Run 2 maps dated to listing B
|
||||
{ source: 'eod', sourceId: 'REASSIGN.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null },
|
||||
],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: baseStats,
|
||||
},
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
const listingAId = run1.listingIdByKey.get(formatListingNaturalKey(keyA))!;
|
||||
const listingBId = run1.listingIdByKey.get(formatListingNaturalKey(keyB))!;
|
||||
expect(run1.providerMappingsDeletedStaleFallback).toBe(0);
|
||||
|
||||
// Run 2:
|
||||
// - ABSENT.US omitted
|
||||
// - (eod, SHARED.ID) dated -> deletes only (eod, SHARED.ID, 1900-01-01), keeps (qm, SHARED.ID, 1900-01-01)
|
||||
// - (eod, DATED_KEEP.US) adds a second dated row -> keeps 2010-01-04
|
||||
// - (eod, MIXED.US) supplies both 1900-01-01 and 2015-01-01 -> keeps both
|
||||
// - (eod, REASSIGN.US) dated to listing B -> deletes stale 1900-01-01 pointing at listing A
|
||||
const run2 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: {
|
||||
listings,
|
||||
providerMappings: [
|
||||
{ source: 'eod', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null },
|
||||
{ source: 'eod', sourceId: 'DATED_KEEP.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2020-01-02', validTo: null },
|
||||
{ source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: DEFAULT_VALID_FROM, validTo: '2014-12-31' },
|
||||
{ source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2015-01-01', validTo: null },
|
||||
{ source: 'eod', sourceId: 'REASSIGN.US', listingKey: keyB, method: 'tier1_isin', validFrom: '2018-06-01', validTo: null },
|
||||
],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: baseStats,
|
||||
},
|
||||
securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
|
||||
// Exactly 2 stale fallbacks removed: (eod, SHARED.ID) and (eod, REASSIGN.US)
|
||||
expect(run2.providerMappingsDeletedStaleFallback).toBe(2);
|
||||
expect(run2.providerMappingsInserted).toBe(4);
|
||||
expect(run2.providerMappingsUpdated).toBe(0);
|
||||
expect(run2.providerMappingsUnchanged).toBe(1); // (eod, MIXED.US, 1900-01-01)
|
||||
|
||||
const allRows = (
|
||||
await f.pool.query<{
|
||||
source: string;
|
||||
source_id: string;
|
||||
valid_from: string;
|
||||
listing_id: number;
|
||||
}>(
|
||||
`SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id
|
||||
FROM provider_mapping
|
||||
ORDER BY source, source_id, valid_from`
|
||||
)
|
||||
).rows;
|
||||
|
||||
expect(allRows).toEqual([
|
||||
{ source: 'eod', source_id: 'ABSENT.US', valid_from: '1900-01-01', listing_id: listingAId },
|
||||
{ source: 'eod', source_id: 'DATED_KEEP.US', valid_from: '2010-01-04', listing_id: listingAId },
|
||||
{ source: 'eod', source_id: 'DATED_KEEP.US', valid_from: '2020-01-02', listing_id: listingAId },
|
||||
{ source: 'eod', source_id: 'MIXED.US', valid_from: '1900-01-01', listing_id: listingAId },
|
||||
{ source: 'eod', source_id: 'MIXED.US', valid_from: '2015-01-01', listing_id: listingAId },
|
||||
{ source: 'eod', source_id: 'REASSIGN.US', valid_from: '2018-06-01', listing_id: listingBId },
|
||||
{ source: 'eod', source_id: 'SHARED.ID', valid_from: '2012-05-18', listing_id: listingAId },
|
||||
{ source: 'qm', source_id: 'SHARED.ID', valid_from: '1900-01-01', listing_id: listingAId },
|
||||
]);
|
||||
});
|
||||
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -219,6 +219,7 @@ describe('persistSecurityMaster unit tests', () => {
|
|||
expect(result.instrumentsInserted).toBe(0);
|
||||
expect(result.listingsInserted).toBe(0);
|
||||
expect(result.providerMappingsInserted).toBe(0);
|
||||
expect(result.providerMappingsDeletedStaleFallback).toBe(0);
|
||||
expect(result.overridesApplied).toBe(0);
|
||||
});
|
||||
|
||||
|
|
@ -960,4 +961,366 @@ describe('persistSecurityMaster unit tests', () => {
|
|||
).rejects.toThrow(TypeError);
|
||||
expect(queries.length).toBe(0);
|
||||
});
|
||||
|
||||
test('selects deduplicated dated-only stale-fallback targets with override guards and parameterized SQL', async () => {
|
||||
const hostileSourceId = "HOSTILE'ID;DELETE";
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc.',
|
||||
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
const validKey = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const missingKey = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XXXX',
|
||||
tickerRoot: 'MISS',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const stageB = emptyStageB();
|
||||
stageB.listings.push({
|
||||
...validKey,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: '2012-05-18',
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push(
|
||||
// Dated-only with two dated rows -> must appear ONCE in staleFallbackTargets
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'DATED_MULTI.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '2012-05-18',
|
||||
validTo: '2019-12-31',
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'DATED_MULTI.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '2020-01-01',
|
||||
validTo: null,
|
||||
},
|
||||
// Dated-only with hostile sourceId -> must be parameterized, never interpolated
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: hostileSourceId,
|
||||
listingKey: validKey,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: '2015-01-02',
|
||||
validTo: null,
|
||||
},
|
||||
// Fallback-only (null) -> excluded
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'FALLBACK_NULL.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
},
|
||||
// Fallback-only (explicit DEFAULT_VALID_FROM) -> excluded
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'FALLBACK_EXPLICIT.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: DEFAULT_VALID_FROM,
|
||||
validTo: null,
|
||||
},
|
||||
// Mixed fallback-first then dated -> excluded
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'MIXED_FB_FIRST.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: '2014-12-31',
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'MIXED_FB_FIRST.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '2015-01-01',
|
||||
validTo: null,
|
||||
},
|
||||
// Mixed dated-first then fallback -> excluded
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'MIXED_DATED_FIRST.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '2015-01-01',
|
||||
validTo: null,
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'MIXED_DATED_FIRST.US',
|
||||
listingKey: validKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: DEFAULT_VALID_FROM,
|
||||
validTo: '2014-12-31',
|
||||
},
|
||||
// Dated mapping whose listing is skipped (missing_listing) -> excluded
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'SKIPPED_LISTING.US',
|
||||
listingKey: missingKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '2018-01-01',
|
||||
validTo: null,
|
||||
}
|
||||
);
|
||||
|
||||
const { client, queries } = createMockClient((text, values) => {
|
||||
if (text.startsWith('SELECT mic FROM exchange')) {
|
||||
return { rows: [{ mic: 'XNAS' }] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument (')) {
|
||||
return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
||||
const ids = (values?.[0] as number[]) ?? [];
|
||||
return { rows: ids.map(() => ({ inserted: 1 })) };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO listing (')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
listing_id: 10,
|
||||
instrument_id: 1,
|
||||
mic: 'XNAS',
|
||||
ticker_root: 'AAPL',
|
||||
class_suffix: '',
|
||||
currency: 'USD',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (text.includes('INTO listing_symbol_history')) {
|
||||
return { rows: [{ inserted_count: 1, updated_count: 0 }] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO provider_mapping')) {
|
||||
const sources = (values?.[0] as string[]) ?? [];
|
||||
const sourceIds = (values?.[1] as string[]) ?? [];
|
||||
const validFroms = (values?.[2] as string[]) ?? [];
|
||||
return {
|
||||
rows: sources.map((source, i) => ({
|
||||
source,
|
||||
source_id: sourceIds[i],
|
||||
valid_from: validFroms[i],
|
||||
inserted: true,
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (text.includes('DELETE FROM provider_mapping')) {
|
||||
return { rows: [{ deleted_count: 2 }] };
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
const result = await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
});
|
||||
|
||||
const deleteQueries = queries.filter(q => q.text.includes('DELETE FROM provider_mapping'));
|
||||
expect(deleteQueries).toHaveLength(1);
|
||||
const dq = deleteQueries[0]!;
|
||||
expect(dq.text).toContain("pm.method <> 'override'");
|
||||
expect(dq.text).toContain('NOT EXISTS');
|
||||
expect(dq.text).toContain('FROM override o');
|
||||
expect(dq.text).not.toContain(hostileSourceId);
|
||||
expect(dq.values).toEqual([
|
||||
['eod', 'qm'],
|
||||
['DATED_MULTI.US', hostileSourceId],
|
||||
DEFAULT_VALID_FROM,
|
||||
]);
|
||||
|
||||
expect(result.providerMappingsDeletedStaleFallback).toBe(2);
|
||||
expect(result.providerMappingsInserted).toBe(9);
|
||||
expect(result.providerMappingsUpdated).toBe(0);
|
||||
expect(result.providerMappingsUnchanged).toBe(0);
|
||||
expect(result.providerMappingsSkipped).toBe(1);
|
||||
});
|
||||
|
||||
test('batches stale-fallback deletes by chunkSize and sums counts independently of upsert totals', async () => {
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc.',
|
||||
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
const key = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const stageB = emptyStageB();
|
||||
stageB.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: '2012-05-18',
|
||||
listedTo: null,
|
||||
});
|
||||
for (let i = 0; i < 5; i++) {
|
||||
stageB.providerMappings.push({
|
||||
source: 'eod',
|
||||
sourceId: `S${i}.US`,
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '2012-05-18',
|
||||
validTo: null,
|
||||
});
|
||||
}
|
||||
|
||||
const chunkDeleteCounts = [1, 2, 0];
|
||||
let deleteChunkIdx = 0;
|
||||
const { client, queries } = createMockClient((text, values) => {
|
||||
if (text.startsWith('SELECT mic FROM exchange')) {
|
||||
return { rows: [{ mic: 'XNAS' }] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument (')) {
|
||||
return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
||||
const ids = (values?.[0] as number[]) ?? [];
|
||||
return { rows: ids.map(() => ({ inserted: 1 })) };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO listing (')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
listing_id: 10,
|
||||
instrument_id: 1,
|
||||
mic: 'XNAS',
|
||||
ticker_root: 'AAPL',
|
||||
class_suffix: '',
|
||||
currency: 'USD',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (text.includes('INTO listing_symbol_history')) {
|
||||
return { rows: [{ inserted_count: 1, updated_count: 0 }] };
|
||||
}
|
||||
if (text.startsWith('INSERT INTO provider_mapping')) {
|
||||
const sources = (values?.[0] as string[]) ?? [];
|
||||
const sourceIds = (values?.[1] as string[]) ?? [];
|
||||
const validFroms = (values?.[2] as string[]) ?? [];
|
||||
return {
|
||||
rows: sources.map((source, i) => ({
|
||||
source,
|
||||
source_id: sourceIds[i],
|
||||
valid_from: validFroms[i],
|
||||
inserted: true,
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (text.includes('DELETE FROM provider_mapping')) {
|
||||
const deleted = chunkDeleteCounts[deleteChunkIdx++] ?? 0;
|
||||
return { rows: [{ deleted_count: deleted }] };
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
const result = await persistSecurityMaster(
|
||||
client,
|
||||
{
|
||||
stageA,
|
||||
stageB,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
},
|
||||
{ chunkSize: 2 }
|
||||
);
|
||||
|
||||
const deleteQueries = queries.filter(q => q.text.includes('DELETE FROM provider_mapping'));
|
||||
expect(deleteQueries).toHaveLength(3);
|
||||
expect(deleteQueries.map(q => (q.values?.[1] as string[]).length)).toEqual([2, 2, 1]);
|
||||
expect(result.providerMappingsDeletedStaleFallback).toBe(3);
|
||||
expect(result.providerMappingsInserted).toBe(5);
|
||||
expect(result.providerMappingsUpdated).toBe(0);
|
||||
expect(result.providerMappingsUnchanged).toBe(0);
|
||||
});
|
||||
|
||||
test('issues zero DELETE queries when no dated-only provider_mapping pairs exist', async () => {
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc.',
|
||||
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
const key = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const stageB = emptyStageB();
|
||||
stageB.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push(
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
},
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'AAPL:US',
|
||||
listingKey: key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: DEFAULT_VALID_FROM,
|
||||
validTo: '2014-12-31',
|
||||
},
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'AAPL:US',
|
||||
listingKey: key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: '2015-01-01',
|
||||
validTo: null,
|
||||
}
|
||||
);
|
||||
|
||||
const { client, queries } = createMockClient();
|
||||
const result = await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
});
|
||||
|
||||
expect(queries.filter(q => q.text.includes('DELETE FROM provider_mapping'))).toHaveLength(0);
|
||||
expect(result.providerMappingsDeletedStaleFallback).toBe(0);
|
||||
expect(result.providerMappingsInserted).toBe(3);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -288,6 +288,7 @@ function makeFakePersistResult(): PersistSecurityMasterResult {
|
|||
providerMappingsUpdated: 0,
|
||||
providerMappingsUnchanged: 0,
|
||||
providerMappingsSkipped: 0,
|
||||
providerMappingsDeletedStaleFallback: 0,
|
||||
overridesApplied: 0,
|
||||
conflictsInserted: 0,
|
||||
conflictsUnchanged: 0,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue