T-40: M1.1c — Pass 1 exchanges: ISO MIC seed, source-code role classifier and reviewable seed-SQL generator

This commit is contained in:
Studio 2026-11-27 15:19:40 -05:00
parent d0d2ebdfc8
commit dcca90004d
7 changed files with 115 additions and 21 deletions

View file

@ -53,4 +53,4 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@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`.

View file

@ -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 };
}

View file

@ -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 {

View file

@ -1,6 +1,7 @@
export {
classifySourceExchanges,
compareAscii,
compareUnresolvedExchangeRecords,
EXCHANGE_SOURCES,
EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
EXPLICIT_EXCHANGE_SOURCE_RULES,

View file

@ -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;

View file

@ -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',
});
});
});

View file

@ -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: [