T-69: Bug sweep (3 bugs: T-64, T-67, T-71)
This commit is contained in:
parent
2d40d5146a
commit
7f1c9e70ef
4 changed files with 613 additions and 23 deletions
|
|
@ -59,7 +59,8 @@ export type DelistingChainConflictKind =
|
|||
| 'ambiguous_otc_continuation'
|
||||
| 'invalid_listing_dates'
|
||||
| 'duplicate_listing_key'
|
||||
| 'missing_otc_listed_from';
|
||||
| 'missing_otc_listed_from'
|
||||
| 'malformed_listing_entry';
|
||||
|
||||
export interface DelistingChainConflictDetail {
|
||||
primaryIsin: string;
|
||||
|
|
@ -87,6 +88,7 @@ export interface DelistingChainOutcomeStats {
|
|||
export interface DelistingChainStats {
|
||||
totalInputListings: number;
|
||||
processedListings: number;
|
||||
skippedMalformedEntries: number;
|
||||
skippedInvalidDates: number;
|
||||
skippedDuplicateKeys: number;
|
||||
continuitiesCreated: number;
|
||||
|
|
@ -393,18 +395,46 @@ export function linkDelistingChains(
|
|||
const totalInputListings = input.listings.length;
|
||||
|
||||
// Pass 1a: validate container slots and count natural-key occurrences so duplicates are quarantined.
|
||||
const normalizedKeys = new Array<ListingNaturalKey>(totalInputListings);
|
||||
const keyIds = new Array<string>(totalInputListings);
|
||||
const conflicts: DelistingChainConflictRecord[] = [];
|
||||
const normalizedKeys = new Array<ListingNaturalKey | undefined>(totalInputListings);
|
||||
const keyIds = new Array<string | undefined>(totalInputListings);
|
||||
const keyCounts = new Map<string, number>();
|
||||
|
||||
let skippedMalformedEntries = 0;
|
||||
|
||||
for (let i = 0; i < totalInputListings; i++) {
|
||||
let malformedKind: string | null = null;
|
||||
const row = i in input.listings ? input.listings[i] : undefined;
|
||||
if (!(i in input.listings)) {
|
||||
throw new TypeError(`Invalid sparse slot at input.listings[${i}]: expected a listing object`);
|
||||
malformedKind = 'sparse slot';
|
||||
} else if (row === undefined) {
|
||||
malformedKind = 'undefined';
|
||||
} else if (row === null) {
|
||||
malformedKind = 'null';
|
||||
} else if (Array.isArray(row)) {
|
||||
malformedKind = 'array';
|
||||
} else if (typeof row !== 'object') {
|
||||
malformedKind = typeof row;
|
||||
}
|
||||
const row = input.listings[i];
|
||||
if (row === undefined || row === null || typeof row !== 'object') {
|
||||
throw new TypeError(`Invalid listing entry at input.listings[${i}]: expected an object`);
|
||||
|
||||
if (malformedKind !== null || row === undefined) {
|
||||
skippedMalformedEntries += 1;
|
||||
conflicts.push({
|
||||
conflictKind: 'malformed_listing_entry',
|
||||
detail: {
|
||||
primaryIsin: '',
|
||||
currency: '',
|
||||
fromListingKeys: [],
|
||||
toListingKeys: [],
|
||||
candidateListingKeys: [],
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
reason: `Malformed listing entry at input.listings[${i}]: expected a listing object, received ${malformedKind ?? 'undefined'}`,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = normalizeKeyFromListing(row);
|
||||
const keyId = makeListingNaturalKeyId(key);
|
||||
normalizedKeys[i] = key;
|
||||
|
|
@ -412,10 +442,29 @@ export function linkDelistingChains(
|
|||
keyCounts.set(keyId, (keyCounts.get(keyId) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const conflicts: DelistingChainConflictRecord[] = [];
|
||||
const validRows: NormalizedListingRow[] = [];
|
||||
const groups = new Map<string, InstrumentCurrencyGroup>();
|
||||
const reportedDuplicateKeyIds = new Set<string>();
|
||||
const droppedOtcKeysByGroup = new Map<string, Map<string, ListingNaturalKey>>();
|
||||
|
||||
const recordDroppedOtcIfApplicable = (key: ListingNaturalKey, keyId: string): void => {
|
||||
if (
|
||||
!normalizedOtcMics.has(key.mic) ||
|
||||
key.primaryIsin.length === 0 ||
|
||||
key.currency.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const groupKey = makeGroupKey(key.primaryIsin, key.currency);
|
||||
let droppedForGroup = droppedOtcKeysByGroup.get(groupKey);
|
||||
if (droppedForGroup === undefined) {
|
||||
droppedForGroup = new Map<string, ListingNaturalKey>();
|
||||
droppedOtcKeysByGroup.set(groupKey, droppedForGroup);
|
||||
}
|
||||
if (!droppedForGroup.has(keyId)) {
|
||||
droppedForGroup.set(keyId, key);
|
||||
}
|
||||
};
|
||||
|
||||
let skippedDuplicateKeys = 0;
|
||||
let skippedInvalidDates = 0;
|
||||
|
|
@ -432,6 +481,7 @@ export function linkDelistingChains(
|
|||
const occurrences = keyCounts.get(keyId) ?? 0;
|
||||
if (occurrences > 1) {
|
||||
skippedDuplicateKeys += 1;
|
||||
recordDroppedOtcIfApplicable(key, keyId);
|
||||
if (!reportedDuplicateKeyIds.has(keyId)) {
|
||||
reportedDuplicateKeyIds.add(keyId);
|
||||
conflicts.push({
|
||||
|
|
@ -483,6 +533,7 @@ export function linkDelistingChains(
|
|||
|
||||
if (dateErrorReason !== null) {
|
||||
skippedInvalidDates += 1;
|
||||
recordDroppedOtcIfApplicable(key, keyId);
|
||||
conflicts.push({
|
||||
conflictKind: 'invalid_listing_dates',
|
||||
detail: {
|
||||
|
|
@ -549,36 +600,64 @@ export function linkDelistingChains(
|
|||
continue;
|
||||
}
|
||||
|
||||
if (group.missingFromOtcs.length > 0) {
|
||||
const droppedOtcMap = droppedOtcKeysByGroup.get(
|
||||
makeGroupKey(group.primaryIsin, group.currency)
|
||||
);
|
||||
const droppedOtcCount = droppedOtcMap?.size ?? 0;
|
||||
|
||||
if (group.missingFromOtcs.length > 0 || droppedOtcCount > 0) {
|
||||
const sortedPrimaryKeys = group.endedPrimaries
|
||||
.map(p => p.key)
|
||||
.sort(compareListingNaturalKey);
|
||||
const sortedMissingOtcKeys = group.missingFromOtcs
|
||||
.map(o => o.key)
|
||||
.sort(compareListingNaturalKey);
|
||||
const allKeys = [...sortedPrimaryKeys, ...sortedMissingOtcKeys].sort(
|
||||
const blockingOtcKeyMap = new Map<string, ListingNaturalKey>();
|
||||
for (const o of group.missingFromOtcs) {
|
||||
blockingOtcKeyMap.set(makeListingNaturalKeyId(o.key), o.key);
|
||||
}
|
||||
if (droppedOtcMap !== undefined) {
|
||||
for (const [kId, k] of droppedOtcMap) {
|
||||
if (!blockingOtcKeyMap.has(kId)) {
|
||||
blockingOtcKeyMap.set(kId, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
const sortedBlockingOtcKeys = [...blockingOtcKeyMap.values()].sort(compareListingNaturalKey);
|
||||
const allKeys = [...sortedPrimaryKeys, ...sortedBlockingOtcKeys].sort(
|
||||
compareListingNaturalKey
|
||||
);
|
||||
const singleOtc = group.missingFromOtcs.length === 1 ? group.missingFromOtcs[0] : undefined;
|
||||
const singleMissingOnly =
|
||||
group.missingFromOtcs.length === 1 && droppedOtcCount === 0
|
||||
? group.missingFromOtcs[0]
|
||||
: undefined;
|
||||
let reason: string;
|
||||
if (droppedOtcCount === 0) {
|
||||
reason =
|
||||
group.missingFromOtcs.length === 1
|
||||
? 'OTC listing has null listedFrom; cannot establish transfer window or effectiveDate'
|
||||
: `${group.missingFromOtcs.length} OTC listings have null listedFrom; cannot establish transfer window or effectiveDate`;
|
||||
} else if (group.missingFromOtcs.length === 0) {
|
||||
reason =
|
||||
droppedOtcCount === 1
|
||||
? 'OTC listing was dropped due to duplicate key or invalid dates; cannot establish transfer window or effectiveDate'
|
||||
: `${droppedOtcCount} OTC listings were dropped due to duplicate key or invalid dates; cannot establish transfer window or effectiveDate`;
|
||||
} else {
|
||||
reason = `${group.missingFromOtcs.length} undated OTC listing(s) and ${droppedOtcCount} dropped OTC listing(s) in group; cannot establish transfer window or effectiveDate`;
|
||||
}
|
||||
conflicts.push({
|
||||
conflictKind: 'missing_otc_listed_from',
|
||||
detail: {
|
||||
primaryIsin: group.primaryIsin,
|
||||
currency: group.currency,
|
||||
fromListingKeys: sortedPrimaryKeys.map(cloneListingKey),
|
||||
toListingKeys: sortedMissingOtcKeys.map(cloneListingKey),
|
||||
toListingKeys: sortedBlockingOtcKeys.map(cloneListingKey),
|
||||
candidateListingKeys: allKeys.map(cloneListingKey),
|
||||
listedFrom: null,
|
||||
listedTo: singleOtc !== undefined ? singleOtc.listedTo : null,
|
||||
reason:
|
||||
group.missingFromOtcs.length === 1
|
||||
? 'OTC listing has null listedFrom; cannot establish transfer window or effectiveDate'
|
||||
: `${group.missingFromOtcs.length} OTC listings have null listedFrom; cannot establish transfer window or effectiveDate`,
|
||||
listedTo: singleMissingOnly !== undefined ? singleMissingOnly.listedTo : null,
|
||||
reason,
|
||||
},
|
||||
});
|
||||
// Rule 5 ("never guess"): an undated OTC row in the same (primaryIsin, currency) group
|
||||
// could be the true continuation, so suppress all continuity linking for this group
|
||||
// until listedFrom is resolved.
|
||||
// Rule 5 ("never guess"): an undated or dropped OTC row in the same (primaryIsin, currency)
|
||||
// group could be the true continuation, so suppress all continuity linking for this group
|
||||
// until OTC listing metadata is resolved.
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -772,6 +851,7 @@ export function linkDelistingChains(
|
|||
stats: {
|
||||
totalInputListings,
|
||||
processedListings: validRows.length,
|
||||
skippedMalformedEntries,
|
||||
skippedInvalidDates,
|
||||
skippedDuplicateKeys,
|
||||
continuitiesCreated: continuities.length,
|
||||
|
|
|
|||
|
|
@ -114,6 +114,8 @@ CREATE TABLE IF NOT EXISTS vault_evaluations (
|
|||
);
|
||||
```
|
||||
|
||||
**Enforcement boundary:** The `<= 10`/year rolling cap (`vault_evaluations_cap`, `vault_evaluations_cap_after`) and append-only protections (`trial_ledger_retained`, `trial_ledger_no_truncate`, `vault_evaluations_retained`, `vault_evaluations_no_truncate`) are PostgreSQL triggers that block ordinary DML (`UPDATE`, `DELETE`, `TRUNCATE`, and cap-exceeding `INSERT`) from any role, but a table owner or superuser can bypass them via `ALTER TABLE ... DISABLE TRIGGER`. All services currently share a single owner role (while autonomous agents have no direct DB access); splitting an owner/migration role from a non-owner runtime role with only `SELECT, INSERT` on `trial_ledger` and `vault_evaluations` is deferred to pre-prod hardening.
|
||||
|
||||
---
|
||||
|
||||
## 4. IBKR Margin, USD/CAD, TSX Microstructure & Dual Drift Rules
|
||||
|
|
|
|||
|
|
@ -92,6 +92,68 @@ async function until(check: () => Promise<boolean>): Promise<void> {
|
|||
throw new Error('Timed out waiting for PostgreSQL advisory-lock waiter');
|
||||
}
|
||||
|
||||
interface ProtectionTriggerRow {
|
||||
relname: string;
|
||||
tgname: string;
|
||||
proname: string;
|
||||
tgenabled: string;
|
||||
}
|
||||
|
||||
const EXPECTED_PROTECTION_TRIGGERS: ProtectionTriggerRow[] = [
|
||||
{
|
||||
relname: 'trial_ledger',
|
||||
tgname: 'trial_ledger_no_truncate',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'trial_ledger',
|
||||
tgname: 'trial_ledger_retained',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'vault_evaluations',
|
||||
tgname: 'vault_evaluations_cap',
|
||||
proname: 'enforce_vault_evaluation_cap',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'vault_evaluations',
|
||||
tgname: 'vault_evaluations_cap_after',
|
||||
proname: 'verify_vault_evaluation_cap_after',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'vault_evaluations',
|
||||
tgname: 'vault_evaluations_no_truncate',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
{
|
||||
relname: 'vault_evaluations',
|
||||
tgname: 'vault_evaluations_retained',
|
||||
proname: 'reject_research_evidence_mutation',
|
||||
tgenabled: 'O',
|
||||
},
|
||||
];
|
||||
|
||||
async function listProtectionTriggers(pool: Pool, schema: string): Promise<ProtectionTriggerRow[]> {
|
||||
const result = await pool.query<ProtectionTriggerRow>(
|
||||
`SELECT c.relname, t.tgname, p.proname, t.tgenabled::text AS tgenabled
|
||||
FROM pg_trigger t
|
||||
JOIN pg_class c ON c.oid = t.tgrelid
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
JOIN pg_proc p ON p.oid = t.tgfoid
|
||||
WHERE NOT t.tgisinternal
|
||||
AND n.nspname = $1
|
||||
AND c.relname IN ('trial_ledger', 'vault_evaluations')
|
||||
ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`,
|
||||
[schema]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
interface TrialInsertOverrides {
|
||||
principalId?: string;
|
||||
campaignId?: string | null;
|
||||
|
|
@ -792,6 +854,7 @@ describe.skipIf(!url)(
|
|||
client.release();
|
||||
}
|
||||
expect(await countRows(f.pool, 'vault_evaluations')).toBe(11);
|
||||
expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS);
|
||||
|
||||
const g = await createIsolatedFixture();
|
||||
const seeder = await g.pool.connect();
|
||||
|
|
@ -809,6 +872,7 @@ describe.skipIf(!url)(
|
|||
}
|
||||
await expectPgErrorCode(insertVaultEvaluation(g.pool), '23514', /at most 10 evaluations/i);
|
||||
expect(await countRows(g.pool, 'vault_evaluations')).toBe(10);
|
||||
expect(await listProtectionTriggers(g.pool, g.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS);
|
||||
});
|
||||
|
||||
test('a single 10-row INSERT fills the cap exactly and the next insert is rejected', async () => {
|
||||
|
|
@ -1063,6 +1127,12 @@ describe.skipIf(!url)(
|
|||
client.release();
|
||||
}
|
||||
expect(await countRows(f.pool, 'vault_evaluations')).toBe(0);
|
||||
expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS);
|
||||
});
|
||||
|
||||
test('research-track migration leaves all 6 trial_ledger and vault_evaluations protection triggers enabled (T-64)', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS);
|
||||
});
|
||||
|
||||
test('failed burns (passed = false, negative Sharpe, NULL notes) still count toward the yearly cap', async () => {
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ function assertReconciliationAndContracts(
|
|||
expect(result.stats.processedListings).toBe(result.listingOutcomes.length);
|
||||
expect(
|
||||
result.stats.processedListings +
|
||||
result.stats.skippedMalformedEntries +
|
||||
result.stats.skippedInvalidDates +
|
||||
result.stats.skippedDuplicateKeys
|
||||
).toBe(result.stats.totalInputListings);
|
||||
|
|
@ -1240,6 +1241,443 @@ describe('security master Pass 6 OTC delisting chain linker', () => {
|
|||
expect(unsuppressed.conflicts).toEqual([]);
|
||||
});
|
||||
|
||||
test('quarantines null, sparse, undefined, primitive, and array slots as malformed_listing_entry without aborting valid rows (T-67)', () => {
|
||||
const cleanListings: StageBListingCandidate[] = [
|
||||
makeListing({
|
||||
primaryIsin: 'US78486Q1013',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'SIVB',
|
||||
currency: 'USD',
|
||||
listedFrom: '1987-10-26',
|
||||
listedTo: '2023-03-10',
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: 'US78486Q1013',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'SIVBQ',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-28',
|
||||
listedTo: '2024-11-07',
|
||||
}),
|
||||
];
|
||||
const cleanBaseline = linkDelistingChains(
|
||||
{ listings: cleanListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(cleanBaseline.stats.skippedMalformedEntries).toBe(0);
|
||||
assertReconciliationAndContracts(cleanBaseline, 2);
|
||||
|
||||
// (a) null entry in input.listings
|
||||
const withNull = [
|
||||
cleanListings[0],
|
||||
null as unknown as StageBListingCandidate,
|
||||
cleanListings[1],
|
||||
] as StageBListingCandidate[];
|
||||
const nullResult = linkDelistingChains(
|
||||
{ listings: withNull, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(nullResult.stats.skippedMalformedEntries).toBe(1);
|
||||
expect(nullResult.continuities).toEqual(cleanBaseline.continuities);
|
||||
expect(nullResult.listingOutcomes).toEqual(cleanBaseline.listingOutcomes);
|
||||
expect(nullResult.conflicts).toHaveLength(1);
|
||||
expect(nullResult.conflicts[0]).toMatchObject({
|
||||
conflictKind: 'malformed_listing_entry',
|
||||
detail: {
|
||||
primaryIsin: '',
|
||||
currency: '',
|
||||
fromListingKeys: [],
|
||||
toListingKeys: [],
|
||||
candidateListingKeys: [],
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
},
|
||||
});
|
||||
expect(nullResult.conflicts[0]?.detail.reason).toContain('input.listings[1]');
|
||||
expect(nullResult.conflicts[0]?.detail.reason).toContain('null');
|
||||
assertReconciliationAndContracts(nullResult, 3);
|
||||
|
||||
// (b1) Single sparse slot: listings[5] = ... on a 4-element array (hole at index 4)
|
||||
const singleHole: StageBListingCandidate[] = [
|
||||
cleanListings[0]!,
|
||||
cleanListings[1]!,
|
||||
makeListing({
|
||||
primaryIsin: 'US6700000001',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'ACT1',
|
||||
listedTo: null,
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: 'US6700000002',
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'ACT2',
|
||||
listedTo: null,
|
||||
}),
|
||||
];
|
||||
singleHole[5] = makeListing({
|
||||
primaryIsin: 'US6700000003',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'ACT3',
|
||||
listedTo: null,
|
||||
});
|
||||
const singleHoleResult = linkDelistingChains(
|
||||
{ listings: singleHole, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(singleHoleResult.stats.skippedMalformedEntries).toBe(1);
|
||||
expect(singleHoleResult.stats.processedListings).toBe(5);
|
||||
expect(singleHoleResult.continuities).toEqual(cleanBaseline.continuities);
|
||||
expect(singleHoleResult.conflicts).toHaveLength(1);
|
||||
expect(singleHoleResult.conflicts[0]?.conflictKind).toBe('malformed_listing_entry');
|
||||
expect(singleHoleResult.conflicts[0]?.detail.reason).toContain('input.listings[4]');
|
||||
expect(singleHoleResult.conflicts[0]?.detail.reason).toContain('sparse slot');
|
||||
assertReconciliationAndContracts(singleHoleResult, 6);
|
||||
|
||||
// (b2) Multi-hole sparse gap (holes at indices 1, 2, 3)
|
||||
const multiHole: StageBListingCandidate[] = [cleanListings[0]!];
|
||||
multiHole[4] = cleanListings[1]!;
|
||||
const multiHoleResult = linkDelistingChains(
|
||||
{ listings: multiHole, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(multiHoleResult.stats.skippedMalformedEntries).toBe(3);
|
||||
expect(multiHoleResult.continuities).toEqual(cleanBaseline.continuities);
|
||||
expect(multiHoleResult.listingOutcomes).toEqual(cleanBaseline.listingOutcomes);
|
||||
expect(multiHoleResult.conflicts).toHaveLength(3);
|
||||
expect(multiHoleResult.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'malformed_listing_entry',
|
||||
'malformed_listing_entry',
|
||||
'malformed_listing_entry',
|
||||
]);
|
||||
expect(multiHoleResult.conflicts.map(c => c.detail.reason)).toEqual([
|
||||
expect.stringContaining('input.listings[1]'),
|
||||
expect.stringContaining('input.listings[2]'),
|
||||
expect.stringContaining('input.listings[3]'),
|
||||
]);
|
||||
assertReconciliationAndContracts(multiHoleResult, 5);
|
||||
|
||||
// (c) undefined, primitive (number, string), and array non-object entries
|
||||
const mixedMalformed = [
|
||||
cleanListings[0],
|
||||
undefined as unknown as StageBListingCandidate,
|
||||
42 as unknown as StageBListingCandidate,
|
||||
'bad' as unknown as StageBListingCandidate,
|
||||
[] as unknown as StageBListingCandidate,
|
||||
cleanListings[1],
|
||||
] as StageBListingCandidate[];
|
||||
const mixedResult = linkDelistingChains(
|
||||
{ listings: mixedMalformed, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(mixedResult.stats.skippedMalformedEntries).toBe(4);
|
||||
expect(mixedResult.continuities).toEqual(cleanBaseline.continuities);
|
||||
expect(mixedResult.listingOutcomes).toEqual(cleanBaseline.listingOutcomes);
|
||||
expect(mixedResult.conflicts).toHaveLength(4);
|
||||
const reasons = mixedResult.conflicts.map(c => c.detail.reason);
|
||||
expect(reasons.some(r => r.includes('input.listings[1]') && r.includes('undefined'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(reasons.some(r => r.includes('input.listings[2]') && r.includes('number'))).toBe(true);
|
||||
expect(reasons.some(r => r.includes('input.listings[3]') && r.includes('string'))).toBe(true);
|
||||
expect(reasons.some(r => r.includes('input.listings[4]') && r.includes('array'))).toBe(true);
|
||||
assertReconciliationAndContracts(mixedResult, 6);
|
||||
});
|
||||
|
||||
test('suppresses linking when a same-group OTC row was dropped in Pass 1b as duplicate or invalid dates (T-71)', () => {
|
||||
const basePair: StageBListingCandidate[] = [
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000001',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAA',
|
||||
currency: 'USD',
|
||||
listedFrom: '2018-01-02',
|
||||
listedTo: '2023-03-10',
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000001',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'AAAQ',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-15',
|
||||
listedTo: '2024-01-01',
|
||||
}),
|
||||
];
|
||||
|
||||
// (a) Control case without AAAU -> 1 continuity, 0 conflicts.
|
||||
const control = linkDelistingChains(
|
||||
{ listings: basePair, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(control.continuities).toHaveLength(1);
|
||||
expect(control.conflicts).toEqual([]);
|
||||
assertReconciliationAndContracts(control, 2);
|
||||
|
||||
// (b) Duplicate OTCM AAAU (listedFrom: null) appearing twice -> 0 continuities,
|
||||
// 1 duplicate_listing_key + 1 missing_otc_listed_from (deduplicated toListingKeys), AAA -> unknown_involuntary / -0.3.
|
||||
const dupOtcListings: StageBListingCandidate[] = [
|
||||
...basePair,
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000001',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'AAAU',
|
||||
currency: 'USD',
|
||||
listedFrom: null,
|
||||
listedTo: '2024-01-01',
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000001',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'AAAU',
|
||||
currency: 'USD',
|
||||
listedFrom: null,
|
||||
listedTo: '2024-06-01',
|
||||
}),
|
||||
];
|
||||
const dupResult = linkDelistingChains(
|
||||
{ listings: dupOtcListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(dupResult.continuities).toEqual([]);
|
||||
expect(dupResult.stats.skippedDuplicateKeys).toBe(2);
|
||||
expect(dupResult.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'duplicate_listing_key',
|
||||
'missing_otc_listed_from',
|
||||
]);
|
||||
const dupMissingConflict = dupResult.conflicts.find(
|
||||
c => c.conflictKind === 'missing_otc_listed_from'
|
||||
);
|
||||
expect(dupMissingConflict?.detail.toListingKeys.map(k => k.tickerRoot)).toEqual(['AAAU']);
|
||||
expect(dupMissingConflict?.detail.fromListingKeys.map(k => k.tickerRoot)).toEqual(['AAA']);
|
||||
expect(dupMissingConflict?.detail.listedFrom).toBeNull();
|
||||
expect(dupMissingConflict?.detail.listedTo).toBeNull();
|
||||
expect(
|
||||
dupResult.listingOutcomes.find(o => o.listingKey.tickerRoot === 'AAA')
|
||||
).toMatchObject({
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: SHUMWAY_PRIMARY_TERMINAL_RETURN,
|
||||
});
|
||||
assertReconciliationAndContracts(dupResult, dupOtcListings.length);
|
||||
|
||||
// (c1) Single OTCM AAAU with invalid listedTo ('2024-13-45') and listedFrom: null
|
||||
const badDateNullFromListings: StageBListingCandidate[] = [
|
||||
...basePair,
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000001',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'AAAU',
|
||||
currency: 'USD',
|
||||
listedFrom: null,
|
||||
listedTo: '2024-13-45',
|
||||
}),
|
||||
];
|
||||
const badDateNullFromResult = linkDelistingChains(
|
||||
{ listings: badDateNullFromListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(badDateNullFromResult.continuities).toEqual([]);
|
||||
expect(badDateNullFromResult.stats.skippedInvalidDates).toBe(1);
|
||||
expect(badDateNullFromResult.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'invalid_listing_dates',
|
||||
'missing_otc_listed_from',
|
||||
]);
|
||||
expect(
|
||||
badDateNullFromResult.listingOutcomes.find(o => o.listingKey.tickerRoot === 'AAA')
|
||||
).toMatchObject({
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: SHUMWAY_PRIMARY_TERMINAL_RETURN,
|
||||
});
|
||||
assertReconciliationAndContracts(badDateNullFromResult, badDateNullFromListings.length);
|
||||
|
||||
// (c2) Single OTCM AAAU with invalid listedTo ('2024-13-45') and valid listedFrom ('2023-03-20')
|
||||
const badDateDatedFromListings: StageBListingCandidate[] = [
|
||||
...basePair,
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000001',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'AAAU',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-20',
|
||||
listedTo: '2024-13-45',
|
||||
}),
|
||||
];
|
||||
const badDateDatedFromResult = linkDelistingChains(
|
||||
{ listings: badDateDatedFromListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(badDateDatedFromResult.continuities).toEqual([]);
|
||||
expect(badDateDatedFromResult.stats.skippedInvalidDates).toBe(1);
|
||||
expect(badDateDatedFromResult.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'invalid_listing_dates',
|
||||
'missing_otc_listed_from',
|
||||
]);
|
||||
expect(
|
||||
badDateDatedFromResult.listingOutcomes.find(o => o.listingKey.tickerRoot === 'AAA')
|
||||
).toMatchObject({
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: SHUMWAY_PRIMARY_TERMINAL_RETURN,
|
||||
});
|
||||
assertReconciliationAndContracts(badDateDatedFromResult, badDateDatedFromListings.length);
|
||||
|
||||
// (f) Point-in-time asOfDate: '2023-03-15' (within activeGraceDays of AAA listedTo 2023-03-10)
|
||||
// emits no missing_otc_listed_from conflict.
|
||||
const graceResult = linkDelistingChains(
|
||||
{ listings: dupOtcListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2023-03-15' }
|
||||
);
|
||||
expect(graceResult.continuities).toEqual([]);
|
||||
expect(graceResult.conflicts.map(c => c.conflictKind)).toEqual(['duplicate_listing_key']);
|
||||
assertReconciliationAndContracts(graceResult, dupOtcListings.length);
|
||||
|
||||
// (g) Shuffle determinism & unique cloned ListingNaturalKey reference isolation on dropped-OTC suppression.
|
||||
const baselineJson = JSON.stringify(dupResult);
|
||||
const inputRefs = new Set<unknown>(dupOtcListings);
|
||||
const seenKeyRefs = new Set<ListingNaturalKey>();
|
||||
const registerKey = (key: ListingNaturalKey): void => {
|
||||
expect(inputRefs.has(key)).toBe(false);
|
||||
expect(seenKeyRefs.has(key)).toBe(false);
|
||||
seenKeyRefs.add(key);
|
||||
};
|
||||
for (const o of dupResult.listingOutcomes) {
|
||||
registerKey(o.listingKey);
|
||||
}
|
||||
for (const conflict of dupResult.conflicts) {
|
||||
for (const k of conflict.detail.fromListingKeys) {
|
||||
registerKey(k);
|
||||
}
|
||||
for (const k of conflict.detail.toListingKeys) {
|
||||
registerKey(k);
|
||||
}
|
||||
for (const k of conflict.detail.candidateListingKeys) {
|
||||
registerKey(k);
|
||||
}
|
||||
}
|
||||
for (const seed of [7, 42, 1337, 65535]) {
|
||||
const shuffled = shuffleWithSeed(dupOtcListings, seed);
|
||||
const shuffledResult = linkDelistingChains(
|
||||
{ listings: shuffled, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(JSON.stringify(shuffledResult)).toBe(baselineJson);
|
||||
assertReconciliationAndContracts(shuffledResult, dupOtcListings.length);
|
||||
}
|
||||
});
|
||||
|
||||
test('T-71 negative cases: dropped OTC rows with empty ISIN/currency and dropped non-OTC rows do not block linking; custom otcMics respected', () => {
|
||||
const validPair = (isin: string, root: string, otcMic = 'OTCM'): StageBListingCandidate[] => [
|
||||
makeListing({
|
||||
primaryIsin: isin,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: root,
|
||||
currency: 'USD',
|
||||
listedFrom: '2018-01-02',
|
||||
listedTo: '2023-03-10',
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: isin,
|
||||
mic: otcMic,
|
||||
tickerRoot: `${root}Q`,
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-15',
|
||||
listedTo: '2024-01-01',
|
||||
}),
|
||||
];
|
||||
|
||||
// (d) Dropped OTC rows with empty primaryIsin or empty currency must NOT block any group.
|
||||
const unresolvableKeyListings: StageBListingCandidate[] = [
|
||||
...validPair('US7100000010', 'GOOD'),
|
||||
makeListing({
|
||||
primaryIsin: '',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'NOISIN',
|
||||
currency: 'USD',
|
||||
listedFrom: null,
|
||||
listedTo: '2024-13-45',
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000010',
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'NOCUR',
|
||||
currency: '',
|
||||
listedFrom: null,
|
||||
listedTo: '2024-13-45',
|
||||
}),
|
||||
];
|
||||
const unresolvableResult = linkDelistingChains(
|
||||
{ listings: unresolvableKeyListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(unresolvableResult.continuities).toHaveLength(1);
|
||||
expect(unresolvableResult.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'invalid_listing_dates',
|
||||
'invalid_listing_dates',
|
||||
]);
|
||||
assertReconciliationAndContracts(unresolvableResult, unresolvableKeyListings.length);
|
||||
|
||||
// (e) Dropped non-OTC rows (duplicate or invalid dates in same (primaryIsin, currency) group) must NOT block linking.
|
||||
const droppedNonOtcListings: StageBListingCandidate[] = [
|
||||
...validPair('US7100000011', 'NONO'),
|
||||
// Duplicate non-OTC row in same group
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000011',
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'DUPP',
|
||||
currency: 'USD',
|
||||
listedFrom: '2015-01-02',
|
||||
listedTo: '2020-01-01',
|
||||
}),
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000011',
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'DUPP',
|
||||
currency: 'USD',
|
||||
listedFrom: '2016-01-02',
|
||||
listedTo: '2020-06-01',
|
||||
}),
|
||||
// Invalid-date non-OTC row in same group
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000011',
|
||||
mic: 'XARC',
|
||||
tickerRoot: 'BADP',
|
||||
currency: 'USD',
|
||||
listedFrom: '2020-01-01',
|
||||
listedTo: '2024-13-45',
|
||||
}),
|
||||
];
|
||||
const droppedNonOtcResult = linkDelistingChains(
|
||||
{ listings: droppedNonOtcListings, otcMics: DEFAULT_OTC_MICS },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(droppedNonOtcResult.continuities).toHaveLength(1);
|
||||
expect(droppedNonOtcResult.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'duplicate_listing_key',
|
||||
'invalid_listing_dates',
|
||||
]);
|
||||
assertReconciliationAndContracts(droppedNonOtcResult, droppedNonOtcListings.length);
|
||||
|
||||
// (g) Custom otcMics: dropped PINX row blocks when otcMics = Set(['PINX']), does not block when otcMics = Set(['OTCM']).
|
||||
const customOtcListings: StageBListingCandidate[] = [
|
||||
...validPair('US7100000012', 'PINC', 'PINX'),
|
||||
makeListing({
|
||||
primaryIsin: 'US7100000012',
|
||||
mic: 'PINX',
|
||||
tickerRoot: 'PINCU',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-20',
|
||||
listedTo: '2024-13-45',
|
||||
}),
|
||||
];
|
||||
const customBlocked = linkDelistingChains(
|
||||
{ listings: customOtcListings, otcMics: new Set(['PINX']) },
|
||||
{ asOfDate: '2025-11-27' }
|
||||
);
|
||||
expect(customBlocked.continuities).toEqual([]);
|
||||
expect(customBlocked.conflicts.map(c => c.conflictKind)).toEqual([
|
||||
'invalid_listing_dates',
|
||||
'missing_otc_listed_from',
|
||||
]);
|
||||
assertReconciliationAndContracts(customBlocked, customOtcListings.length);
|
||||
});
|
||||
|
||||
test('throws TypeError or RangeError on invalid options or container arguments', () => {
|
||||
const emptyInput = { listings: [], otcMics: DEFAULT_OTC_MICS };
|
||||
const validOpts = { asOfDate: '2025-11-27' };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue