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:
commit
306d324b8d
6 changed files with 4246 additions and 0 deletions
|
|
@ -63,3 +63,20 @@ 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
|
||||
```
|
||||
|
||||
- **Recorded baseline (`2026-11-28`, host PostgreSQL isolated `stock_bot_safety_*` schema, default `chunkSize = 5000`):**
|
||||
- Workload: `20,000` instruments, `20,000` listings, `60,000` provider mappings (`100,000` core rows; `140,000` total rows including `20,000` `instrument_identifier_history` and `20,000` `listing_symbol_history` rows).
|
||||
- Observed end-to-end test wall time: `2.20s` (`2200.02ms`, reported by `bun test`; includes isolated schema migration, synthetic fixture construction, `persistSecurityMaster`, and `COUNT(*)` verification because `test/setup.ts` suppresses `console.info`).
|
||||
- Throughput (conservative lower bound over full test wall time): `45,454` core rows/s (`100,000 / 2.20002s`), `63,636` total rows/s (`140,000 / 2.20002s`).
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
1616
apps/stock/data-pipeline/src/security-master/persist.ts
Normal file
1616
apps/stock/data-pipeline/src/security-master/persist.ts
Normal file
File diff suppressed because it is too large
Load diff
384
test/postgres/security-master-persist-qa.test.ts
Normal file
384
test/postgres/security-master-persist-qa.test.ts
Normal file
|
|
@ -0,0 +1,384 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool, type PoolClient } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import {
|
||||
DEFAULT_OTC_MICS,
|
||||
formatListingNaturalKey,
|
||||
linkDelistingChains,
|
||||
matchInstrumentsStageA,
|
||||
matchListingsStageB,
|
||||
persistSecurityMaster,
|
||||
type SecurityType,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
// QA edge cases for persistSecurityMaster that complement security-master-persist.test.ts:
|
||||
// mutable-field updates on existing rows, re-runs without Pass 6, price_corr retention,
|
||||
// and instruments that become un-persistable after a successful load.
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('security-master-persist-qa-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
|
||||
const cleanup: (() => Promise<void> | void)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function createIsolatedFixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
options: `-c search_path=${schema} -c statement_timeout=15000 -c lock_timeout=15000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({ connect: () => pool.connect() }),
|
||||
});
|
||||
await runPostgresMigrations(postgres, { track: 'master' });
|
||||
return { pool };
|
||||
}
|
||||
|
||||
async function withClient<T>(pool: Pool, fn: (client: PoolClient) => Promise<T>): Promise<T> {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
return await fn(client);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
const AAPL_KEY = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const SIVB_KEY = {
|
||||
primaryIsin: 'US78486Q1013',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'SIVB',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
const SIVBQ_KEY = { ...SIVB_KEY, mic: 'OTCM', tickerRoot: 'SIVBQ' };
|
||||
|
||||
/** AAPL + SIVB->SIVBQ via the real matchers; `aaplLastBar` varies per run. */
|
||||
function buildFixture(opts: { aaplLastBar?: string } = {}) {
|
||||
const stageA = matchInstrumentsStageA([
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'Apple Inc.',
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'SIVB.US',
|
||||
isin: 'US78486Q1013',
|
||||
cusip: '78486Q101',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'SVB Financial Group',
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'SIVBQ.US',
|
||||
isin: 'US78486Q1013',
|
||||
cusip: '78486Q101',
|
||||
country: 'US',
|
||||
currency: 'USD',
|
||||
name: 'SVB Financial Group',
|
||||
},
|
||||
]);
|
||||
const stageB = matchListingsStageB({
|
||||
instruments: stageA.instruments,
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'AAPL.US',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '1980-12-12', lastBarDate: opts.aaplLastBar ?? '2026-11-27' },
|
||||
},
|
||||
{
|
||||
sourceId: 'SIVB.US',
|
||||
ticker: 'SIVB',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '1987-10-26', lastBarDate: '2023-03-10' },
|
||||
},
|
||||
{
|
||||
sourceId: 'SIVBQ.US',
|
||||
ticker: 'SIVBQ',
|
||||
mic: 'OTCM',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2023-03-28', lastBarDate: '2024-11-07' },
|
||||
},
|
||||
],
|
||||
ibContracts: [],
|
||||
tickerSources: [],
|
||||
});
|
||||
const pass6 = linkDelistingChains(
|
||||
{ listings: stageB.listings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2026-11-27' }
|
||||
);
|
||||
const securityTypeByIsin = new Map<string, SecurityType>([
|
||||
['US0378331005', 'common'],
|
||||
['US78486Q1013', 'common'],
|
||||
]);
|
||||
return { stageA, stageB, pass6, securityTypeByIsin };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('persistSecurityMaster PostgreSQL QA edge cases', () => {
|
||||
test('updates changed instrument fields in place, keeps instrument_id, and appends (never replaces) CUSIP history', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const run1 = await withClient(f.pool, c => persistSecurityMaster(c, buildFixture()));
|
||||
const aaplInstrumentId = run1.instrumentIdByIsin.get('US0378331005');
|
||||
const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY));
|
||||
expect(aaplInstrumentId).toBeDefined();
|
||||
|
||||
// Stage A would quarantine an ISIN/CUSIP mismatch, so emulate a corrected upstream CUSIP and
|
||||
// renamed issuer by editing the matcher output directly.
|
||||
const base = buildFixture();
|
||||
const renamed = {
|
||||
...base,
|
||||
stageA: {
|
||||
...base.stageA,
|
||||
instruments: base.stageA.instruments.map(inst =>
|
||||
inst.primaryIsin === 'US0378331005'
|
||||
? { ...inst, primaryCusip: '037833101', canonicalName: 'Apple Incorporated' }
|
||||
: inst
|
||||
),
|
||||
},
|
||||
};
|
||||
const run2 = await withClient(f.pool, c => persistSecurityMaster(c, renamed));
|
||||
|
||||
expect(run2.instrumentsInserted).toBe(0);
|
||||
expect(run2.instrumentsUpdated).toBe(1);
|
||||
expect(run2.instrumentsUnchanged).toBe(1);
|
||||
expect(run2.identifierHistoryInserted).toBe(1); // new CUSIP only
|
||||
expect(run2.instrumentIdByIsin.get('US0378331005')).toBe(aaplInstrumentId!);
|
||||
expect(run2.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))).toBe(aaplListingId!);
|
||||
|
||||
const inst = (
|
||||
await f.pool.query<{ instrument_id: number; primary_cusip: string; canonical_name: string }>(
|
||||
`SELECT instrument_id, btrim(primary_cusip) AS primary_cusip, canonical_name
|
||||
FROM instrument WHERE primary_isin = 'US0378331005'`
|
||||
)
|
||||
).rows;
|
||||
expect(inst).toEqual([
|
||||
{ instrument_id: aaplInstrumentId!, primary_cusip: '037833101', canonical_name: 'Apple Incorporated' },
|
||||
]);
|
||||
|
||||
const history = (
|
||||
await f.pool.query<{ id_type: string; id_value: string }>(
|
||||
`SELECT id_type, id_value FROM instrument_identifier_history
|
||||
WHERE instrument_id = $1 ORDER BY id_type, id_value`,
|
||||
[aaplInstrumentId]
|
||||
)
|
||||
).rows;
|
||||
expect(history).toEqual([
|
||||
{ id_type: 'CUSIP', id_value: '037833100' },
|
||||
{ id_type: 'CUSIP', id_value: '037833101' },
|
||||
{ id_type: 'ISIN', id_value: 'US0378331005' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('extending listed_to updates the listing and its single symbol-history row in place', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const run1 = await withClient(f.pool, c => persistSecurityMaster(c, buildFixture()));
|
||||
const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))!;
|
||||
|
||||
const run2 = await withClient(f.pool, c =>
|
||||
persistSecurityMaster(c, buildFixture({ aaplLastBar: '2026-12-31' }))
|
||||
);
|
||||
expect(run2.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))).toBe(aaplListingId);
|
||||
expect(run2.listingsInserted).toBe(0);
|
||||
expect(run2.listingsUpdated).toBe(1);
|
||||
expect(run2.listingsUnchanged).toBe(2);
|
||||
expect(run2.listingSymbolHistoryInserted).toBe(0);
|
||||
expect(run2.listingSymbolHistoryUpdated).toBe(1);
|
||||
expect(run2.listingSymbolHistoryUnchanged).toBe(2);
|
||||
|
||||
const listing = (
|
||||
await f.pool.query<{ listed_to: string }>(
|
||||
`SELECT to_char(listed_to, 'YYYY-MM-DD') AS listed_to FROM listing WHERE listing_id = $1`,
|
||||
[aaplListingId]
|
||||
)
|
||||
).rows;
|
||||
expect(listing).toEqual([{ listed_to: '2026-12-31' }]);
|
||||
|
||||
const symbols = (
|
||||
await f.pool.query<{ ticker: string; valid_from: string; valid_to: string | null }>(
|
||||
`SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
||||
to_char(valid_to, 'YYYY-MM-DD') AS valid_to
|
||||
FROM listing_symbol_history WHERE listing_id = $1`,
|
||||
[aaplListingId]
|
||||
)
|
||||
).rows;
|
||||
expect(symbols).toEqual([{ ticker: 'AAPL', valid_from: '1980-12-12', valid_to: '2026-12-31' }]);
|
||||
});
|
||||
|
||||
test('a re-run without pass6 leaves delist_reason, terminal_return and continuities untouched', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const full = buildFixture();
|
||||
const run1 = await withClient(f.pool, c => persistSecurityMaster(c, full));
|
||||
expect(run1.continuitiesInserted).toBe(1);
|
||||
|
||||
const snapshot = async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
`SELECT listing_id, delist_reason, terminal_return::text AS terminal_return
|
||||
FROM listing ORDER BY listing_id`
|
||||
)
|
||||
).rows;
|
||||
const before = await snapshot();
|
||||
const continuityBefore = (await f.pool.query('SELECT * FROM corporate_action_continuity')).rows;
|
||||
|
||||
const run2 = await withClient(f.pool, c =>
|
||||
persistSecurityMaster(c, {
|
||||
stageA: full.stageA,
|
||||
stageB: full.stageB,
|
||||
securityTypeByIsin: full.securityTypeByIsin,
|
||||
})
|
||||
);
|
||||
|
||||
expect(run2.listingsUpdated).toBe(0);
|
||||
expect(run2.listingsUnchanged).toBe(3);
|
||||
expect(run2.pass6OutcomesApplied).toBe(0);
|
||||
expect(run2.continuitiesInserted + run2.continuitiesUpdated + run2.continuitiesUnchanged).toBe(0);
|
||||
expect(await snapshot()).toEqual(before);
|
||||
expect((await f.pool.query('SELECT * FROM corporate_action_continuity')).rows).toEqual(
|
||||
continuityBefore
|
||||
);
|
||||
|
||||
const sivbId = run2.listingIdByKey.get(formatListingNaturalKey(SIVB_KEY));
|
||||
const sivbRow = before.find(r => r.listing_id === sivbId);
|
||||
expect(sivbRow?.delist_reason).toBe('moved_to_otc');
|
||||
expect(run2.listingIdByKey.get(formatListingNaturalKey(SIVBQ_KEY))).toBeDefined();
|
||||
});
|
||||
|
||||
test('keeps price_corr when a matcher update keeps the same listing and clears it when the listing changes', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const base = buildFixture();
|
||||
const run1 = await withClient(f.pool, c => persistSecurityMaster(c, base));
|
||||
const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))!;
|
||||
const sivbListingId = run1.listingIdByKey.get(formatListingNaturalKey(SIVB_KEY))!;
|
||||
|
||||
const aaplMapping = base.stageB.providerMappings.find(m => m.sourceId === 'AAPL.US');
|
||||
expect(aaplMapping).toBeDefined();
|
||||
const validFrom = aaplMapping!.validFrom ?? '1900-01-01';
|
||||
await f.pool.query(
|
||||
`UPDATE provider_mapping SET price_corr = 0.9876
|
||||
WHERE source = 'eod' AND source_id = 'AAPL.US' AND valid_from = $1::date`,
|
||||
[validFrom]
|
||||
);
|
||||
|
||||
const readMapping = async () =>
|
||||
(
|
||||
await f.pool.query<{ listing_id: number; valid_to: string | null; price_corr: string | null }>(
|
||||
`SELECT listing_id, to_char(valid_to, 'YYYY-MM-DD') AS valid_to, price_corr::text AS price_corr
|
||||
FROM provider_mapping
|
||||
WHERE source = 'eod' AND source_id = 'AAPL.US' AND valid_from = $1::date`,
|
||||
[validFrom]
|
||||
)
|
||||
).rows;
|
||||
|
||||
// Same listing, new valid_to -> updated, price_corr retained.
|
||||
const withNewValidTo = {
|
||||
...base,
|
||||
stageB: {
|
||||
...base.stageB,
|
||||
providerMappings: base.stageB.providerMappings.map(m =>
|
||||
m === aaplMapping ? { ...m, validTo: '2030-01-01' } : m
|
||||
),
|
||||
},
|
||||
};
|
||||
const run2 = await withClient(f.pool, c => persistSecurityMaster(c, withNewValidTo));
|
||||
expect(run2.providerMappingsUpdated).toBe(1);
|
||||
expect(await readMapping()).toEqual([
|
||||
{ listing_id: aaplListingId, valid_to: '2030-01-01', price_corr: '0.9876' },
|
||||
]);
|
||||
|
||||
// Redirected to a different listing -> price_corr must not carry over.
|
||||
const redirected = {
|
||||
...base,
|
||||
stageB: {
|
||||
...base.stageB,
|
||||
providerMappings: base.stageB.providerMappings.map(m =>
|
||||
m === aaplMapping ? { ...m, validTo: '2030-01-01', listingKey: SIVB_KEY } : m
|
||||
),
|
||||
},
|
||||
};
|
||||
const run3 = await withClient(f.pool, c => persistSecurityMaster(c, redirected));
|
||||
expect(run3.providerMappingsUpdated).toBe(1);
|
||||
expect(await readMapping()).toEqual([
|
||||
{ listing_id: sivbListingId, valid_to: '2030-01-01', price_corr: null },
|
||||
]);
|
||||
});
|
||||
|
||||
test('an instrument that loses its security type on a later run is skipped without deleting or altering persisted rows', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const base = buildFixture();
|
||||
await withClient(f.pool, c => persistSecurityMaster(c, base));
|
||||
|
||||
const dump = async () => {
|
||||
const out: Record<string, unknown[]> = {};
|
||||
for (const [table, order] of [
|
||||
['instrument', 'instrument_id'],
|
||||
['instrument_identifier_history', 'id_type, id_value'],
|
||||
['listing', 'listing_id'],
|
||||
['listing_symbol_history', 'listing_id, ticker, valid_from'],
|
||||
['provider_mapping', 'source, source_id, valid_from'],
|
||||
['corporate_action_continuity', 'from_listing_id, effective_date'],
|
||||
] as const) {
|
||||
out[table] = (await f.pool.query(`SELECT * FROM ${table} ORDER BY ${order}`)).rows;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const before = await dump();
|
||||
|
||||
const run2 = await withClient(f.pool, c =>
|
||||
persistSecurityMaster(c, {
|
||||
...base,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
})
|
||||
);
|
||||
|
||||
expect(run2.instrumentsSkipped).toBe(1);
|
||||
expect(run2.skippedByReason.instruments.missing_security_type).toBe(1);
|
||||
expect(run2.skippedByReason.listings.skipped_instrument).toBe(2);
|
||||
expect(run2.pass6OutcomesSkipped).toBe(2); // SIVB + SIVBQ
|
||||
expect(run2.skippedByReason.continuities.missing_both_listings).toBe(1);
|
||||
expect(run2.instrumentIdByIsin.has('US78486Q1013')).toBe(false);
|
||||
expect(run2.instrumentsInserted + run2.instrumentsUpdated).toBe(0);
|
||||
expect(run2.listingsInserted + run2.listingsUpdated).toBe(0);
|
||||
expect(run2.providerMappingsInserted + run2.providerMappingsUpdated).toBe(0);
|
||||
expect(await dump()).toEqual(before);
|
||||
});
|
||||
});
|
||||
1405
test/postgres/security-master-persist.test.ts
Normal file
1405
test/postgres/security-master-persist.test.ts
Normal file
File diff suppressed because it is too large
Load diff
804
test/unit/security-master-persist.test.ts
Normal file
804
test/unit/security-master-persist.test.ts
Normal file
|
|
@ -0,0 +1,804 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalizeJsonValue,
|
||||
DEFAULT_VALID_FROM,
|
||||
formatListingNaturalKey,
|
||||
MAX_PERSIST_CHUNK_SIZE,
|
||||
persistSecurityMaster,
|
||||
PROVIDER_MAPPING_CONFIDENCE,
|
||||
SECURITY_MASTER_PERSIST_LOCK_NAMESPACE,
|
||||
stableJsonStringify,
|
||||
type DelistingChainResult,
|
||||
type PersistSecurityMasterInput,
|
||||
type SecurityMasterQueryable,
|
||||
type SecurityMasterQueryResult,
|
||||
type SecurityType,
|
||||
type StageAMatchResult,
|
||||
type StageBMatchResult,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
interface RecordedQuery {
|
||||
text: string;
|
||||
values: readonly unknown[] | undefined;
|
||||
}
|
||||
|
||||
function emptyStageA(): StageAMatchResult {
|
||||
return {
|
||||
instruments: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalInputRecords: 0,
|
||||
totalInstruments: 0,
|
||||
bySource: {
|
||||
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function emptyStageB(): StageBMatchResult {
|
||||
return {
|
||||
listings: [],
|
||||
providerMappings: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalListings: 0,
|
||||
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 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createMockClient(
|
||||
handler?: (
|
||||
text: string,
|
||||
values: readonly unknown[] | undefined,
|
||||
index: number
|
||||
) => SecurityMasterQueryResult | Promise<SecurityMasterQueryResult>
|
||||
): { client: SecurityMasterQueryable; queries: RecordedQuery[] } {
|
||||
const queries: RecordedQuery[] = [];
|
||||
let nextInstrumentId = 100;
|
||||
let nextListingId = 1000;
|
||||
|
||||
const client: SecurityMasterQueryable = {
|
||||
release: () => undefined,
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
const index = queries.length;
|
||||
queries.push({ text, values });
|
||||
if (handler) {
|
||||
return (await handler(text, values, index)) as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
|
||||
if (text.startsWith('SELECT mic FROM exchange')) {
|
||||
return {
|
||||
rows: [{ mic: 'XNAS' }, { mic: 'XNYS' }, { mic: 'XTSE' }, { mic: 'OTCM' }],
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument (')) {
|
||||
const isins = (values?.[0] as string[]) ?? [];
|
||||
return {
|
||||
rows: isins.map(isin => ({
|
||||
instrument_id: nextInstrumentId++,
|
||||
primary_isin: isin,
|
||||
})),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
||||
const ids = (values?.[0] as number[]) ?? [];
|
||||
return {
|
||||
rows: ids.map(() => ({ inserted: 1 })),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO listing (')) {
|
||||
const instrumentIds = (values?.[0] as number[]) ?? [];
|
||||
const mics = (values?.[1] as string[]) ?? [];
|
||||
const roots = (values?.[2] as string[]) ?? [];
|
||||
const suffixes = (values?.[3] as string[]) ?? [];
|
||||
const currencies = (values?.[4] as string[]) ?? [];
|
||||
return {
|
||||
rows: instrumentIds.map((instrumentId, i) => ({
|
||||
listing_id: nextListingId++,
|
||||
instrument_id: instrumentId,
|
||||
mic: mics[i],
|
||||
ticker_root: roots[i],
|
||||
class_suffix: suffixes[i],
|
||||
currency: currencies[i],
|
||||
})),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.includes('INTO listing_symbol_history')) {
|
||||
const firstCol = (values?.[0] as unknown[]) ?? [];
|
||||
return {
|
||||
rows: [{ inserted_count: firstCol.length, updated_count: 0 }],
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
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,
|
||||
})),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO corporate_action_continuity')) {
|
||||
const firstCol = (values?.[0] as unknown[]) ?? [];
|
||||
return {
|
||||
rows: firstCol.map(() => ({ inserted: true })),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.includes('WITH enforced AS')) {
|
||||
return {
|
||||
rows: [],
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
return { rows: [] } as SecurityMasterQueryResult<Row>;
|
||||
},
|
||||
};
|
||||
|
||||
return { client, queries };
|
||||
}
|
||||
|
||||
describe('persistSecurityMaster unit tests', () => {
|
||||
test('rejects a pg.Pool-shaped object and non-queryable inputs', async () => {
|
||||
const fakePool = {
|
||||
totalCount: 1,
|
||||
idleCount: 1,
|
||||
waitingCount: 0,
|
||||
query: async () => ({ rows: [] }),
|
||||
} as unknown as SecurityMasterQueryable;
|
||||
|
||||
const emptyInput: PersistSecurityMasterInput = {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
};
|
||||
|
||||
await expect(persistSecurityMaster(fakePool, emptyInput)).rejects.toThrow(/PoolClient/);
|
||||
await expect(
|
||||
persistSecurityMaster(null as unknown as SecurityMasterQueryable, emptyInput)
|
||||
).rejects.toThrow(/query\(\)/);
|
||||
});
|
||||
|
||||
test('validates chunkSize bounds', async () => {
|
||||
const { client } = createMockClient();
|
||||
const emptyInput: PersistSecurityMasterInput = {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
};
|
||||
|
||||
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 0 })).rejects.toThrow(
|
||||
RangeError
|
||||
);
|
||||
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: -5 })).rejects.toThrow(
|
||||
RangeError
|
||||
);
|
||||
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 1.5 })).rejects.toThrow(
|
||||
RangeError
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, emptyInput, { chunkSize: MAX_PERSIST_CHUNK_SIZE + 1 })
|
||||
).rejects.toThrow(RangeError);
|
||||
});
|
||||
|
||||
test('empty input fast path runs only BEGIN, advisory lock, override CTE, and COMMIT', async () => {
|
||||
const { client, queries } = createMockClient();
|
||||
const result = await persistSecurityMaster(client, {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
});
|
||||
|
||||
expect(queries.map(q => q.text.trim().split('\n')[0])).toEqual([
|
||||
'BEGIN',
|
||||
'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))',
|
||||
'WITH enforced AS (',
|
||||
'COMMIT',
|
||||
]);
|
||||
expect(queries[1]?.values).toEqual([SECURITY_MASTER_PERSIST_LOCK_NAMESPACE]);
|
||||
expect(result.instrumentsInserted).toBe(0);
|
||||
expect(result.listingsInserted).toBe(0);
|
||||
expect(result.providerMappingsInserted).toBe(0);
|
||||
expect(result.overridesApplied).toBe(0);
|
||||
});
|
||||
|
||||
test('parameterizes all SQL values and never interpolates untrusted strings into SQL text', async () => {
|
||||
const { client, queries } = createMockClient();
|
||||
const hostileName = "O'Brien Corp; DROP TABLE instrument; --";
|
||||
const hostileSourceId = "BAD'ID;DELETE";
|
||||
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: hostileName,
|
||||
members: [{ source: 'ib', sourceId: hostileSourceId, currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
stageA.conflicts.push({
|
||||
source: 'eod',
|
||||
sourceId: hostileSourceId,
|
||||
conflictKind: 'isin_cusip_mismatch',
|
||||
detail: {
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
derivedIsin: null,
|
||||
},
|
||||
});
|
||||
|
||||
const stageB = emptyStageB();
|
||||
const key = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
stageB.listings.push({
|
||||
...key,
|
||||
ibConid: 265598,
|
||||
ibPrimaryExchange: 'NASDAQ',
|
||||
listedFrom: '1980-12-12',
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push({
|
||||
source: 'ib',
|
||||
sourceId: hostileSourceId,
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
});
|
||||
|
||||
await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
});
|
||||
|
||||
for (const q of queries) {
|
||||
expect(q.text).not.toContain(hostileName);
|
||||
expect(q.text).not.toContain(hostileSourceId);
|
||||
expect(q.text).not.toContain('US0378331005');
|
||||
}
|
||||
|
||||
const mappingInsert = queries.find(q => q.text.startsWith('INSERT INTO provider_mapping'));
|
||||
expect(mappingInsert?.values?.[2]).toEqual([DEFAULT_VALID_FROM]);
|
||||
expect(mappingInsert?.values?.[6]).toEqual([
|
||||
PROVIDER_MAPPING_CONFIDENCE.tier1_isin.toFixed(3),
|
||||
]);
|
||||
});
|
||||
|
||||
test('statement count scales with O(ceil(N / chunkSize)) rather than O(N)', async () => {
|
||||
const count = 600;
|
||||
const chunkSize = 200;
|
||||
const stageA = emptyStageA();
|
||||
const stageB = emptyStageB();
|
||||
const securityTypeByIsin = new Map<string, SecurityType>();
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const isin = `US${String(i).padStart(9, '0')}0`;
|
||||
const cusip = String(i).padStart(9, '0');
|
||||
stageA.instruments.push({
|
||||
primaryIsin: isin,
|
||||
primaryCusip: cusip,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: `Corp ${i}`,
|
||||
members: [{ source: 'eod', sourceId: `T${i}.US`, currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
securityTypeByIsin.set(isin, 'common');
|
||||
const key = {
|
||||
primaryIsin: isin,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: `T${i}`,
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
stageB.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: '2020-01-01',
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push({
|
||||
source: 'eod',
|
||||
sourceId: `T${i}.US`,
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
});
|
||||
stageB.providerMappings.push({
|
||||
source: 'qm',
|
||||
sourceId: `T${i}:US`,
|
||||
listingKey: key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: '2020-01-01',
|
||||
validTo: null,
|
||||
});
|
||||
}
|
||||
|
||||
const { client, queries } = createMockClient();
|
||||
const result = await persistSecurityMaster(
|
||||
client,
|
||||
{ stageA, stageB, securityTypeByIsin },
|
||||
{ chunkSize }
|
||||
);
|
||||
|
||||
expect(result.instrumentsInserted).toBe(count);
|
||||
expect(result.listingsInserted).toBe(count);
|
||||
expect(result.providerMappingsInserted).toBe(count * 2);
|
||||
// 3 chunks for instruments (select+insert), 6 for id_history (ISIN+CUSIP),
|
||||
// 1 exchange select, 3+3+3 for listings (select+insert+symbol_history),
|
||||
// 6 for provider_mapping, plus BEGIN/lock/override/COMMIT = 31 queries total << 600 rows.
|
||||
expect(queries.length).toBeLessThan(40);
|
||||
});
|
||||
|
||||
test('canonicalizes JSONB keys deterministically regardless of property insertion order', () => {
|
||||
const a = { z: 1, a: { d: 2, b: [3, undefined, { y: true, x: false }] }, dropMe: undefined };
|
||||
const b = { a: { b: [3, null, { x: false, y: true }], d: 2 }, z: 1 };
|
||||
|
||||
expect(stableJsonStringify(a)).toBe(stableJsonStringify(b));
|
||||
expect(canonicalizeJsonValue(Number.NaN)).toBeNull();
|
||||
});
|
||||
|
||||
test('selects best member source for instrument_identifier_history (tier1_isin > tier2_cusip, ib > eod)', async () => {
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push(
|
||||
{
|
||||
primaryIsin: 'US0000000010',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Tier1 IB wins over EOD',
|
||||
members: [
|
||||
{ source: 'eod', sourceId: 'A.US', currency: 'USD', method: 'tier1_isin' },
|
||||
{ source: 'ib', sourceId: '1', currency: 'USD', method: 'tier1_isin' },
|
||||
],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US0000000020',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Tier1 EOD wins over Tier2 IB',
|
||||
members: [
|
||||
{ source: 'ib', sourceId: '2', currency: 'USD', method: 'tier2_cusip' },
|
||||
{ source: 'eod', sourceId: 'B.US', currency: 'USD', method: 'tier1_isin' },
|
||||
],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US0000000030',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Empty members falls back to eod',
|
||||
members: [],
|
||||
}
|
||||
);
|
||||
|
||||
const { client, queries } = createMockClient();
|
||||
await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map<string, SecurityType>([
|
||||
['US0000000010', 'common'],
|
||||
['US0000000020', 'common'],
|
||||
['US0000000030', 'common'],
|
||||
]),
|
||||
});
|
||||
|
||||
const idHistoryQuery = queries.find(q =>
|
||||
q.text.startsWith('INSERT INTO instrument_identifier_history')
|
||||
);
|
||||
expect(idHistoryQuery?.values?.[4]).toEqual(['ib', 'eod', 'eod']);
|
||||
});
|
||||
|
||||
test('rejects duplicate input natural keys and duplicate DB listing rows', async () => {
|
||||
const { client } = createMockClient();
|
||||
|
||||
// 1. Duplicate primaryIsin
|
||||
const dupIsin = emptyStageA();
|
||||
dupIsin.instruments.push(
|
||||
{
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple',
|
||||
members: [],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Dup',
|
||||
members: [],
|
||||
}
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA: dupIsin,
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate primaryIsin/);
|
||||
|
||||
// 2. Duplicate listing natural key
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple',
|
||||
members: [],
|
||||
});
|
||||
const dupListing = emptyStageB();
|
||||
const key = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
dupListing.listings.push(
|
||||
{ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null },
|
||||
{ ...key, ibConid: 1, ibPrimaryExchange: 'NASDAQ', listedFrom: null, listedTo: null }
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: dupListing,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate listing natural key/);
|
||||
|
||||
// 3. Duplicate provider_mapping PK
|
||||
const dupMapping = emptyStageB();
|
||||
dupMapping.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
});
|
||||
dupMapping.providerMappings.push(
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: DEFAULT_VALID_FROM,
|
||||
validTo: null,
|
||||
}
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: dupMapping,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate provider_mapping primary key/);
|
||||
|
||||
// 4. Duplicate Pass 6 listing outcome
|
||||
const dupPass6: DelistingChainResult = {
|
||||
continuities: [],
|
||||
listingOutcomes: [
|
||||
{ listingKey: key, delistReason: 'active', terminalReturn: null },
|
||||
{ listingKey: key, delistReason: 'unknown_involuntary', terminalReturn: -0.3 },
|
||||
],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalInputListings: 1,
|
||||
processedListings: 1,
|
||||
skippedMalformedEntries: 0,
|
||||
skippedInvalidDates: 0,
|
||||
skippedDuplicateKeys: 0,
|
||||
continuitiesCreated: 0,
|
||||
conflictsDetected: 0,
|
||||
byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 0 },
|
||||
},
|
||||
};
|
||||
const singleStageB = emptyStageB();
|
||||
singleStageB.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
});
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: singleStageB,
|
||||
pass6: dupPass6,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate listing outcome key/);
|
||||
|
||||
// 5. Duplicate existing DB listing rows for incoming natural key
|
||||
const { client: dupDbClient, queries: dupDbQueries } = createMockClient(text => {
|
||||
if (text.startsWith('SELECT') && text.includes('FROM instrument')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
instrument_id: 7,
|
||||
primary_isin: 'US0378331005',
|
||||
primary_cusip: '037833100',
|
||||
canonical_name: 'Apple',
|
||||
security_type: 'common',
|
||||
issuer_country: 'US',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (text.startsWith('SELECT mic FROM exchange')) {
|
||||
return { rows: [{ mic: 'XNAS' }] };
|
||||
}
|
||||
if (text.startsWith('SELECT') && text.includes('FROM listing')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
listing_id: 1,
|
||||
instrument_id: 7,
|
||||
mic: 'XNAS',
|
||||
ticker_root: 'AAPL',
|
||||
class_suffix: '',
|
||||
currency: 'USD',
|
||||
ib_conid: null,
|
||||
ib_primary_exchange: null,
|
||||
listed_from: null,
|
||||
listed_to: null,
|
||||
delist_reason: null,
|
||||
terminal_return: null,
|
||||
},
|
||||
{
|
||||
listing_id: 2,
|
||||
instrument_id: 7,
|
||||
mic: 'XNAS',
|
||||
ticker_root: 'AAPL',
|
||||
class_suffix: '',
|
||||
currency: 'USD',
|
||||
ib_conid: null,
|
||||
ib_primary_exchange: null,
|
||||
listed_from: '2020-01-01',
|
||||
listed_to: null,
|
||||
delist_reason: null,
|
||||
terminal_return: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
await expect(
|
||||
persistSecurityMaster(dupDbClient, {
|
||||
stageA,
|
||||
stageB: singleStageB,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/duplicate rows for natural key/);
|
||||
expect(dupDbQueries.at(-1)?.text).toBe('ROLLBACK');
|
||||
});
|
||||
|
||||
test('executes ROLLBACK and rethrows original error on mid-run failure (even if ROLLBACK fails)', async () => {
|
||||
const boom = new Error('injected check violation');
|
||||
const { client, queries } = createMockClient(text => {
|
||||
if (text.startsWith('INSERT INTO instrument (')) {
|
||||
throw boom;
|
||||
}
|
||||
if (text === 'ROLLBACK') {
|
||||
throw new Error('rollback also failed');
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc.',
|
||||
members: [],
|
||||
});
|
||||
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toBe(boom);
|
||||
|
||||
expect(queries.some(q => q.text === 'BEGIN')).toBe(true);
|
||||
expect(queries.some(q => q.text === 'ROLLBACK')).toBe(true);
|
||||
expect(queries.some(q => q.text === 'COMMIT')).toBe(false);
|
||||
expect(formatListingNaturalKey({
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
})).toBe('US0378331005\u0000XNAS\u0000AAPL\u0000\u0000USD');
|
||||
});
|
||||
|
||||
test('rejects overlapping calls on the same client before issuing BEGIN and allows sequential reuse', async () => {
|
||||
let releaseFirstBegin!: () => void;
|
||||
const firstBeginPaused = new Promise<void>(resolve => {
|
||||
releaseFirstBegin = resolve;
|
||||
});
|
||||
let beginCount = 0;
|
||||
|
||||
const { client, queries } = createMockClient(async text => {
|
||||
if (text === 'BEGIN') {
|
||||
beginCount += 1;
|
||||
if (beginCount === 1) {
|
||||
await firstBeginPaused;
|
||||
}
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
const emptyInput: PersistSecurityMasterInput = {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
};
|
||||
|
||||
const firstCall = persistSecurityMaster(client, emptyInput);
|
||||
const secondCall = persistSecurityMaster(client, emptyInput);
|
||||
|
||||
await expect(secondCall).rejects.toThrow(/overlapping calls on the same client/);
|
||||
// Second call must reject before issuing a second BEGIN.
|
||||
expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(1);
|
||||
|
||||
releaseFirstBegin();
|
||||
const firstResult = await firstCall;
|
||||
expect(firstResult.instrumentsInserted).toBe(0);
|
||||
|
||||
// Once the first call completes, sequential reuse of the same client succeeds.
|
||||
const thirdResult = await persistSecurityMaster(client, emptyInput);
|
||||
expect(thirdResult.instrumentsInserted).toBe(0);
|
||||
expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('counts each provider_mapping key once across matcher and override outcomes', 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: '1980-12-12',
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push(
|
||||
// Existing row skipped by matcher because override exists, then updated by override
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '1980-12-12',
|
||||
validTo: null,
|
||||
},
|
||||
// Fresh row inserted by matcher, then immediately updated by override -> net outcome: inserted
|
||||
{
|
||||
source: 'ib',
|
||||
sourceId: '265598',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: '1980-12-12',
|
||||
validTo: null,
|
||||
},
|
||||
// Existing row unchanged by matcher and not in override -> unchanged
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'AAPL:US',
|
||||
listingKey: key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: '2010-01-04',
|
||||
validTo: null,
|
||||
}
|
||||
);
|
||||
|
||||
const { client } = 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')) {
|
||||
// Only the fresh ib row is inserted by matcher; eod is skipped by override guard; qm unchanged.
|
||||
return {
|
||||
rows: [
|
||||
{ source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: true },
|
||||
],
|
||||
};
|
||||
}
|
||||
if (text.includes('WITH enforced AS')) {
|
||||
return {
|
||||
rows: [
|
||||
{ source: 'eod', source_id: 'AAPL.US', valid_from: '1980-12-12', inserted: false },
|
||||
{ source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: false },
|
||||
{ source: 'qm', source_id: 'OVR_NEW:US', valid_from: '2021-01-01', inserted: true },
|
||||
{ source: 'qm', source_id: 'OVR_SAME:US', valid_from: '2021-01-01', inserted: null },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
const result = await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
});
|
||||
|
||||
expect(result.overridesApplied).toBe(4);
|
||||
expect(result.providerMappingsInserted).toBe(2); // ib (fresh+overridden) + OVR_NEW
|
||||
expect(result.providerMappingsUpdated).toBe(1); // eod (existing+overridden)
|
||||
expect(result.providerMappingsUnchanged).toBe(2); // qm AAPL:US + OVR_SAME
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue