From dcca90004dde1ef2101aff8d6db4af05c64f5179 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 15:19:40 -0500 Subject: [PATCH] =?UTF-8?q?T-40:=20M1.1c=20=E2=80=94=20Pass=201=20exchange?= =?UTF-8?q?s:=20ISO=20MIC=20seed,=20source-code=20role=20classifier=20and?= =?UTF-8?q?=20reviewable=20seed-SQL=20generator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 2 +- .../src/security-master/exchange-pass1.ts | 26 +++++--- .../src/security-master/exchange-seed-sql.ts | 14 ++-- .../src/security-master/index.ts | 1 + .../init/35-security-master-exchange-seed.sql | 3 +- .../security-master-exchange-seed.test.ts | 65 +++++++++++++++++++ .../security-master-exchange-pass1.test.ts | 25 +++++++ 7 files changed, 115 insertions(+), 21 deletions(-) diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 921a8cb6..60fd07a6 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -53,4 +53,4 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto ``` - **Read-only guarantee:** The CLI initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` with `readOnly: true`, performs zero MongoDB writes, and performs zero PostgreSQL writes. -- **Review workflow:** Inspect `./tmp/pass1-unresolved-exchanges.md` for unresolved codes (unknown MICs, multi-valued `OperatingMIC`, missing MICs), add approved mappings to `EXPLICIT_EXCHANGE_SOURCE_RULES` (or `database/postgres/init/35-security-master-exchange-seed.sql` with `reviewed_by` set as appropriate), and commit the reviewed SQL. Re-applying the migration never overwrites rows where `reviewed_by IS NOT NULL`. +- **Review and upgrade workflow:** Keep `database/postgres/init/35-security-master-exchange-seed.sql` immutable as the reproducible Pass 1 baseline—`runPostgresMigrations` records applied filenames in `migrations` and skips any file it has already run, so editing migration `35` in place would not reach databases that already applied it. Instead, inspect `./tmp/pass1-unresolved-exchanges.md` for unresolved codes (unknown MICs, multi-valued `OperatingMIC`, missing MICs), add approved additions or corrections as a **new** numbered migration under `database/postgres/init/` (for example `36-security-master-exchange-overrides.sql`, setting `reviewed_by` on director-approved rows) and register it in `MASTER_FILES` in `libs/data/postgres/src/migrations.ts` (also updating `EXPLICIT_EXCHANGE_SOURCE_RULES` if future generator runs should classify those codes explicitly). Verify the upgrade against a schema where migration `35` has already run—not only a fresh schema—confirming the new migration applies cleanly and that re-applying the baseline never overwrites rows where `reviewed_by IS NOT NULL`. 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 b66e49e2..6ff61115 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts @@ -88,6 +88,22 @@ export function compareAscii(a: string, b: string): number { return 0; } +export function compareUnresolvedExchangeRecords( + a: UnresolvedExchangeRecord, + b: UnresolvedExchangeRecord +): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceCode, b.sourceCode) || + compareAscii(a.reason, b.reason) || + compareAscii(a.rawCode, b.rawCode) || + compareAscii(a.operatingMic ?? '', b.operatingMic ?? '') || + compareAscii(a.name ?? '', b.name ?? '') || + compareAscii(a.country ?? '', b.country ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') + ); +} + export function isExchangeSource(value: unknown): value is ExchangeSource { return typeof value === 'string' && VALID_EXCHANGE_SOURCE_SET.has(value); } @@ -469,15 +485,7 @@ export function classifySourceExchanges( (a, b) => compareAscii(a.source, b.source) || compareAscii(a.sourceCode, b.sourceCode) ); - unresolved.sort( - (a, b) => - compareAscii(a.source, b.source) || - compareAscii(a.sourceCode, b.sourceCode) || - compareAscii(a.reason, b.reason) || - compareAscii(a.rawCode, b.rawCode) || - compareAscii(a.operatingMic ?? '', b.operatingMic ?? '') || - compareAscii(a.name ?? '', b.name ?? '') - ); + unresolved.sort(compareUnresolvedExchangeRecords); return { mapped, unresolved }; } 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 b7c19790..15519573 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,5 +1,6 @@ import { compareAscii, + compareUnresolvedExchangeRecords, type ExchangeClassificationResult, type ExchangeSeedRow, type ExchangeSourceMapRow, @@ -81,7 +82,8 @@ export function generateExchangeSeedSql(input: GenerateExchangeSeedSqlInput): st ' role = EXCLUDED.role,', ' mic = EXCLUDED.mic,', ' country_iso = EXCLUDED.country_iso,', - ' method = EXCLUDED.method', + ' method = EXCLUDED.method,', + ' reviewed_by = EXCLUDED.reviewed_by', 'WHERE exchange_source_map.reviewed_by IS NULL;', ].join('\n') ); @@ -100,15 +102,7 @@ function escapeMarkdownCell(value: string | null | undefined): string { function sortUnresolvedForReport( records: readonly UnresolvedExchangeRecord[] ): UnresolvedExchangeRecord[] { - return [...records].sort( - (a, b) => - compareAscii(a.source, b.source) || - compareAscii(a.sourceCode, b.sourceCode) || - compareAscii(a.reason, b.reason) || - compareAscii(a.rawCode, b.rawCode) || - compareAscii(a.operatingMic ?? '', b.operatingMic ?? '') || - compareAscii(a.name ?? '', b.name ?? '') - ); + return [...records].sort(compareUnresolvedExchangeRecords); } export function generateUnresolvedExchangesMarkdown(result: ExchangeClassificationResult): string { diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 61bbdce2..1a40e633 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -1,6 +1,7 @@ export { classifySourceExchanges, compareAscii, + compareUnresolvedExchangeRecords, EXCHANGE_SOURCES, EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, EXPLICIT_EXCHANGE_SOURCE_RULES, diff --git a/database/postgres/init/35-security-master-exchange-seed.sql b/database/postgres/init/35-security-master-exchange-seed.sql index 21f6a6fd..b6034671 100644 --- a/database/postgres/init/35-security-master-exchange-seed.sql +++ b/database/postgres/init/35-security-master-exchange-seed.sql @@ -40,5 +40,6 @@ ON CONFLICT (source, source_code) DO UPDATE SET role = EXCLUDED.role, mic = EXCLUDED.mic, country_iso = EXCLUDED.country_iso, - method = EXCLUDED.method + method = EXCLUDED.method, + reviewed_by = EXCLUDED.reviewed_by WHERE exchange_source_map.reviewed_by IS NULL; diff --git a/test/postgres/security-master-exchange-seed.test.ts b/test/postgres/security-master-exchange-seed.test.ts index 7e3c59cf..60ae5010 100644 --- a/test/postgres/security-master-exchange-seed.test.ts +++ b/test/postgres/security-master-exchange-seed.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, test } from 'bun:test'; import { Pool } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { generateExchangeSeedSql } from '../../apps/stock/data-pipeline/src/security-master'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('security-master-exchange-seed-test'); @@ -224,4 +225,68 @@ describe.skipIf(!url)('security master Pass 1 exchange seed migration', () => { expect(await countRows()).toEqual(initialCounts); }); + + test('reviewed follow-up SQL promotes an existing unreviewed row with reviewed_by and survives baseline re-apply', async () => { + const f = await createIsolatedFixture(); + const baselineSql = readFileSync(exchangeSeedSqlPath, 'utf8'); + + const followUpSql = generateExchangeSeedSql({ + mappings: [ + { + source: 'eod', + sourceCode: 'US', + role: 'primary_venue', + mic: 'XNYS', + countryIso: 'US', + method: 'explicit_rule', + reviewedBy: 'director', + }, + { + source: 'qm', + sourceCode: 'TSX', + role: 'primary_venue', + mic: 'XTSE', + countryIso: 'CA', + method: 'explicit_rule', + reviewedBy: 'director', + }, + ], + }); + + // Apply reviewed follow-up after migration 35 has already run + await f.pool.query(followUpSql); + + // Re-apply baseline migration 35; promoted and added reviewed rows must remain intact + await f.pool.query(baselineSql); + + const promotedRow = ( + await f.pool.query( + `SELECT role, mic, country_iso, method, reviewed_by + FROM exchange_source_map + WHERE source = 'eod' AND source_code = 'US'` + ) + ).rows[0]; + expect(promotedRow).toEqual({ + role: 'primary_venue', + mic: 'XNYS', + country_iso: 'US', + method: 'explicit_rule', + reviewed_by: 'director', + }); + + const addedRow = ( + await f.pool.query( + `SELECT role, mic, country_iso, method, reviewed_by + FROM exchange_source_map + WHERE source = 'qm' AND source_code = 'TSX'` + ) + ).rows[0]; + expect(addedRow).toEqual({ + role: 'primary_venue', + mic: 'XTSE', + country_iso: 'CA', + method: 'explicit_rule', + reviewed_by: 'director', + }); + }); }); diff --git a/test/unit/security-master-exchange-pass1.test.ts b/test/unit/security-master-exchange-pass1.test.ts index 1f471b5a..228e84a1 100644 --- a/test/unit/security-master-exchange-pass1.test.ts +++ b/test/unit/security-master-exchange-pass1.test.ts @@ -335,6 +335,31 @@ describe('security master Pass 1 SQL and Markdown generator', () => { expect(mdA).toContain('Pipe \\| Name Line2'); }); + test('breaks ties on country and currency for shuffled missing-code records with identical name and MIC', () => { + const recordsA: SourceExchangeRecord[] = [ + { source: 'qm', code: '', name: 'Unnamed Venue', operatingMic: null, country: 'US', currency: 'USD' }, + { source: 'qm', code: '', name: 'Unnamed Venue', operatingMic: null, country: 'US', currency: 'CAD' }, + { source: 'qm', code: '', name: 'Unnamed Venue', operatingMic: null, country: 'CA', currency: 'CAD' }, + ]; + const recordsB: SourceExchangeRecord[] = [recordsA[2]!, recordsA[0]!, recordsA[1]!]; + + const resA = classifySourceExchanges(recordsA); + const resB = classifySourceExchanges(recordsB); + + expect(resA.unresolved).toEqual(resB.unresolved); + expect(resA.unresolved.map(row => [row.country, row.currency])).toEqual([ + ['CA', 'CAD'], + ['US', 'CAD'], + ['US', 'USD'], + ]); + + const mdA = generateUnresolvedExchangesMarkdown(resA); + const mdB = generateUnresolvedExchangesMarkdown(resB); + expect(mdA).toBe(mdB); + expect(mdA.indexOf('| CA | CAD |')).toBeLessThan(mdA.indexOf('| US | CAD |')); + expect(mdA.indexOf('| US | CAD |')).toBeLessThan(mdA.indexOf('| US | USD |')); + }); + test('escapes single quotes in generated SQL values', () => { const sql = generateExchangeSeedSql({ exchanges: [