From 9e259ca43bca4c8d536b48e1e4abbd6f8aabfc70 Mon Sep 17 00:00:00 2001 From: Boki Date: Fri, 27 Nov 2026 16:11:57 -0500 Subject: [PATCH] Clear M1 milestone bugs (T-37, T-39, T-41, T-42, T-44, T-45, T-46, T-48, T-49, T-51, T-52) --- Cargo.toml | 7 ++- apps/stock/config/src/env-safety.ts | 36 ++++++++++- apps/stock/data-pipeline/README.md | 8 +-- .../src/normalization/bar-spans.ts | 17 +++--- .../data-pipeline/src/normalization/ticker.ts | 9 ++- .../src/security-master/exchange-pass1.ts | 17 ++++++ .../src/security-master/exchange-seed-sql.ts | 59 ++++++++++++++++++- apps/stock/engine/Cargo.toml | 5 -- database/postgres/init/34-security-master.sql | 2 +- design/DATA-CONTRACTS.md | 2 +- design/PLATFORM-PLAN.md | 2 +- studio.config.json | 2 +- .../postgres/security-master-contract.test.ts | 2 +- test/unit/environment-safety.test.ts | 13 ++++ ...normalization-bar-spans-edge-cases.test.ts | 19 +++++- test/unit/normalization-bar-spans.test.ts | 32 ++++++++-- test/unit/normalization-ticker.test.ts | 9 +++ ...y-master-exchange-pass1-edge-cases.test.ts | 48 +++++++++++++++ 18 files changed, 255 insertions(+), 34 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index adb925b9..0658ca13 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,4 +21,9 @@ chrono = { version = "0.4", features = ["serde"] } uuid = { version = "1", features = ["v4", "serde"] } tracing = "0.1" thiserror = "1" -anyhow = "1" \ No newline at end of file +anyhow = "1" + +[profile.release] +lto = true +opt-level = 3 +codegen-units = 1 \ No newline at end of file diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 5ee63dc2..e449d383 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -122,8 +122,30 @@ function parseNumericIpv4Octets(host: string): [number, number, number, number] return [p0, p1, p2, p3]; } -function isIpv4Loopback(host: string): boolean { - const octets = parseNumericIpv4Octets(host); +function parseDecimalIpv4Octets(host: string): [number, number, number, number] | null { + const octets = host.split('.'); + if (octets.length !== 4) { + return null; + } + const values: number[] = []; + for (const part of octets) { + if (!/^\d+$/.test(part)) { + return null; + } + const value = Number(part); + if (!Number.isSafeInteger(value) || value < 0 || value > 255) { + return null; + } + values.push(value); + } + const [a, b, c, d] = values; + if (a === undefined || b === undefined || c === undefined || d === undefined) { + return null; + } + return [a, b, c, d]; +} + +function isIpv4LoopbackOctets(octets: [number, number, number, number] | null): boolean { return ( octets !== null && (octets[0] === 127 || @@ -131,6 +153,16 @@ function isIpv4Loopback(host: string): boolean { ); } +function isIpv4Loopback(host: string): boolean { + // Check both POSIX numeric IPv4 (octal/hex/shorthand, e.g. 0177.0.0.1, 127.1, 0x7f000001) + // and decimal dotted-quad interpretation (e.g. 0127.0.0.1 -> 127.0.0.1) so resolvers that + // read leading-zero quads as decimal cannot bypass the loopback guard. + return ( + isIpv4LoopbackOctets(parseNumericIpv4Octets(host)) || + isIpv4LoopbackOctets(parseDecimalIpv4Octets(host)) + ); +} + function parseIpv6Side(side: string, allowIpv4Tail: boolean): number[] | null { if (side === '') { return []; diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 60fd07a6..9f8aa718 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -11,7 +11,7 @@ Normalizes raw provider collections from MongoDB (`stock`) into canonical Postgr ## Current Runtime Scope - **MongoDB Inputs:** `exchanges`, `eodExchanges`, `ibExchanges`, `qmExchanges`, `eodSymbols`, `ibSymbols`, `qmSymbols`. -- **PostgreSQL Tables (`database/postgres/init/02-exchange-symbol-schema.sql`):** +- **PostgreSQL Tables (`database/postgres/init/02-master-schema.sql`):** - `exchanges` & `provider_exchange_mappings` - `symbols` & `provider_mappings` - `sync_status` @@ -23,9 +23,9 @@ Normalizes raw provider collections from MongoDB (`stock`) into canonical Postgr ## Target Architecture (`Milestone M1` & `M2`) Full specifications live in: -- [DATA-CONTRACTS.md](../../../docs/DATA-CONTRACTS.md) — Empirical 31-collection rules, bi-temporal security master (`instruments`, `instrument_listings`, `provider_symbol_map`, `corporate_actions`), Hive Parquet + DuckDB schemas (`bars_1d`, `fundamentals_pit`, `earnings_events_pit`, `short_interest_pit`, `macro_pit`, `fx_rates_1d`), and QuestDB `10.2.0` intraday schema. -- [MILESTONES.md](../../../docs/MILESTONES.md) — Step-by-step `M0` (read-only wrapper hardening), `M1` (US + Canada security master & `bars_1d` + `fx_rates_1d` curation), and `M2` (`qmFilings`-backed PIT fundamentals, earnings, short interest, and macro curation). -- [phase1-investigation.md](../../../docs/data-pipeline/phase1-investigation.md) — Initial provider exchange/symbol investigation notes. +- [DATA-CONTRACTS.md](../../../design/DATA-CONTRACTS.md) — Empirical 31-collection rules, bi-temporal security master (`exchange`, `exchange_source_map`, `instrument`, `instrument_identifier_history`, `listing`, `corporate_action_continuity`, `listing_symbol_history`, `provider_mapping`, `resolution_conflict`, `override`, `golden_field_audit`), Hive Parquet + DuckDB schemas (`bars_1d`, `fundamentals_pit`, `earnings_events_pit`, `short_interest_pit`, `macro_pit`, `fx_rates_1d`), and QuestDB `10.2.0` intraday schema. +- [MILESTONES.md](../../../design/MILESTONES.md) — Step-by-step `M0` (read-only wrapper hardening), `M1` (US + Canada security master & `bars_1d` + `fx_rates_1d` curation), and `M2` (`qmFilings`-backed PIT fundamentals, earnings, short interest, and macro curation). +- [phase1-investigation.md](../../../design/data-pipeline/phase1-investigation.md) — Initial provider exchange/symbol investigation notes. ## Commands Run from the repository root: diff --git a/apps/stock/data-pipeline/src/normalization/bar-spans.ts b/apps/stock/data-pipeline/src/normalization/bar-spans.ts index e0a79f90..7be715c5 100644 --- a/apps/stock/data-pipeline/src/normalization/bar-spans.ts +++ b/apps/stock/data-pipeline/src/normalization/bar-spans.ts @@ -487,7 +487,11 @@ function buildNormalizedSpanStages(spec: BarSpanCollectionSpec): Record MAX_CLASS_SUFFIX_LENGTH) { + return null; + } + return { tickerRoot, classSuffix }; } diff --git a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts index 6ff61115..de857f66 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts @@ -13,8 +13,11 @@ export type BoardLotPolicy = 'us_100' | 'tsx_tiered' | 'fx'; export type ClassificationMethod = 'explicit_rule' | 'operating_mic'; +export const MAX_EXCHANGE_SOURCE_CODE_LENGTH = 32; + export type UnresolvedExchangeReason = | 'empty_code' + | 'source_code_too_long' | 'multi_valued_operating_mic' | 'invalid_operating_mic_format' | 'unknown_operating_mic' @@ -347,6 +350,20 @@ export function classifySourceExchanges( continue; } + if (normalizedCode.length > MAX_EXCHANGE_SOURCE_CODE_LENGTH) { + unresolved.push({ + source: record.source, + sourceCode: normalizedCode, + rawCode, + name: normalizeOptionalString(record.name), + country: normalizeOptionalString(record.country), + operatingMic: normalizeOptionalString(record.operatingMic), + currency: normalizeOptionalString(record.currency), + reason: 'source_code_too_long', + }); + continue; + } + const key = makeRuleKey(record.source, normalizedCode); const existing = grouped.get(key); if (existing) { diff --git a/apps/stock/data-pipeline/src/security-master/exchange-seed-sql.ts b/apps/stock/data-pipeline/src/security-master/exchange-seed-sql.ts index 15519573..d691bc4a 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-seed-sql.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-seed-sql.ts @@ -1,6 +1,7 @@ import { compareAscii, compareUnresolvedExchangeRecords, + MAX_EXCHANGE_SOURCE_CODE_LENGTH, type ExchangeClassificationResult, type ExchangeSeedRow, type ExchangeSourceMapRow, @@ -22,11 +23,63 @@ export function escapeSqlLiteral(value: string | null | undefined): string { return `'${value.replaceAll("'", "''")}'`; } -export function generateExchangeSeedSql(input: GenerateExchangeSeedSqlInput): string { - const exchanges = [...(input.exchanges ?? [])].sort((a, b) => compareAscii(a.mic, b.mic)); - const mappings = [...input.mappings].sort( +function deduplicateExchanges(rows: readonly ExchangeSeedRow[]): ExchangeSeedRow[] { + const byMic = new Map(); + for (const row of rows) { + const existing = byMic.get(row.mic); + if (!existing) { + byMic.set(row.mic, row); + continue; + } + if ( + existing.operatingMic !== row.operatingMic || + existing.name !== row.name || + existing.countryIso !== row.countryIso || + existing.currency !== row.currency || + existing.timezone !== row.timezone || + existing.calendarCode !== row.calendarCode || + existing.boardLotPolicy !== row.boardLotPolicy + ) { + throw new Error(`Conflicting duplicate exchange row for mic "${row.mic}"`); + } + } + return Array.from(byMic.values()).sort((a, b) => compareAscii(a.mic, b.mic)); +} + +function deduplicateMappings(rows: readonly ExchangeSourceMapRow[]): ExchangeSourceMapRow[] { + const byKey = new Map(); + for (const row of rows) { + if (row.sourceCode.length === 0 || row.sourceCode.length > MAX_EXCHANGE_SOURCE_CODE_LENGTH) { + throw new Error( + `Invalid sourceCode "${row.sourceCode}" for source "${row.source}": length must be between 1 and ${MAX_EXCHANGE_SOURCE_CODE_LENGTH} characters` + ); + } + const key = `${row.source}\u0000${row.sourceCode}`; + const existing = byKey.get(key); + if (!existing) { + byKey.set(key, row); + continue; + } + if ( + existing.role !== row.role || + existing.mic !== row.mic || + existing.countryIso !== row.countryIso || + existing.method !== row.method || + (existing.reviewedBy ?? null) !== (row.reviewedBy ?? null) + ) { + throw new Error( + `Conflicting duplicate exchange_source_map row for (${row.source}, "${row.sourceCode}")` + ); + } + } + return Array.from(byKey.values()).sort( (a, b) => compareAscii(a.source, b.source) || compareAscii(a.sourceCode, b.sourceCode) ); +} + +export function generateExchangeSeedSql(input: GenerateExchangeSeedSqlInput): string { + const exchanges = deduplicateExchanges(input.exchanges ?? []); + const mappings = deduplicateMappings(input.mappings); const sections: string[] = [ [ diff --git a/apps/stock/engine/Cargo.toml b/apps/stock/engine/Cargo.toml index dbea6685..1503338c 100644 --- a/apps/stock/engine/Cargo.toml +++ b/apps/stock/engine/Cargo.toml @@ -44,8 +44,3 @@ tracing-subscriber = "0.3" [build-dependencies] napi-build = "2" - -[profile.release] -lto = true -opt-level = 3 -codegen-units = 1 diff --git a/database/postgres/init/34-security-master.sql b/database/postgres/init/34-security-master.sql index d591ba04..97a02708 100644 --- a/database/postgres/init/34-security-master.sql +++ b/database/postgres/init/34-security-master.sql @@ -43,7 +43,7 @@ CREATE TABLE IF NOT EXISTS instrument_identifier_history ( id_type VARCHAR(8) NOT NULL CHECK (id_type IN ('ISIN', 'CUSIP')), id_value VARCHAR(16) NOT NULL, - valid_from DATE, + valid_from DATE NOT NULL, valid_to DATE, source VARCHAR(16) NOT NULL, PRIMARY KEY (id_type, id_value, valid_from) diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index bbad5858..bec7f246 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -73,7 +73,7 @@ CREATE TABLE IF NOT EXISTS instrument_identifier_history ( id_type VARCHAR(8) NOT NULL CHECK (id_type IN ('ISIN', 'CUSIP')), id_value VARCHAR(16) NOT NULL, - valid_from DATE, + valid_from DATE NOT NULL, valid_to DATE, source VARCHAR(16) NOT NULL, PRIMARY KEY (id_type, id_value, valid_from) diff --git a/design/PLATFORM-PLAN.md b/design/PLATFORM-PLAN.md index dacbb6e5..4ab93132 100644 --- a/design/PLATFORM-PLAN.md +++ b/design/PLATFORM-PLAN.md @@ -207,7 +207,7 @@ Exact DDL and edge-case rules are specified in **[DATA-CONTRACTS.md](DATA-CONTRA ### Six-pass resolution pipeline 1. **Pass 1 — Exchanges (~320 rows):** Seed ISO 10383 MICs; map EOD (`76`), IB (`214`), QM (`25`), and CEO (`4: TSX→XTSE, CDX→XTSX, CNQ→XCNQ, AQL→NEOE`). Explicitly tag EOD `US` as composite (resolved via per-symbol `eodSymbols.Exchange`), exclude EOD `NMFQS` (`44,970` mutual funds) from equity universes, and mark IB ATS/smart codes (`AEQLIT`, `ARCAEDGE`, `BEX`, `DRCTEDGE`, `EDGEA`, `IEX`, `MEMX`, `OTCLNKECN`, `PSX`, `IBEOS`) as **`ats_routing`** rather than primary listing MICs. -2. **Pass 2 — Normalization & Observed Spans:** Parse root + suffix (`AAA-P`/`AAA.P`, `AACT U`/`AACT.U`, `SCU.UN`, strip CEO `.TO`/`.V`), Luhn-validate ISINs (rejecting `CATSETEST001`, `CA00149WBAD4`, checksum-corrupted `CA8131391062` while recovering valid CUSIP `813139106` → `CA8131391064`), fix `provider-symbol.ts` to read IB `exchangeId`/`description`, and precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`. +2. **Pass 2 — Normalization & Observed Spans:** Parse root + suffix (`AAA-P`/`AAA.P`, `AACT U`/`AACT.U`, `SCU.UN`, strip CEO `.TO`/`.V`), Luhn-validate ISINs (rejecting placeholder/checksum-bad values like `CATSETEST001`, `CA00149WBAD4`, `CA8131391062` while recovering a checksum-corrupted US/CA ISIN from a valid 9-char CUSIP, e.g. `037833100` → `US0378331005` or `82509L107` → `CA82509L1076`), fix `provider-symbol.ts` to read IB `exchangeId`/`description`, and precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`. 3. **Pass 3 — Two-Stage Matching (Instrument first, Listing second):** - **Stage A (`instrument`):** Match globally by Luhn-valid ISIN and US/CA CUSIP-derived ISIN (`IB ↔ EOD`). Interlisted US/CA shares (`SHOP` on `XTSE` CAD and `XNYS` USD) share one `instrument_id` and get two `listing_id`s. - **Stage B (`listing` & non-ISIN sources):** Assign primary `listing.mic` from EOD `Exchange` + QM `exchange`; attach IB `conid` at `(instrument_id, currency)` (resolving the 83% TSX-on-`AEQLIT` and >90% NYSE/Nasdaq-on-ATS `ibSymbols` problem). Match QM and CEO by `(normalized_ticker, mic, currency)` **requiring overlapping `[first_bar_date, last_bar_date]` spans** so reused tickers (`FB` 2012–2022 Meta vs `FB` 2025 ProShares ETF; CSE `CNX`/`CC` duplicates) never collide. diff --git a/studio.config.json b/studio.config.json index 8289bc2a..b425c1fc 100644 --- a/studio.config.json +++ b/studio.config.json @@ -11,7 +11,7 @@ } }, "test": { - "command": "bun --env-file=/home/boki/.studio/test-env/stock-bot.env test", + "command": "bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline", "env": {} }, "ci": "off", diff --git a/test/postgres/security-master-contract.test.ts b/test/postgres/security-master-contract.test.ts index c36c07c6..a15ebdfe 100644 --- a/test/postgres/security-master-contract.test.ts +++ b/test/postgres/security-master-contract.test.ts @@ -64,7 +64,7 @@ const ORIGINAL_CONTRACT_COLUMNS: Record = { 'instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id)', 'id_type VARCHAR(8) NOT NULL', 'id_value VARCHAR(16) NOT NULL', - 'valid_from DATE', + 'valid_from DATE NOT NULL', 'valid_to DATE', 'source VARCHAR(16) NOT NULL', 'PRIMARY KEY (id_type, id_value, valid_from)', diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index 134166f3..6146efae 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -266,6 +266,19 @@ describe('Environment safety & multi-env isolation', () => { ); }); + test('blocks leading-zero decimal and octal IPv4 loopback quads like 0127.0.0.1 and 0177.0.0.1 (T-37)', () => { + for (const host of ['0127.0.0.1', '00127.0.0.1', '0177.0.0.1', '00.00.00.00']) { + const cfg = makeConfig({ + environment: 'development', + mongoUri: `mongodb://trading_admin:pass@${host}:27017/stock`, + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } + }); + test('blocks multi-host MongoDB seed lists targeting QA loopback :27017 for dataIngestion and dataPipeline', () => { const qaFirstIngestion = makeConfig({ environment: 'development', diff --git a/test/unit/normalization-bar-spans-edge-cases.test.ts b/test/unit/normalization-bar-spans-edge-cases.test.ts index 0c7f3c1c..47136e24 100644 --- a/test/unit/normalization-bar-spans-edge-cases.test.ts +++ b/test/unit/normalization-bar-spans-edge-cases.test.ts @@ -230,10 +230,27 @@ describe('pipeline builder edge cases', () => { expect( (buildQmBarSpansPipeline()[2] as { $group: Record }).$group.barCount ).toEqual({ - $sum: 1, + $sum: { + $cond: [{ $ne: ['$normalizedDate', null] }, 1, 0], + }, }); }); + test('stored source IDs with leading/trailing spaces are not merged with trimmed IDs', async () => { + const reader: BarSpanAggregateReader = { + aggregate>(): T[] { + return [ + { _id: 'AAPL.US', firstBarDate: '2020-01-02', lastBarDate: '2024-12-31', barCount: 10 }, + { _id: ' AAPL.US ', firstBarDate: '2021-01-04', lastBarDate: '2022-12-30', barCount: 5 }, + ] as unknown as T[]; + }, + }; + const result = await computeBarSpans(reader, { sources: ['eod'] }); + expect(result.index.get('eod', 'AAPL.US')?.barCount).toBe(10); + expect(result.index.get('eod', ' AAPL.US ')?.barCount).toBe(5); + expect(result.index.sizeForSource('eod')).toBe(2); + }); + test('dispatcher rejects unknown sources', () => { expect(() => buildBarSpansPipeline('ib' as unknown as BarSpanSource)).toThrow(RangeError); }); diff --git a/test/unit/normalization-bar-spans.test.ts b/test/unit/normalization-bar-spans.test.ts index 18c3c78e..77afada0 100644 --- a/test/unit/normalization-bar-spans.test.ts +++ b/test/unit/normalization-bar-spans.test.ts @@ -122,7 +122,11 @@ describe('bar-span pipeline builders and safety guards', () => { _id: '$sourceId', firstBarDate: { $min: '$normalizedDate' }, lastBarDate: { $max: '$normalizedDate' }, - barCount: { $sum: 1 }, + barCount: { + $sum: { + $cond: [{ $ne: ['$normalizedDate', null] }, 1, 0], + }, + }, }, }); expect(eodTargeted).toHaveLength(3); @@ -253,6 +257,10 @@ describe('bar-span pipeline builders and safety guards', () => { const [left, right] = obj.$eq as [unknown, unknown]; return evalExpr(left, doc, vars) === evalExpr(right, doc, vars); } + if ('$ne' in obj) { + const [left, right] = obj.$ne as [unknown, unknown]; + return evalExpr(left, doc, vars) !== evalExpr(right, doc, vars); + } if ('$gte' in obj) { const [left, right] = obj.$gte as [unknown, unknown]; return (evalExpr(left, doc, vars) as number) >= (evalExpr(right, doc, vars) as number); @@ -269,6 +277,12 @@ describe('bar-span pipeline builders and safety guards', () => { return true; } if ('$cond' in obj) { + if (Array.isArray(obj.$cond)) { + const [condExpr, thenExpr, elseExpr] = obj.$cond as [unknown, unknown, unknown]; + return evalExpr(condExpr, doc, vars) + ? evalExpr(thenExpr, doc, vars) + : evalExpr(elseExpr, doc, vars); + } const cfg = obj.$cond as { if: unknown; then: unknown; else: unknown }; return evalExpr(cfg.if, doc, vars) ? evalExpr(cfg.then, doc, vars) @@ -425,7 +439,14 @@ describe('bar-span pipeline builders and safety guards', () => { } out[field] = maxVal; } else if ('$sum' in accObj) { - out[field] = bucket.length; + let total = 0; + for (const doc of bucket) { + const val = evalExpr(accObj.$sum, doc); + if (typeof val === 'number') { + total += val; + } + } + out[field] = total; } } grouped.push(out); @@ -490,7 +511,7 @@ describe('bar-span pipeline builders and safety guards', () => { sourceId: 'TZLESS_EXTREMUM.US', firstBarDate: '2024-06-03', lastBarDate: '2024-06-07', - barCount: 5, + barCount: 2, }); expect(result.index.get('qm', 'MIXED:TO')).toEqual({ source: 'qm', @@ -505,7 +526,7 @@ describe('bar-span pipeline builders and safety guards', () => { sourceId: 'QM_OLD:TO', firstBarDate: '2024-06-03', lastBarDate: '2024-06-07', - barCount: 3, + barCount: 2, }); // Must not falsely overlap a different listing starting June 10. expect( @@ -731,7 +752,8 @@ describe('computeBarSpans', () => { }); // 5 unique eod IDs at batchSize 2 => 3 batched queries (never 5 per-symbol queries) - expect(batchesSeen).toEqual([['A.US', 'B.US'], ['C.US', 'D.US'], ['E.US']]); + // Exact source IDs (including surrounding spaces) are preserved so stored IDs can be targeted. + expect(batchesSeen).toEqual([['A.US', ' B.US '], ['C.US', 'D.US'], ['E.US']]); expect(result.bySource.eod?.batchesRun).toBe(3); // Empty targeted list for qm must execute 0 queries (never fall back to a full collection scan) expect(result.bySource.qm?.batchesRun).toBe(0); diff --git a/test/unit/normalization-ticker.test.ts b/test/unit/normalization-ticker.test.ts index 81be365f..258cbb20 100644 --- a/test/unit/normalization-ticker.test.ts +++ b/test/unit/normalization-ticker.test.ts @@ -79,6 +79,15 @@ describe('parseTicker', () => { expect(parseTicker('..TO', 'ceo')).toBeNull(); }); + test('enforces listing.class_suffix VARCHAR(12) max length', () => { + expect(parseTicker('RY.ABCDEFGHIJKL', 'eod')).toEqual({ + tickerRoot: 'RY', + classSuffix: 'ABCDEFGHIJKL', + }); + expect(parseTicker('RY.ABCDEFGHIJKLM', 'eod')).toBeNull(); + expect(parseTicker('RY.PR.ABCDEFGHIJ', 'eod')).toBeNull(); + }); + test('completes 100,000 resolveIsin + parseTicker calls in under 500 ms', () => { const isinCorpus: readonly ResolveIsinInput[] = [ { isin: 'US0378331005' }, diff --git a/test/unit/security-master-exchange-pass1-edge-cases.test.ts b/test/unit/security-master-exchange-pass1-edge-cases.test.ts index b0195908..f345380d 100644 --- a/test/unit/security-master-exchange-pass1-edge-cases.test.ts +++ b/test/unit/security-master-exchange-pass1-edge-cases.test.ts @@ -116,6 +116,54 @@ describe('Pass 1 classifier edge cases', () => { ]); }); + test('routes source codes longer than 32 chars to unresolved and rejects them in SQL generation (T-44)', () => { + const exact32 = 'A'.repeat(32); + const tooLong33 = 'B'.repeat(33); + const result = classifySourceExchanges([ + { source: 'eod', code: exact32, operatingMic: 'XNAS' }, + { source: 'eod', code: tooLong33, operatingMic: 'XNAS' }, + ]); + + expect(result.mapped.map(row => row.sourceCode)).toEqual([exact32]); + expect(result.unresolved.map(row => [row.sourceCode, row.reason])).toEqual([ + [tooLong33, 'source_code_too_long'], + ]); + + expect(() => + generateExchangeSeedSql({ + mappings: [ + { + source: 'eod', + sourceCode: tooLong33, + role: 'primary_venue', + mic: 'XNAS', + countryIso: 'US', + method: 'operating_mic', + }, + ], + }) + ).toThrow(/length must be between 1 and 32/); + }); + + test('deduplicates identical (source, source_code) rows and rejects conflicting duplicates in SQL generation (T-45)', () => { + const row = { + source: 'eod' as const, + sourceCode: 'NASDAQ', + role: 'primary_venue' as const, + mic: 'XNAS', + countryIso: 'US', + method: 'operating_mic' as const, + }; + const sql = generateExchangeSeedSql({ mappings: [row, { ...row }] }); + expect(sql.match(/'eod', 'NASDAQ'/g)).toHaveLength(1); + + expect(() => + generateExchangeSeedSql({ + mappings: [row, { ...row, mic: 'XNYS' }], + }) + ).toThrow(/Conflicting duplicate exchange_source_map row/); + }); + test('classification output is identical for every rotation of the input', () => { const records = [ { source: 'eod' as const, code: 'TO', operatingMic: 'XTSE', name: 'Toronto' },