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

@ -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();