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:
parent
d68577843e
commit
3ca206150e
3 changed files with 680 additions and 80 deletions
|
|
@ -718,6 +718,8 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
|
|||
);
|
||||
expect(runWithOverrides.overridesApplied).toBe(2);
|
||||
expect(runWithOverrides.providerMappingsInserted).toBe(1); // the override-only mapping
|
||||
expect(runWithOverrides.providerMappingsUpdated).toBe(1); // AAPL.US redirected by override
|
||||
expect(runWithOverrides.providerMappingsUnchanged).toBe(9); // remaining 9 matcher mappings
|
||||
|
||||
const rowsAfterOverride = (
|
||||
await f.pool.query<{
|
||||
|
|
@ -766,6 +768,118 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
|
|||
expect(secondRun.overridesApplied).toBe(2);
|
||||
expect(secondRun.providerMappingsInserted).toBe(0);
|
||||
expect(secondRun.providerMappingsUpdated).toBe(0);
|
||||
expect(secondRun.providerMappingsUnchanged).toBe(11);
|
||||
});
|
||||
|
||||
test('replaces loader-generated listing_symbol_history interval when listed_from changes while preserving unrelated aliases', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const stageA = matchInstrumentsStageA([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Apple Inc.',
|
||||
},
|
||||
]);
|
||||
const aaplKey = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const securityTypeByIsin = new Map<string, SecurityType>([['US0378331005', 'common']]);
|
||||
|
||||
// Load 1: no bar span yet -> listedFrom = null -> symbol history starts at 1900-01-01
|
||||
const stageBNoSpan = matchListingsStageB({
|
||||
instruments: stageA.instruments,
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'AAPL.US',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: null,
|
||||
},
|
||||
],
|
||||
ibContracts: [],
|
||||
tickerSources: [],
|
||||
});
|
||||
|
||||
const run1 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, { stageA, stageB: stageBNoSpan, securityTypeByIsin })
|
||||
);
|
||||
const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(aaplKey))!;
|
||||
expect(run1.listingSymbolHistoryInserted).toBe(1);
|
||||
|
||||
// Seed two unrelated historical aliases on the same listing that must be preserved.
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source)
|
||||
VALUES
|
||||
($1, 'OLDT', DATE '1978-01-01', DATE '1980-12-11', 'eod'),
|
||||
($1, 'AAPL', DATE '1979-06-01', DATE '1980-06-01', 'manual')`,
|
||||
[aaplListingId]
|
||||
);
|
||||
|
||||
// Load 2: actual first bar date is supplied -> listed_from updates from NULL to 1980-12-12
|
||||
const stageBWithSpan = matchListingsStageB({
|
||||
instruments: stageA.instruments,
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'AAPL.US',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '1980-12-12', lastBarDate: '2026-11-27' },
|
||||
},
|
||||
],
|
||||
ibContracts: [],
|
||||
tickerSources: [],
|
||||
});
|
||||
|
||||
const run2 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, { stageA, stageB: stageBWithSpan, securityTypeByIsin })
|
||||
);
|
||||
expect(run2.listingIdByKey.get(formatListingNaturalKey(aaplKey))).toBe(aaplListingId);
|
||||
expect(run2.listingsInserted).toBe(0);
|
||||
expect(run2.listingsUpdated).toBe(1);
|
||||
expect(run2.listingSymbolHistoryInserted).toBe(0);
|
||||
expect(run2.listingSymbolHistoryUpdated).toBe(1);
|
||||
|
||||
const historyRows = (
|
||||
await f.pool.query<{
|
||||
ticker: string;
|
||||
valid_from: string;
|
||||
valid_to: string | null;
|
||||
source: string;
|
||||
}>(
|
||||
`SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
||||
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source
|
||||
FROM listing_symbol_history
|
||||
WHERE listing_id = $1
|
||||
ORDER BY ticker, valid_from, source`,
|
||||
[aaplListingId]
|
||||
)
|
||||
).rows;
|
||||
expect(historyRows).toEqual([
|
||||
{ ticker: 'AAPL', valid_from: '1979-06-01', valid_to: '1980-06-01', source: 'manual' },
|
||||
{ ticker: 'AAPL', valid_from: '1980-12-12', valid_to: '2026-11-27', source: 'eod' },
|
||||
{ ticker: 'OLDT', valid_from: '1978-01-01', valid_to: '1980-12-11', source: 'eod' },
|
||||
]);
|
||||
|
||||
// Load 3: identical re-run is a no-op
|
||||
const run3 = await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, { stageA, stageB: stageBWithSpan, securityTypeByIsin })
|
||||
);
|
||||
expect(run3.listingSymbolHistoryInserted).toBe(0);
|
||||
expect(run3.listingSymbolHistoryUpdated).toBe(0);
|
||||
expect(run3.listingSymbolHistoryUnchanged).toBe(1);
|
||||
});
|
||||
|
||||
test('persists Stage A, Stage B, and Pass 6 conflicts once and never reopens or modifies non-open rows', async () => {
|
||||
|
|
@ -978,23 +1092,237 @@ describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => {
|
|||
expect(result.skippedByReason.continuities.missing_from_listing).toBe(1);
|
||||
});
|
||||
|
||||
test('rolls back all 7 tables atomically on a mid-run CHECK constraint violation', async () => {
|
||||
test('rolls back all 7 tables atomically on a late CHECK constraint violation after earlier phases wrote changes', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const fixture = buildExitCriterionFixture();
|
||||
|
||||
const preCounts = await getSevenTableCounts(f.pool);
|
||||
const badTypes = new Map(fixture.securityTypeByIsin);
|
||||
// Chunk size 2 -> chunk 1 inserts 2 valid instruments, chunk 2 hits Postgres CHECK violation
|
||||
badTypes.set('US78486Q1013', 'bogus_type' as SecurityType);
|
||||
// Seed all 7 tables so both updates to existing rows and new inserts are exercised.
|
||||
await withClient(f.pool, client => persistSecurityMaster(client, fixture));
|
||||
|
||||
const snapshotSevenTables = async () => ({
|
||||
instrument: (
|
||||
await f.pool.query(
|
||||
`SELECT instrument_id, btrim(primary_isin) AS primary_isin, btrim(primary_cusip) AS primary_cusip,
|
||||
canonical_name, security_type, btrim(issuer_country) AS issuer_country
|
||||
FROM instrument ORDER BY instrument_id`
|
||||
)
|
||||
).rows,
|
||||
instrument_identifier_history: (
|
||||
await f.pool.query(
|
||||
`SELECT instrument_id, id_type, id_value, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
||||
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source
|
||||
FROM instrument_identifier_history ORDER BY id_type, id_value, valid_from`
|
||||
)
|
||||
).rows,
|
||||
listing: (
|
||||
await f.pool.query(
|
||||
`SELECT listing_id, instrument_id, mic, ticker_root, class_suffix, btrim(currency) AS currency,
|
||||
ib_conid, ib_primary_exchange, to_char(listed_from, 'YYYY-MM-DD') AS listed_from,
|
||||
to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, terminal_return
|
||||
FROM listing ORDER BY listing_id`
|
||||
)
|
||||
).rows,
|
||||
listing_symbol_history: (
|
||||
await f.pool.query(
|
||||
`SELECT listing_id, ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
||||
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source
|
||||
FROM listing_symbol_history ORDER BY listing_id, ticker, valid_from`
|
||||
)
|
||||
).rows,
|
||||
provider_mapping: (
|
||||
await f.pool.query(
|
||||
`SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
||||
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, method,
|
||||
confidence::text, price_corr::text
|
||||
FROM provider_mapping ORDER BY source, source_id, valid_from`
|
||||
)
|
||||
).rows,
|
||||
resolution_conflict: (
|
||||
await f.pool.query(
|
||||
`SELECT conflict_id, source, source_id, conflict_kind, detail, status
|
||||
FROM resolution_conflict ORDER BY conflict_id`
|
||||
)
|
||||
).rows,
|
||||
corporate_action_continuity: (
|
||||
await f.pool.query(
|
||||
`SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind
|
||||
FROM corporate_action_continuity ORDER BY from_listing_id, effective_date`
|
||||
)
|
||||
).rows,
|
||||
});
|
||||
|
||||
const before = await snapshotSevenTables();
|
||||
|
||||
// Mutate phases 1-6 (update existing instrument/listing, add new instrument/listing/mapping/conflict),
|
||||
// then fail in phase 7 (corporate_action_continuity.kind CHECK constraint).
|
||||
const newIsin = 'US0846707026';
|
||||
const newKey = {
|
||||
primaryIsin: newIsin,
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'BRK',
|
||||
classSuffix: 'B',
|
||||
currency: 'USD',
|
||||
};
|
||||
const mutatedStageA: StageAMatchResult = {
|
||||
...fixture.stageA,
|
||||
instruments: [
|
||||
...fixture.stageA.instruments.map(inst =>
|
||||
inst.primaryIsin === 'US0378331005'
|
||||
? { ...inst, canonicalName: 'Apple Inc. MUTATED' }
|
||||
: inst
|
||||
),
|
||||
{
|
||||
primaryIsin: newIsin,
|
||||
primaryCusip: '084670702',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Berkshire Hathaway Inc.',
|
||||
members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }],
|
||||
},
|
||||
],
|
||||
conflicts: [
|
||||
...fixture.stageA.conflicts,
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'ROLLBACK_TEST.US',
|
||||
conflictKind: 'isin_cusip_mismatch',
|
||||
detail: { isin: newIsin, cusip: '084670702', country: 'US', derivedIsin: null },
|
||||
},
|
||||
],
|
||||
};
|
||||
const mutatedStageB: StageBMatchResult = {
|
||||
...fixture.stageB,
|
||||
listings: [
|
||||
...fixture.stageB.listings.map(l =>
|
||||
l.primaryIsin === 'CA82509L1076' && l.mic === 'XNYS'
|
||||
? { ...l, ibConid: 999999, listedTo: '2026-11-28' }
|
||||
: l
|
||||
),
|
||||
{
|
||||
...newKey,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: '1996-05-09',
|
||||
listedTo: null,
|
||||
},
|
||||
],
|
||||
providerMappings: [
|
||||
...fixture.stageB.providerMappings,
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'BRK-B.US',
|
||||
listingKey: newKey,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
const mutatedPass6: DelistingChainResult = {
|
||||
...fixture.pass6,
|
||||
continuities: [
|
||||
...fixture.pass6.continuities.map(c => ({
|
||||
...c,
|
||||
kind: 'bogus_kind' as typeof c.kind,
|
||||
})),
|
||||
],
|
||||
};
|
||||
const mutatedTypes = new Map(fixture.securityTypeByIsin);
|
||||
mutatedTypes.set(newIsin, 'common');
|
||||
|
||||
await expect(
|
||||
withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, { ...fixture, securityTypeByIsin: badTypes }, { chunkSize: 2 })
|
||||
persistSecurityMaster(client, {
|
||||
stageA: mutatedStageA,
|
||||
stageB: mutatedStageB,
|
||||
pass6: mutatedPass6,
|
||||
securityTypeByIsin: mutatedTypes,
|
||||
})
|
||||
)
|
||||
).rejects.toThrow(/security_type/);
|
||||
).rejects.toThrow(/corporate_action_continuity|kind/);
|
||||
|
||||
const postCounts = await getSevenTableCounts(f.pool);
|
||||
expect(postCounts).toEqual(preCounts);
|
||||
const after = await snapshotSevenTables();
|
||||
expect(after).toEqual(before);
|
||||
});
|
||||
|
||||
test('rejects overlapping calls on one shared PoolClient without creating duplicate listings', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const stageA = matchInstrumentsStageA([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Apple Inc.',
|
||||
},
|
||||
]);
|
||||
const securityTypeByIsin = new Map<string, SecurityType>([['US0378331005', 'common']]);
|
||||
const emptyListingsStageB = matchListingsStageB({
|
||||
instruments: stageA.instruments,
|
||||
eodListings: [],
|
||||
ibContracts: [],
|
||||
tickerSources: [],
|
||||
});
|
||||
const withNewListingStageB = matchListingsStageB({
|
||||
instruments: stageA.instruments,
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'AAPL.US',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '1980-12-12', lastBarDate: '2026-11-27' },
|
||||
},
|
||||
],
|
||||
ibContracts: [],
|
||||
tickerSources: [],
|
||||
});
|
||||
|
||||
// Seed the existing instrument first, then overlap two loads adding the same new listing on one client.
|
||||
await withClient(f.pool, client =>
|
||||
persistSecurityMaster(client, { stageA, stageB: emptyListingsStageB, securityTypeByIsin })
|
||||
);
|
||||
|
||||
const sharedClient = await f.pool.connect();
|
||||
try {
|
||||
const [first, second] = await Promise.allSettled([
|
||||
persistSecurityMaster(sharedClient, {
|
||||
stageA,
|
||||
stageB: withNewListingStageB,
|
||||
securityTypeByIsin,
|
||||
}),
|
||||
persistSecurityMaster(sharedClient, {
|
||||
stageA,
|
||||
stageB: withNewListingStageB,
|
||||
securityTypeByIsin,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(first.status).toBe('fulfilled');
|
||||
expect(second.status).toBe('rejected');
|
||||
if (second.status === 'rejected') {
|
||||
expect(String(second.reason)).toMatch(/overlapping calls on the same client/);
|
||||
}
|
||||
|
||||
const counts = await getSevenTableCounts(f.pool);
|
||||
expect(counts.instrument).toBe(1);
|
||||
expect(counts.listing).toBe(1);
|
||||
expect(counts.provider_mapping).toBe(1);
|
||||
|
||||
// Sequential reuse of the same PoolClient succeeds once the first call has finished.
|
||||
const followUp = await persistSecurityMaster(sharedClient, {
|
||||
stageA,
|
||||
stageB: withNewListingStageB,
|
||||
securityTypeByIsin,
|
||||
});
|
||||
expect(followUp.listingsInserted).toBe(0);
|
||||
expect(followUp.listingsUnchanged).toBe(1);
|
||||
} finally {
|
||||
sharedClient.release();
|
||||
}
|
||||
});
|
||||
|
||||
test('serializes two concurrent writers via pg_advisory_xact_lock without duplicate listings', async () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue