T-56: M1.1f — Pass 3 Stage B: pure in-memory listing matcher (EOD venue → listing, IB conid at (instrument, currency), QM/CEO ticker+span Tier 3)

This commit is contained in:
Studio 2026-11-27 16:50:47 -05:00 • committed by Boki
parent 381334720a
commit 0df989cc07
4 changed files with 162 additions and 123 deletions

View file

@ -7,6 +7,13 @@ export interface ParsedTicker {
classSuffix: string;
}
export type ParseTickerFailureReason = 'invalid_ticker' | 'class_suffix_too_long';
export type ParseTickerDetailedResult =
| { ok: true; tickerRoot: string; classSuffix: string }
| { ok: false; reason: 'invalid_ticker' }
| { ok: false; reason: 'class_suffix_too_long'; tickerRoot: string; classSuffix: string };
const CODE_TAB = 9;
const CODE_SPACE = 32;
const CODE_DASH = 45;
@ -37,21 +44,21 @@ function findNextSeparator(str: string, start: number): number {
}
/**
* Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair.
* Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair,
* returning a structured failure reason (`invalid_ticker` or `class_suffix_too_long`) on failure.
* Strips embedded `.TO` / `.V` venue suffixes only when `source === 'ceo'`.
* Plain tickers return `classSuffix: ''`; empty or malformed inputs return `null`.
*/
export function parseTicker(
export function parseTickerDetailed(
raw: string | null | undefined,
source: TickerSource
): ParsedTicker | null {
): ParseTickerDetailedResult {
if (typeof raw !== 'string') {
return null;
return { ok: false, reason: 'invalid_ticker' };
}
let s = raw.trim().toUpperCase();
if (s.length === 0) {
return null;
return { ok: false, reason: 'invalid_ticker' };
}
if (source === 'ceo') {
@ -61,16 +68,16 @@ export function parseTicker(
s = s.slice(0, -2).trimEnd();
}
if (s.length === 0) {
return null;
return { ok: false, reason: 'invalid_ticker' };
}
}
const firstSep = findNextSeparator(s, 0);
if (firstSep === -1) {
return { tickerRoot: s, classSuffix: '' };
return { ok: true, tickerRoot: s, classSuffix: '' };
}
if (firstSep === 0) {
return null;
return { ok: false, reason: 'invalid_ticker' };
}
const tickerRoot = s.slice(0, firstSep);
@ -79,13 +86,16 @@ export function parseTicker(
pos++;
}
if (pos >= s.length || isSeparator(s.charCodeAt(pos))) {
return null;
return { ok: false, reason: 'invalid_ticker' };
}
const secondSep = findNextSeparator(s, pos);
if (secondSep === -1) {
const classSuffix = s.slice(pos);
return classSuffix.length <= MAX_CLASS_SUFFIX_LENGTH ? { tickerRoot, classSuffix } : null;
if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) {
return { ok: false, reason: 'class_suffix_too_long', tickerRoot, classSuffix };
}
return { ok: true, tickerRoot, classSuffix };
}
let classSuffix = s.slice(pos, secondSep);
@ -96,7 +106,7 @@ export function parseTicker(
pos++;
}
if (pos >= s.length || isSeparator(s.charCodeAt(pos))) {
return null;
return { ok: false, reason: 'invalid_ticker' };
}
const nextSep = findNextSeparator(s, pos);
if (nextSep === -1) {
@ -108,8 +118,21 @@ export function parseTicker(
}
if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) {
return null;
return { ok: false, reason: 'class_suffix_too_long', tickerRoot, classSuffix };
}
return { tickerRoot, classSuffix };
return { ok: true, tickerRoot, classSuffix };
}
/**
* Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair.
* Strips embedded `.TO` / `.V` venue suffixes only when `source === 'ceo'`.
* Plain tickers return `classSuffix: ''`; empty or malformed inputs return `null`.
*/
export function parseTicker(
raw: string | null | undefined,
source: TickerSource
): ParsedTicker | null {
const result = parseTickerDetailed(raw, source);
return result.ok ? { tickerRoot: result.tickerRoot, classSuffix: result.classSuffix } : null;
}

View file

@ -4,7 +4,7 @@ import {
type SpanDateRange,
type SpansOverlapOptions,
} from '../normalization/bar-spans';
import { MAX_CLASS_SUFFIX_LENGTH, parseTicker } from '../normalization/ticker';
import { parseTickerDetailed } from '../normalization/ticker';
import { compareAscii, type ExchangeRole } from './exchange-pass1';
import type {
StageAInstrumentCandidate,
@ -180,12 +180,7 @@ interface StagedIbCandidate {
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/;
const CODE_TAB = 9;
const CODE_SPACE = 32;
const CODE_DASH = 45;
const CODE_DOT = 46;
const CODE_SLASH = 47;
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
export function isStageBSource(value: unknown): value is StageBSource {
return value === 'eod' || value === 'ib' || value === 'qm' || value === 'ceo';
@ -222,118 +217,26 @@ function createEmptySourceStats(): StageBSourceStats {
};
}
function isTickerWhitespace(code: number): boolean {
return code === CODE_SPACE || code === CODE_TAB;
}
function isTickerSeparator(code: number): boolean {
return (
code === CODE_DOT ||
code === CODE_DASH ||
code === CODE_SPACE ||
code === CODE_TAB ||
code === CODE_SLASH
);
}
function findNextTickerSeparator(str: string, start: number): number {
for (let i = start; i < str.length; i++) {
if (isTickerSeparator(str.charCodeAt(i))) {
return i;
}
}
return -1;
}
/**
* Called only when `parseTicker` returned `null` so the hot path remains single-pass.
* Distinguishes structurally valid tickers whose `classSuffix` exceeded `MAX_CLASS_SUFFIX_LENGTH`
* (or whose `tickerRoot` exceeded `MAX_TICKER_ROOT_LENGTH`) from malformed tickers.
*/
function classifyNullTickerReason(
raw: string | null | undefined,
source: StageBSource
): 'ticker_root_too_long' | 'class_suffix_too_long' | 'invalid_ticker' {
if (typeof raw !== 'string') {
return 'invalid_ticker';
}
let s = raw.trim().toUpperCase();
if (s.length === 0) {
return 'invalid_ticker';
}
if (source === 'ceo') {
if (s.length > 3 && s.endsWith('.TO')) {
s = s.slice(0, -3).trimEnd();
} else if (s.length > 2 && s.endsWith('.V')) {
s = s.slice(0, -2).trimEnd();
}
if (s.length === 0) {
return 'invalid_ticker';
}
}
const firstSep = findNextTickerSeparator(s, 0);
if (firstSep <= 0) {
return 'invalid_ticker';
}
const tickerRoot = s.slice(0, firstSep);
let pos = firstSep + 1;
while (pos < s.length && isTickerWhitespace(s.charCodeAt(pos))) {
pos++;
}
if (pos >= s.length || isTickerSeparator(s.charCodeAt(pos))) {
return 'invalid_ticker';
}
const secondSep = findNextTickerSeparator(s, pos);
let classSuffix: string;
if (secondSep === -1) {
classSuffix = s.slice(pos);
} else {
classSuffix = s.slice(pos, secondSep);
pos = secondSep;
while (pos < s.length) {
pos++;
while (pos < s.length && isTickerWhitespace(s.charCodeAt(pos))) {
pos++;
}
if (pos >= s.length || isTickerSeparator(s.charCodeAt(pos))) {
return 'invalid_ticker';
}
const nextSep = findNextTickerSeparator(s, pos);
if (nextSep === -1) {
classSuffix += '.' + s.slice(pos);
break;
}
classSuffix += '.' + s.slice(pos, nextSep);
pos = nextSep;
}
}
if (tickerRoot.length > MAX_TICKER_ROOT_LENGTH) {
return 'ticker_root_too_long';
}
if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) {
return 'class_suffix_too_long';
}
return 'invalid_ticker';
}
function classifyTicker(
raw: string | null | undefined,
source: StageBSource
):
| { ok: true; tickerRoot: string; classSuffix: string }
| { ok: false; reason: 'ticker_root_too_long' | 'class_suffix_too_long' | 'invalid_ticker' } {
const parsed = parseTicker(raw, source);
if (parsed === null) {
return { ok: false, reason: classifyNullTickerReason(raw, source) };
const parsed = parseTickerDetailed(raw, source);
if (!parsed.ok) {
if (
parsed.reason === 'class_suffix_too_long' &&
parsed.tickerRoot.length > MAX_TICKER_ROOT_LENGTH
) {
return { ok: false, reason: 'ticker_root_too_long' };
}
return { ok: false, reason: parsed.reason };
}
if (parsed.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) {
return { ok: false, reason: 'ticker_root_too_long' };
}
return { ok: true, tickerRoot: parsed.tickerRoot, classSuffix: parsed.classSuffix };
return parsed;
}
function classifyVenueRoleAndMic(
@ -410,6 +313,13 @@ function validateSpan(
if (typeof span.firstBarDate !== 'string' || typeof span.lastBarDate !== 'string') {
return { status: 'invalid' };
}
// Require exact YYYY-MM-DD strings so timezone-qualified timestamps cannot shift across UTC day boundaries.
if (
!EXACT_YMD_PATTERN.test(span.firstBarDate) ||
!EXACT_YMD_PATTERN.test(span.lastBarDate)
) {
return { status: 'invalid' };
}
const firstBarDate = normalizeBarDate(span.firstBarDate);
const lastBarDate = normalizeBarDate(span.lastBarDate);
if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) {

View file

@ -5,6 +5,7 @@ import {
} from '../../apps/stock/data-pipeline/src/normalization/identifiers';
import {
parseTicker,
parseTickerDetailed,
type TickerSource,
} from '../../apps/stock/data-pipeline/src/normalization/ticker';
@ -86,6 +87,23 @@ describe('parseTicker', () => {
});
expect(parseTicker('RY.ABCDEFGHIJKLM', 'eod')).toBeNull();
expect(parseTicker('RY.PR.ABCDEFGHIJ', 'eod')).toBeNull();
expect(parseTickerDetailed('RY.ABCDEFGHIJKLM', 'eod')).toEqual({
ok: false,
reason: 'class_suffix_too_long',
tickerRoot: 'RY',
classSuffix: 'ABCDEFGHIJKLM',
});
expect(parseTickerDetailed('RY.PR.ABCDEFGHIJ.TO', 'ceo')).toEqual({
ok: false,
reason: 'class_suffix_too_long',
tickerRoot: 'RY',
classSuffix: 'PR.ABCDEFGHIJ',
});
expect(parseTickerDetailed('RY..A', 'eod')).toEqual({
ok: false,
reason: 'invalid_ticker',
});
});
test('completes 100,000 resolveIsin + parseTicker calls in under 500 ms', () => {

View file

@ -864,6 +864,94 @@ describe('security master Pass 3 Stage B listing matcher', () => {
expect(() => matchListingsStageB(baseInput, { spanOverlapToleranceDays: 1.5 })).toThrow(RangeError);
});
test('rejects timestamp-shaped and padded spans as invalid_span instead of shifting across UTC day boundaries', () => {
const result = matchListingsStageB({
instruments: [
{
primaryIsin: 'US0000000026',
primaryCusip: null,
issuerCountry: 'US',
canonicalName: 'FB Reused Listing',
members: [
{ source: 'eod', sourceId: 'FB_NEW.US', currency: 'USD', method: 'tier1_isin' },
{ source: 'eod', sourceId: 'FB_TS_EOD.US', currency: 'USD', method: 'tier1_isin' },
],
},
],
eodListings: [
{
sourceId: 'FB_NEW.US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' },
},
{
sourceId: 'FB_TS_EOD.US',
ticker: 'FBTS',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: {
firstBarDate: '2025-01-01T23:30:00-05:00',
lastBarDate: '2025-01-02T00:00:00Z',
},
},
],
ibContracts: [],
tickerSources: [
// Timezone offset would shift 2025-01-01T23:30:00-05:00 -> 2025-01-02 UTC and falsely match FB_NEW.US.
{
source: 'qm',
sourceId: 'QM_TZ_SHIFT',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: {
firstBarDate: '2025-01-01T23:30:00-05:00',
lastBarDate: '2025-01-01T23:30:00-05:00',
},
},
{
source: 'qm',
sourceId: 'QM_UTC_TS',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: {
firstBarDate: '2025-01-02T00:00:00Z',
lastBarDate: '2025-01-02T00:00:00Z',
},
},
{
source: 'qm',
sourceId: 'QM_PADDED_YMD',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: {
firstBarDate: ' 2025-01-02 ',
lastBarDate: '2025-01-03',
},
},
],
});
expect(result.listings).toHaveLength(1);
expect(result.providerMappings.filter(m => m.source === 'qm')).toEqual([]);
expect(result.unresolved).toEqual([
{ source: 'eod', sourceId: 'FB_TS_EOD.US', reason: 'invalid_span', primaryIsin: 'US0000000026' },
{ source: 'qm', sourceId: 'QM_PADDED_YMD', reason: 'invalid_span', primaryIsin: null },
{ source: 'qm', sourceId: 'QM_TZ_SHIFT', reason: 'invalid_span', primaryIsin: null },
{ source: 'qm', sourceId: 'QM_UTC_TS', reason: 'invalid_span', primaryIsin: null },
]);
assertReconciliationAndContracts(result);
});
test('enforces ticker/classSuffix/currency bounds and does not mask explicitly invalid eod.currency', () => {
const root25 = 'A'.repeat(MAX_TICKER_ROOT_LENGTH + 1);
const suffix13 = 'B'.repeat(MAX_CLASS_SUFFIX_LENGTH + 1);