From c9ab13d5a3276525bc80fe62cb174ab1bc27e96d Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 4 Dec 2026 14:09:44 -0500 Subject: [PATCH] =?UTF-8?q?T-211:=20M2.2v=20=E2=80=94=20Export=20listing?= =?UTF-8?q?=5Fvenues.tsv=20and=20extend=20field-shape=20probe=20&=20BSON?= =?UTF-8?q?=20fixture=20exporter=20for=20M2=20collections?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../security-master/export-curate-inputs.ts | 186 +++++++++++++- .../src/security-master/export-raw-bson.ts | 13 +- .../src/security-master/index.ts | 8 + .../probe-source-field-shapes.ts | 101 +++++++- .../run-export-curate-inputs.ts | 3 +- .../security-master/run-export-raw-bson.ts | 4 +- .../security-master/source-field-shapes.ts | 6 + .../test/export-raw-bson.test.ts | 59 ++++- .../test/run-export-raw-bson.test.ts | 46 +++- .../test/source-field-shapes.test.ts | 222 +++++++++++++++- ...curity-master-export-curate-inputs.test.ts | 233 ++++++++++++++++- ...curity-master-export-curate-inputs.test.ts | 237 ++++++++++++++++-- 12 files changed, 1047 insertions(+), 71 deletions(-) diff --git a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts index 299bac4d..d2d38570 100644 --- a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts +++ b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts @@ -20,9 +20,34 @@ import type { SecurityMasterQueryable } from './persist'; export const CURATE_INPUT_FILES = Object.freeze({ providerMapping: 'provider_mapping.tsv', listingCurrencies: 'listing_currencies.tsv', + listingVenues: 'listing_venues.tsv', delistings: 'delistings.tsv', } as const); +export const LISTING_STATUTORY_LAG_VENUES = Object.freeze(['us_tsx', 'tsxv_cse'] as const); + +export type ListingStatutoryLagVenue = (typeof LISTING_STATUTORY_LAG_VENUES)[number]; + +/** + * Maps ISO 10383 exchange MICs in `ISO_EXCHANGE_SEEDS` to `curate-fundamentals` statutory-lag + * classes (`us_tsx`: +45d quarterly / +90d annual; `tsxv_cse`: +60d quarterly / +120d annual). + */ +export const LISTING_VENUE_BY_MIC: Readonly> = Object.freeze( + { + ARCX: 'us_tsx', + BATS: 'us_tsx', + IEXG: 'us_tsx', + NEOE: 'us_tsx', + OTCM: 'us_tsx', + XASE: 'us_tsx', + XCNQ: 'tsxv_cse', + XNAS: 'us_tsx', + XNYS: 'us_tsx', + XTSE: 'us_tsx', + XTSX: 'tsxv_cse', + } +); + export const CURATE_INPUT_GENERATIONS_DIR = 'generations'; export const CURATE_INPUT_CURRENT_LINK = 'current'; export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock'; @@ -50,6 +75,9 @@ export type CurateInputExportErrorCode = | 'OVERLAPPING_PROVIDER_MAPPING' | 'UNSORTED_PROVIDER_MAPPING_STREAM' | 'DUPLICATE_LISTING_CURRENCY' + | 'UNKNOWN_LISTING_MIC' + | 'INVALID_LISTING_VENUE' + | 'DUPLICATE_LISTING_VENUE' | 'UNSORTED_LISTING_STREAM' | 'INVALID_TERMINAL_RETURN' | 'INVALID_DELISTING_OUTCOME' @@ -105,6 +133,11 @@ export interface ListingCurrencyExportRow { readonly currency: string; } +export interface ListingVenueExportRow { + readonly listingId: number; + readonly venue: ListingStatutoryLagVenue; +} + export interface DelistingExportRow { readonly sourceId: string; readonly delistDate: string; @@ -189,6 +222,7 @@ export interface PinnedCurateInputSnapshot { readonly generationDir: string; readonly providerMapping: string; readonly listingCurrencies: string; + readonly listingVenues: string; readonly delistings: string; } @@ -201,6 +235,7 @@ export interface ExportCurateInputsResult { readonly delistingMappingSource: string; readonly providerMapping: ExportCurateInputsFileStats; readonly listingCurrencies: ExportCurateInputsFileStats; + readonly listingVenues: ExportCurateInputsFileStats; readonly delistings: ExportCurateInputsFileStats & { readonly stats: DelistingExportStats; }; @@ -232,6 +267,7 @@ interface DbContinuityRow { interface DbListingRow { listing_id: number; + mic: string | null; currency: string | null; listed_to: string | null; delist_reason: string | null; @@ -596,6 +632,95 @@ export function formatListingCurrenciesTsv(rows: readonly ListingCurrencyExportR return joinLinesInChunks(lines); } +/** + * Resolves a persisted ISO 10383 `listing.mic` to its `curate-fundamentals` statutory-lag venue + * class (`us_tsx` vs `tsxv_cse`). Fails closed on blank, control-character, whitespace-padded, + * prototype-key, or unmapped MIC values. + */ +export function resolveListingVenueForMic( + mic: unknown, + table = 'listing', + key = 'mic' +): ListingStatutoryLagVenue { + const validatedMic = assertNonBlankVerbatim(mic, table, key, 'mic'); + const venue = Object.hasOwn(LISTING_VENUE_BY_MIC, validatedMic) + ? LISTING_VENUE_BY_MIC[validatedMic] + : undefined; + if (venue === undefined) { + throw new CurateInputExportError({ + code: 'UNKNOWN_LISTING_MIC', + table, + key, + field: 'mic', + detail: `unknown listing mic "${validatedMic}" (expected one of: ${Object.keys(LISTING_VENUE_BY_MIC).join(', ')})`, + }); + } + return venue; +} + +function assertListingVenue( + value: unknown, + table: string, + key: string, + field: string +): ListingStatutoryLagVenue { + if (typeof value === 'string') { + assertNoTsvControlChars(value, table, key, field); + } + if (value !== 'us_tsx' && value !== 'tsxv_cse') { + throw new CurateInputExportError({ + code: 'INVALID_LISTING_VENUE', + table, + key, + field, + detail: `invalid ${field} "${String(value)}" (expected one of: ${LISTING_STATUTORY_LAG_VENUES.join(', ')})`, + }); + } + return value; +} + +/** + * Validates, sorts by ascending `listing_id`, rejects duplicate `listing_id`s, and formats + * `listing_venues.tsv`. Headerless 2-column TSV: `listing_id\tvenue` (`us_tsx` | `tsxv_cse`), + * matching `tools/curate-etl/src/run_curate_fundamentals.rs::load_listing_venues_tsv`. + */ +export function formatListingVenuesTsv(rows: readonly ListingVenueExportRow[]): string { + if (rows.length === 0) { + return ''; + } + + const validated: ListingVenueExportRow[] = []; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row === undefined) { + continue; + } + const listingId = assertPositiveI32(row.listingId, 'listing', `row#${i}`, 'listing_id'); + const venue = assertListingVenue(row.venue, 'listing', `listing_id=${listingId}`, 'venue'); + validated.push({ listingId, venue }); + } + + validated.sort((a, b) => a.listingId - b.listingId); + + const lines: string[] = []; + let prevListingId: number | undefined; + for (const curr of validated) { + if (prevListingId === curr.listingId) { + throw new CurateInputExportError({ + code: 'DUPLICATE_LISTING_VENUE', + table: 'listing', + key: `listing_id=${curr.listingId}`, + field: 'listing_id', + detail: `duplicate listing_id ${curr.listingId} in listing_venues`, + }); + } + lines.push(`${curr.listingId}\t${curr.venue}`); + prevListingId = curr.listingId; + } + + return joinLinesInChunks(lines); +} + function validateDelistingExportRow(row: DelistingExportRow, index: number): ValidatedDelistingRow { const fallbackKey = `row#${index}`; const sourceId = assertNonBlankVerbatim(row.sourceId, 'delistings', fallbackKey, 'source_id'); @@ -1189,7 +1314,7 @@ async function acquirePublishLock( /** * Resolves and pins the currently active immutable generation directory via `/current` - * before a consumer opens any TSV file. All three returned paths belong to the same atomic + * before a consumer opens any TSV file. All four returned paths belong to the same atomic * PostgreSQL snapshot and remain immutable even if a concurrent export refreshes `/current`. */ export async function pinCurateInputSnapshot( @@ -1216,6 +1341,7 @@ export async function pinCurateInputSnapshot( generationDir, providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(generationDir, CURATE_INPUT_FILES.listingVenues), delistings: join(generationDir, CURATE_INPUT_FILES.delistings), }; } @@ -1225,7 +1351,7 @@ export async function pinCurateInputSnapshot( * transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable * generation directory under `/generations/`, and atomically commits * `/current` (plus top-level symlinks `provider_mapping.tsv`, `listing_currencies.tsv`, - * and `delistings.tsv` pointing through `current/`). + * `listing_venues.tsv`, and `delistings.tsv` pointing through `current/`). */ export async function exportCurateInputs( queryable: SecurityMasterQueryable, @@ -1299,31 +1425,37 @@ export async function exportCurateInputs( const targets = { providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(outDir, CURATE_INPUT_FILES.listingVenues), delistings: join(outDir, CURATE_INPUT_FILES.delistings), }; const stagedFiles = { providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(stagingDir, CURATE_INPUT_FILES.listingVenues), delistings: join(stagingDir, CURATE_INPUT_FILES.delistings), }; const generationFiles = { providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping), listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies), + listingVenues: join(generationDir, CURATE_INPUT_FILES.listingVenues), delistings: join(generationDir, CURATE_INPUT_FILES.delistings), }; const backups = { providerMapping: `${targets.providerMapping}.${runTag}.bak`, listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`, + listingVenues: `${targets.listingVenues}.${runTag}.bak`, delistings: `${targets.delistings}.${runTag}.bak`, }; const linkTemps = { providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`, listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`, + listingVenues: `${targets.listingVenues}.${runTag}.link.tmp`, delistings: `${targets.delistings}.${runTag}.link.tmp`, }; let providerMappingHandle: FileHandle | null = null; let listingCurrenciesHandle: FileHandle | null = null; + let listingVenuesHandle: FileHandle | null = null; let delistingsHandle: FileHandle | null = null; let providerMappingRowsIn = 0; @@ -1334,11 +1466,20 @@ export async function exportCurateInputs( let listingCurrenciesRowsOut = 0; let listingCurrenciesBytes = 0; + let listingVenuesRowsIn = 0; + let listingVenuesRowsOut = 0; + let listingVenuesBytes = 0; + let delistingsBytes = 0; let delistingsStats!: DelistingExportStats; - type PublishKey = 'providerMapping' | 'listingCurrencies' | 'delistings'; - const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings']; + type PublishKey = 'providerMapping' | 'listingCurrencies' | 'listingVenues' | 'delistings'; + const publishOrder: PublishKey[] = [ + 'providerMapping', + 'listingCurrencies', + 'listingVenues', + 'delistings', + ]; let stagingCreated = false; let publishLockAcquired = false; @@ -1353,6 +1494,7 @@ export async function exportCurateInputs( providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx'); listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx'); + listingVenuesHandle = await fsOpen(stagedFiles.listingVenues, 'wx'); delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx'); const otcByFromListingId = new Map(); @@ -1481,7 +1623,7 @@ export async function exportCurateInputs( } } - // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv directly. + // 2. Keyset-paginated read of listing -> stream listing_currencies.tsv and listing_venues.tsv directly. let lastListingId: number | null = null; for (;;) { const res = @@ -1489,6 +1631,7 @@ export async function exportCurateInputs( ? await queryable.query( `SELECT listing_id, + mic, btrim(currency) AS currency, to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, @@ -1501,6 +1644,7 @@ export async function exportCurateInputs( : await queryable.query( `SELECT listing_id, + mic, btrim(currency) AS currency, to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, @@ -1517,6 +1661,7 @@ export async function exportCurateInputs( } const chunkLines: string[] = []; + const venueChunkLines: string[] = []; for (const row of res.rows) { const listingId = assertPositiveI32( row.listing_id, @@ -1548,9 +1693,13 @@ export async function exportCurateInputs( } const currency = assertNonBlankVerbatim(row.currency, 'listing', listingKey, 'currency'); + const venue = resolveListingVenueForMic(row.mic, 'listing', listingKey); chunkLines.push(`${listingId}\t${currency}`); + venueChunkLines.push(`${listingId}\t${venue}`); listingCurrenciesRowsIn += 1; listingCurrenciesRowsOut += 1; + listingVenuesRowsIn += 1; + listingVenuesRowsOut += 1; const otc = otcByFromListingId.get(listingId); const hasTerminalReturn = @@ -1607,6 +1756,11 @@ export async function exportCurateInputs( await writeAll(listingCurrenciesHandle, buf); listingCurrenciesBytes += buf.byteLength; + const venueChunkText = `${venueChunkLines.join('\n')}\n`; + const venueBuf = Buffer.from(venueChunkText, 'utf8'); + await writeAll(listingVenuesHandle, venueBuf); + listingVenuesBytes += venueBuf.byteLength; + if (res.rows.length < chunkSize) { break; } @@ -1842,7 +1996,7 @@ export async function exportCurateInputs( }, }; - // 5. Sync and close all three staged files before atomic generation publish. + // 5. Sync and close all four staged files before atomic generation publish. await providerMappingHandle.sync(); await providerMappingHandle.close(); providerMappingHandle = null; @@ -1851,6 +2005,10 @@ export async function exportCurateInputs( await listingCurrenciesHandle.close(); listingCurrenciesHandle = null; + await listingVenuesHandle.sync(); + await listingVenuesHandle.close(); + listingVenuesHandle = null; + await delistingsHandle.sync(); await delistingsHandle.close(); delistingsHandle = null; @@ -1915,7 +2073,12 @@ export async function exportCurateInputs( currentTempCreated = false; } catch (error) { // Close any still-open staged file handles. - for (const handle of [providerMappingHandle, listingCurrenciesHandle, delistingsHandle]) { + for (const handle of [ + providerMappingHandle, + listingCurrenciesHandle, + listingVenuesHandle, + delistingsHandle, + ]) { if (handle !== null) { await handle.close().catch(() => {}); } @@ -2027,6 +2190,12 @@ export async function exportCurateInputs( rowsOut: listingCurrenciesRowsOut, bytesWritten: listingCurrenciesBytes, }, + listingVenues: { + path: generationFiles.listingVenues, + rowsIn: listingVenuesRowsIn, + rowsOut: listingVenuesRowsOut, + bytesWritten: listingVenuesBytes, + }, delistings: { path: generationFiles.delistings, rowsIn: delistingsStats.rowsIn, @@ -2034,7 +2203,8 @@ export async function exportCurateInputs( bytesWritten: delistingsBytes, stats: delistingsStats, }, - totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes, + totalBytesWritten: + providerMappingBytes + listingCurrenciesBytes + listingVenuesBytes + delistingsBytes, cleanupWarnings, }; } diff --git a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts index 8ba7e632..bfa6a765 100644 --- a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts +++ b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts @@ -4,9 +4,10 @@ import { join } from 'node:path'; import type { MongoDBClient } from '@stock-bot/mongodb'; /** - * M1 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by + * M1+M2 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by * `tools/curate-etl` (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, - * `curate-fx-1d`, `curate-shorts`, `curate-events`). + * `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-fundamentals`, `curate-sentiment`, + * `curate-macro`, `curate-intraday`). */ export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([ 'eodPrices', @@ -17,6 +18,12 @@ export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([ 'ceoShorts', 'qmFilings', 'qmEarnings', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', ] as const); export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number]; @@ -390,7 +397,7 @@ function validateExportOptions(options: ExportRawBsonCollectionOptions): Validat throw new RawBsonExportError({ code: 'DISALLOWED_COLLECTION', collection: collectionName || '', - detail: `collection "${collectionName}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, + detail: `collection "${collectionName}" is not in the M1+M2 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, }); } diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 85707ca8..feecc13e 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -60,11 +60,15 @@ export { exportCurateInputs, formatDelistingsTsv, formatListingCurrenciesTsv, + formatListingVenuesTsv, formatPlainDecimal, formatProviderMappingTsv, isValidStrictYmd, + LISTING_STATUTORY_LAG_VENUES, + LISTING_VENUE_BY_MIC, MAX_EXPORT_CHUNK_SIZE, pinCurateInputSnapshot, + resolveListingVenueForMic, type BuildDelistingExportRowsOptions, type BuildDelistingExportRowsResult, type ContinuityExportSourceRow, @@ -79,6 +83,8 @@ export { type ExportCurateInputsResult, type ListingCurrencyExportRow, type ListingDelistingSourceRow, + type ListingStatutoryLagVenue, + type ListingVenueExportRow, type PinnedCurateInputSnapshot, type ProviderMappingExportRow, } from './export-curate-inputs'; @@ -360,11 +366,13 @@ export { } from './security-type'; export { + assertProbeSourceFieldShapesSafety, parseProbeSourceFieldShapesArgs, PROBE_SOURCE_FIELD_SHAPES_USAGE, runCli as runProbeSourceFieldShapesCli, runSourceFieldShapesProbe, type ParsedProbeSourceFieldShapesArgs, + type RunProbeSourceFieldShapesCliOverrides, type RunSourceFieldShapesProbeDeps, type RunSourceFieldShapesProbeOptions, type RunSourceFieldShapesProbeOutput, diff --git a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts index b3fbcfca..f0bd0a8c 100644 --- a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts +++ b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts @@ -2,7 +2,11 @@ import { mkdir, writeFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { getLogger } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; -import { initializeStockConfig } from '@stock-bot/stock-config'; +import { + assertEnvironmentSafety, + initializeStockConfig, + type StockAppConfig, +} from '@stock-bot/stock-config'; import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; import { DEFAULT_FIELD_SHAPE_LIMIT, @@ -45,6 +49,22 @@ export interface RunSourceFieldShapesProbeDeps { readonly writeStdout?: (text: string) => void; } +export interface RunProbeSourceFieldShapesCliOverrides { + readonly initializeConfig?: typeof initializeStockConfig; + readonly assertSafety?: () => void; + readonly createMongoClient?: () => + | Promise<{ + readonly client: ReadOnlyMongoCollectionClient; + readonly close: () => Promise | void; + }> + | { + readonly client: ReadOnlyMongoCollectionClient; + readonly close: () => Promise | void; + }; + readonly writeFile?: (filePath: string, content: string) => Promise | void; + readonly writeStdout?: (text: string) => void; +} + export interface RunSourceFieldShapesProbeOptions { readonly outPath: string; readonly limit?: number; @@ -256,23 +276,86 @@ export async function runSourceFieldShapesProbe( return output; } -export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { +export function assertProbeSourceFieldShapesSafety( + config: StockAppConfig, + env: Record = process.env +): void { + const mongo = config.database.mongodb; + if (!mongo.enabled) { + throw new Error('MongoDB is disabled in configuration; cannot probe source field shapes'); + } + if (mongo.readOnly !== true) { + throw new Error( + 'Source field-shape probe requires read-only MongoDB configuration (database.mongodb.readOnly === true)' + ); + } + + const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env; + const mongoOnlyConfig: StockAppConfig = { + ...config, + database: { + ...config.database, + postgres: { + ...config.database.postgres, + enabled: false, + }, + }, + }; + assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv); +} + +export async function runCli( + argv: readonly string[] = process.argv.slice(2), + overrides?: RunProbeSourceFieldShapesCliOverrides +): Promise { const parsed = parseProbeSourceFieldShapesArgs(argv); if (parsed.help) { - process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); + const writeStdout = + overrides?.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); return; } const logger = getLogger('source-field-shapes-probe'); - const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); - const mongoConfig = resolveReadOnlyMongoClientConfig(config); - const mongo = new MongoDBClient(mongoConfig, logger); + const initConfig = overrides?.initializeConfig ?? initializeStockConfig; + const config = initConfig('dataPipeline', { mongoReadOnly: true }); - await mongo.connect(); + const assertSafety = + overrides?.assertSafety ?? + (() => { + assertProbeSourceFieldShapesSafety(config, process.env); + }); + assertSafety(); + + const createMongoClient = + overrides?.createMongoClient ?? + (async () => { + const mongoConfig = resolveReadOnlyMongoClientConfig(config); + const mongo = new MongoDBClient(mongoConfig, logger); + await mongo.connect(); + let closed = false; + return { + client: mongo, + async close(): Promise { + if (closed) { + return; + } + closed = true; + await mongo.disconnect(); + }, + }; + }); + + const mongoHandle = await createMongoClient(); await runSourceFieldShapesProbe( { - mongoCollectionClient: mongo, - closeMongo: () => mongo.disconnect(), + mongoCollectionClient: mongoHandle.client, + closeMongo: mongoHandle.close, + writeFile: overrides?.writeFile, + writeStdout: overrides?.writeStdout, }, { outPath: parsed.outPath, diff --git a/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts index 38d15920..1f6afaf7 100644 --- a/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts +++ b/apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts @@ -21,7 +21,7 @@ export const EXPORT_CURATE_INPUTS_USAGE = [ 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir [--chunk-size ] [--help]', '', 'Options:', - ` --out-dir Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`, + ` --out-dir Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, ${CURATE_INPUT_FILES.listingVenues}, and ${CURATE_INPUT_FILES.delistings}.`, ` --chunk-size Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`, ' --help Show this help message and exit.', ].join('\n'); @@ -171,6 +171,7 @@ export function formatExportCurateInputsSummary(result: ExportCurateInputsResult `Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`, ` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`, ` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`, + ` ${CURATE_INPUT_FILES.listingVenues}: rows_in=${result.listingVenues.rowsIn} rows_out=${result.listingVenues.rowsOut} bytes=${result.listingVenues.bytesWritten}`, ` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`, ` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`, ]; diff --git a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts index 17ba87cf..a2092563 100644 --- a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts +++ b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts @@ -121,7 +121,7 @@ function parseCollectionsList(raw: string): RawBsonExportCollection[] { throw new RawBsonExportError({ code: 'DISALLOWED_COLLECTION', collection: trimmed, - detail: `collection "${trimmed}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, + detail: `collection "${trimmed}" is not in the M1+M2 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`, }); } if (seen.has(trimmed)) { @@ -327,7 +327,7 @@ export async function runExportRawBson( throw new RawBsonExportError({ code: 'DISALLOWED_COLLECTION', collection: String(collection), - detail: `collection "${String(collection)}" is not in the M1 allowlist`, + detail: `collection "${String(collection)}" is not in the M1+M2 allowlist`, }); } } diff --git a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts index da009d68..02f1a1bf 100644 --- a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts +++ b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts @@ -14,6 +14,12 @@ export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([ 'qmPrices', 'eodPrices', 'teMarketData', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', ] as const); export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]; diff --git a/apps/stock/data-pipeline/test/export-raw-bson.test.ts b/apps/stock/data-pipeline/test/export-raw-bson.test.ts index e1fc3b59..e1c856b6 100644 --- a/apps/stock/data-pipeline/test/export-raw-bson.test.ts +++ b/apps/stock/data-pipeline/test/export-raw-bson.test.ts @@ -446,12 +446,27 @@ describe('exportRawBsonCollection', () => { }; const fsHooks: ExportRawBsonFsHooks = { open: openMock }; - for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) { + for (const disallowed of [ + 'symbols', + 'eodSymbols', + 'eodFundamentalsOLD', + 'eodFinancialsOLD', + 'ttFutures', + ]) { await expect( exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks }) ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed }); } + await expect( + exportRawBsonCollection(source, { + collection: 'eodIntraday1M', + outDir: '/tmp/unused', + eodSymbol: 'AAPL.US', + fs: fsHooks, + }) + ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); + await expect( exportRawBsonCollection(source, { collection: 'teMarketData', @@ -650,7 +665,41 @@ describe('exportRawBsonCollection', () => { }); }); - test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { + test('exports all 6 M2 allowlisted collections including hyphenated qmFinancials-old.bson with valid BSON framing', async () => { + const m2Collections = [ + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ] as const; + + await withTempDir(async outDir => { + for (const collection of m2Collections) { + const doc = { collection, seq: 1 }; + const serialized = Uint8Array.from(BSON.serialize(doc)); + const source = createFakeSource([serialized]); + + const res = await exportRawBsonCollection(source, { collection, outDir }); + expect(res.collection).toBe(collection); + expect(res.outPath).toBe(join(outDir, `${collection}.bson`)); + expect(res.docsWritten).toBe(1); + expect(res.bytesWritten).toBe(serialized.byteLength); + + const bytes = Uint8Array.from(await readFile(res.outPath)); + const frames = walkRawBsonFrames(bytes); + expect(frames).toHaveLength(1); + expect(BSON.deserialize(frames[0]!)).toEqual(doc); + } + + expect((await readdir(outDir)).sort()).toEqual( + m2Collections.map(c => `${c}.bson`).sort() + ); + }); + }); + + test('exports exact M1+M2 allowlist of 14 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([ 'eodPrices', 'qmSplits', @@ -660,6 +709,12 @@ describe('exportRawBsonCollection', () => { 'ceoShorts', 'qmFilings', 'qmEarnings', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', ]); const emptyBson = new Uint8Array([5, 0, 0, 0, 0]); expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson); diff --git a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts index a0c6ab21..dea12280 100644 --- a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts +++ b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts @@ -102,6 +102,30 @@ describe('parseExportRawBsonArgs', () => { collections: [...RAW_BSON_EXPORT_COLLECTIONS], batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, }); + expect(parsedDefault.help).toBe(false); + if (!parsedDefault.help) { + expect(parsedDefault.collections).toHaveLength(14); + } + + const parsedM2 = parseExportRawBsonArgs([ + '--out-dir', + './tmp/m2', + '--collections', + 'qmFinancials,qmFinancials-old,ceoPosts,teData,eodIntraday1M,qmIntraday', + ]); + expect(parsedM2).toEqual({ + help: false, + outDir: './tmp/m2', + collections: [ + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ], + batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, + }); expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true }); }); @@ -149,12 +173,20 @@ describe('parseExportRawBsonArgs', () => { }); test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => { + for (const disallowed of [ + 'symbols', + 'eodSymbols', + 'eodFundamentalsOLD', + 'eodFinancialsOLD', + 'ttFutures', + ]) { + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', disallowed]) + ).toThrow(RawBsonExportError); + } expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M']) - ).toThrow(RawBsonExportError); - expect(() => - parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols']) - ).toThrow(RawBsonExportError); + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M', '--eod-symbol', 'AAPL.US']) + ).toThrow(/--eod-symbol is only permitted/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX']) ).toThrow(/--eod-symbol is only permitted/); @@ -193,7 +225,7 @@ describe('assertExportRawBsonSafety', () => { readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', readOnly: true, }), - {} + { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' } ) ).toThrow(/Safety guard/); }); @@ -350,7 +382,7 @@ describe('runExportRawBson & runCli', () => { }, { outDir: '/tmp/unused', - collections: ['eodIntraday1M' as never], + collections: ['eodFundamentalsOLD' as never], } ) ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' }); diff --git a/apps/stock/data-pipeline/test/source-field-shapes.test.ts b/apps/stock/data-pipeline/test/source-field-shapes.test.ts index 47e150e9..7882f452 100644 --- a/apps/stock/data-pipeline/test/source-field-shapes.test.ts +++ b/apps/stock/data-pipeline/test/source-field-shapes.test.ts @@ -1,9 +1,11 @@ -import { describe, expect, test } from 'bun:test'; +import { describe, expect, mock, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; +import type { StockAppConfig } from '@stock-bot/stock-config'; import type { ParserOptions } from 'prettier'; import * as markdownPlugin from 'prettier/plugins/markdown'; import { + assertProbeSourceFieldShapesSafety, DEFAULT_FIELD_SHAPE_LIMIT, DEFAULT_MAX_EXAMPLE_LENGTH, DEFAULT_MAX_EXAMPLES, @@ -13,8 +15,10 @@ import { MAX_EXAMPLES_CAP, MAX_FIELD_SHAPE_LIMIT, parseProbeSourceFieldShapesArgs, + PROBE_SOURCE_FIELD_SHAPES_USAGE, readFieldShapes, renderFieldShapesMarkdown, + runProbeSourceFieldShapesCli, runSourceFieldShapesProbe, STRING_PATTERN_CLASSES, summarizeFieldShapes, @@ -444,14 +448,31 @@ describe('readFieldShapes', () => { expect(amountField.typeCounts.double).toBe(2); }); - test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { + test('defaults to all 14 M1+M2 allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { + expect([...FIELD_SHAPE_PROBE_COLLECTIONS]).toEqual([ + 'ceoShorts', + 'qmSplits', + 'qmDividends', + 'qmFilings', + 'qmEarnings', + 'qmPrices', + 'eodPrices', + 'teMarketData', + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ]); + const { reader, calls } = createFakeReader({}); const result = await readFieldShapes(reader); expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT); expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES); expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH); - expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length); + expect(calls.length).toBe(14); for (const call of calls) { expect(call.options).toEqual({ limit: DEFAULT_FIELD_SHAPE_LIMIT, @@ -461,7 +482,45 @@ describe('readFieldShapes', () => { } }); - test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => { + test('probes all 6 M2 collections including hyphenated qmFinancials-old', async () => { + const m2Collections = [ + 'qmFinancials', + 'qmFinancials-old', + 'ceoPosts', + 'teData', + 'eodIntraday1M', + 'qmIntraday', + ] as const; + + const docsByCollection: Record[]> = { + qmFinancials: [{ qmSearchCode: 'AAPL', periodEndDate: '2024-09-30', revenue: 100 }], + 'qmFinancials-old': [{ qmSearchCode: 'SHOP:CA', periodEndDate: '2023-12-31', revenue: 50 }], + ceoPosts: [{ channel: 'abc', body: 'drilling update', createdAt: new Date('2025-01-02T14:30:00Z') }], + teData: [{ country: 'Canada', indicator: 'CPI', value: 2.1 }], + eodIntraday1M: [{ eodSearchCode: 'AAPL.US', timestamp: 1735828200, close: 243.5 }], + qmIntraday: [{ symbol: 'SHOP:CA', timestamp: '2025-01-02T14:30:00Z', close: 150.2 }], + }; + + const { reader, calls, closedCollections } = createFakeReader(docsByCollection); + const result = await readFieldShapes(reader, { + collections: m2Collections, + limit: 5, + }); + + expect(calls.map(c => c.collectionName)).toEqual([ + 'ceoPosts', + 'eodIntraday1M', + 'qmFinancials', + 'qmFinancials-old', + 'qmIntraday', + 'teData', + ]); + expect(closedCollections).toEqual(calls.map(c => c.collectionName)); + expect(result.totalDocsSampled).toBe(6); + expect(result.collections.map(c => c.collection)).toEqual(calls.map(c => c.collectionName)); + }); + + test('rejects invalid limit, unknown/quarantined collections, and non-read-only reader before any query', async () => { const nonRo = createFakeReader({}, { readOnly: false }); await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i); expect(nonRo.calls.length).toBe(0); @@ -476,16 +535,25 @@ describe('readFieldShapes', () => { await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError); expect(badLimitZero.calls.length).toBe(0); - const unknownCol = createFakeReader({}); - let caught: unknown; - try { - await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] }); - } catch (err) { - caught = err; + for (const disallowed of [ + 'notACollection', + 'symbols', + 'eodSymbols', + 'eodFundamentalsOLD', + 'eodFinancialsOLD', + 'ttFutures', + ]) { + const unknownCol = createFakeReader({}); + let caught: unknown; + try { + await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', disallowed] }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(UnknownProbeCollectionError); + expect((caught as UnknownProbeCollectionError).collectionName).toBe(disallowed); + expect(unknownCol.calls.length).toBe(0); } - expect(caught).toBeInstanceOf(UnknownProbeCollectionError); - expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection'); - expect(unknownCol.calls.length).toBe(0); }); test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => { @@ -809,4 +877,132 @@ describe('CLI arg parsing and headless probe runner', () => { expect(writtenFiles[0]!.content).toBe(output.markdown); expect(stdoutChunks.join('')).toContain('Documents sampled: 1'); }); + + test('assertProbeSourceFieldShapesSafety and runProbeSourceFieldShapesCli enforce mongoReadOnly: true and block QA write bypass', async () => { + const createConfig = ( + overrides: Partial = {} + ): StockAppConfig => + ({ + environment: 'development', + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5432, + database: 'trading_bot', + user: 'trading_user', + password: 'pw', + ssl: false, + poolSize: 5, + idleTimeout: 10000, + connectionTimeout: 5000, + }, + mongodb: { + enabled: true, + uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', + readOnly: true, + host: 'localhost', + port: 27017, + database: 'stock', + poolSize: 5, + ...overrides, + }, + dragonfly: { enabled: false, host: 'localhost', port: 6380 }, + questdb: { enabled: false, host: 'localhost', port: 9100 }, + }, + }) as unknown as StockAppConfig; + + // Allows read-only dev MongoDB even if Postgres config points to QA. + expect(() => assertProbeSourceFieldShapesSafety(createConfig(), {})).not.toThrow(); + + // Rejects disabled MongoDB, readOnly: false, and admin/writable QA MongoDB even with override env var. + expect(() => assertProbeSourceFieldShapesSafety(createConfig({ enabled: false }), {})).toThrow( + /MongoDB is disabled/ + ); + expect(() => assertProbeSourceFieldShapesSafety(createConfig({ readOnly: false }), {})).toThrow( + /read-only MongoDB configuration/ + ); + expect(() => + assertProbeSourceFieldShapesSafety( + createConfig({ + readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', + readOnly: true, + }), + { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' } + ) + ).toThrow(/Safety guard/); + + // --help performs zero config or Mongo I/O. + const helpStdout: string[] = []; + const initNeverMock = mock(() => { + throw new Error('initializeConfig must not be called on --help'); + }); + const clientNeverMock = mock(() => { + throw new Error('createMongoClient must not be called on --help'); + }); + await runProbeSourceFieldShapesCli(['--help'], { + initializeConfig: initNeverMock as never, + createMongoClient: clientNeverMock, + writeStdout: text => helpStdout.push(text), + }); + expect(helpStdout.join('')).toBe(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); + expect(initNeverMock).not.toHaveBeenCalled(); + expect(clientNeverMock).not.toHaveBeenCalled(); + + // Normal CLI run initializes config with mongoReadOnly: true and probes M2 collection. + const initCalls: Array<{ service: string; opts: unknown }> = []; + const written: Array<{ filePath: string; content: string }> = []; + const stdout: string[] = []; + let closed = 0; + + await runProbeSourceFieldShapesCli( + ['--out', './tmp/m2-probe.md', '--limit', '5', '--collections', 'qmFinancials-old,teData'], + { + initializeConfig: ((service: string, opts?: unknown) => { + initCalls.push({ service, opts }); + return createConfig(); + }) as never, + createMongoClient: async () => ({ + client: { + isReadOnly: () => true, + getCollection: (name: string) => ({ + find: () => ({ + async *[Symbol.asyncIterator]() { + yield { collectionTag: name, v: 1 }; + }, + async close() {}, + }), + }), + }, + close: () => { + closed += 1; + }, + }), + writeFile: (filePath, content) => { + written.push({ filePath, content }); + }, + writeStdout: text => { + stdout.push(text); + }, + } + ); + + expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]); + expect(closed).toBe(1); + expect(written).toHaveLength(1); + expect(written[0]!.filePath).toBe('./tmp/m2-probe.md'); + expect(written[0]!.content).toContain('qmFinancials-old'); + expect(written[0]!.content).toContain('teData'); + expect(stdout.join('')).toContain('Documents sampled: 2'); + + // Safety failure blocks createMongoClient. + await expect( + runProbeSourceFieldShapesCli(['--out', './tmp/blocked.md', '--collections', 'ceoPosts'], { + initializeConfig: (() => createConfig({ readOnly: false })) as never, + createMongoClient: clientNeverMock, + }) + ).rejects.toThrow(/read-only MongoDB configuration/); + expect(clientNeverMock).not.toHaveBeenCalled(); + }); }); diff --git a/test/postgres/security-master-export-curate-inputs.test.ts b/test/postgres/security-master-export-curate-inputs.test.ts index 51705ecd..822fd7a2 100644 --- a/test/postgres/security-master-export-curate-inputs.test.ts +++ b/test/postgres/security-master-export-curate-inputs.test.ts @@ -1,5 +1,5 @@ import { randomUUID } from 'node:crypto'; -import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, test } from 'bun:test'; @@ -7,6 +7,8 @@ import { Pool, type PoolClient } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { + CURATE_INPUT_FILES, + CurateInputExportError, exportCurateInputs, pinCurateInputSnapshot, type SecurityMasterQueryable, @@ -95,14 +97,21 @@ async function seedFixtureData(pool: Pool) { try { await client.query('BEGIN'); - // Ensure required MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent). + // Ensure all 11 ISO MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent). await client.query(` INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) VALUES + ('ARCX', 'XNYS', 'NYSE Arca', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('BATS', 'BATS', 'Cboe BZX Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('IEXG', 'IEXG', 'Investors Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('NEOE', 'NEOE', 'Cboe Canada (NEO Exchange)', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), + ('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XASE', 'XNYS', 'NYSE American', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), + ('XCNQ', 'XCNQ', 'Canadian Securities Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), ('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), ('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'), ('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'), - ('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100') + ('XTSX', 'XTSX', 'TSX Venture Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered') ON CONFLICT (mic) DO NOTHING `); @@ -132,6 +141,13 @@ async function seedFixtureData(pool: Pool) { const instNoListedTo = await insertInstrument('US0000000035', '000000003', 'No ListedTo Corp', 'common', 'US'); const instNoQm = await insertInstrument('US0000000043', '000000004', 'No QM Mapping Corp', 'common', 'US'); const instNoSuccQm = await insertInstrument('US0000000050', '000000005', 'No Succ QM Corp', 'common', 'US'); + const instArcx = await insertInstrument('US0000000068', '000000006', 'Arca ETF Corp', 'etf', 'US'); + const instXase = await insertInstrument('US0000000076', '000000007', 'American Corp', 'common', 'US'); + const instBats = await insertInstrument('US0000000084', '000000008', 'BZX ETF Corp', 'etf', 'US'); + const instIexg = await insertInstrument('US0000000092', '000000009', 'IEX Corp', 'common', 'US'); + const instNeoe = await insertInstrument('CA0000000109', '000000010', 'NEO Corp', 'common', 'CA'); + const instXtsx = await insertInstrument('CA0000000117', '000000011', 'Venture Mining Corp', 'common', 'CA'); + const instXcnq = await insertInstrument('CA0000000125', '000000012', 'CSE Junior Corp', 'common', 'CA'); const insertListing = async (params: { instrumentId: number; @@ -284,6 +300,76 @@ async function seedFixtureData(pool: Pool) { delistReason: null, terminalReturn: null, }); + const arcxId = await insertListing({ + instrumentId: instArcx, + mic: 'ARCX', + tickerRoot: 'ARCA', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const xaseId = await insertListing({ + instrumentId: instXase, + mic: 'XASE', + tickerRoot: 'AMEX', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const batsId = await insertListing({ + instrumentId: instBats, + mic: 'BATS', + tickerRoot: 'CBOE', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const iexgId = await insertListing({ + instrumentId: instIexg, + mic: 'IEXG', + tickerRoot: 'IEXX', + currency: 'USD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const neoeId = await insertListing({ + instrumentId: instNeoe, + mic: 'NEOE', + tickerRoot: 'NEOC', + currency: 'CAD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const xtsxId = await insertListing({ + instrumentId: instXtsx, + mic: 'XTSX', + tickerRoot: 'VMIN', + currency: 'CAD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); + const xcnqId = await insertListing({ + instrumentId: instXcnq, + mic: 'XCNQ', + tickerRoot: 'CSEJ', + currency: 'CAD', + listedFrom: '2020-01-02', + listedTo: null, + delistReason: 'active', + terminalReturn: null, + }); const insertMapping = async ( source: string, @@ -351,6 +437,13 @@ async function seedFixtureData(pool: Pool) { noQmId, noSuccQmFromId, noSuccQmToId, + arcxId, + xaseId, + batsId, + iexgId, + neoeId, + xtsxId, + xcnqId, }; } catch (error) { await client.query('ROLLBACK').catch(() => {}); @@ -402,6 +495,7 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* expect(pinned5000.generationId).toBe(res5000.generationId); expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path); expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path); + expect(pinned5000.listingVenues).toBe(res5000.listingVenues.path); expect(pinned5000.delistings).toBe(res5000.delistings.path); // Verify chunkSize=1 actually paginated across multiple queries. @@ -410,10 +504,12 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* // Byte-identical outputs between chunkSize=1 and chunkSize=5000. const pm5000 = await readFile(res5000.providerMapping.path, 'utf8'); const lc5000 = await readFile(res5000.listingCurrencies.path, 'utf8'); + const lv5000 = await readFile(res5000.listingVenues.path, 'utf8'); const dl5000 = await readFile(res5000.delistings.path, 'utf8'); expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000); expect(await readFile(res1.listingCurrencies.path, 'utf8')).toBe(lc5000); + expect(await readFile(res1.listingVenues.path, 'utf8')).toBe(lv5000); expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000); // Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order). @@ -456,10 +552,60 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* `${ids.noQmId}\tUSD`, `${ids.noSuccQmFromId}\tUSD`, `${ids.noSuccQmToId}\tUSD`, + `${ids.arcxId}\tUSD`, + `${ids.xaseId}\tUSD`, + `${ids.batsId}\tUSD`, + `${ids.iexgId}\tUSD`, + `${ids.neoeId}\tCAD`, + `${ids.xtsxId}\tCAD`, + `${ids.xcnqId}\tCAD`, '', ].join('\n') ); + // Assert exact listing_venues.tsv content covering all 11 ISO MICs (us_tsx vs tsxv_cse). + expect(lv5000).toBe( + [ + `${ids.aaplId}\tus_tsx`, + `${ids.shopId}\tus_tsx`, + `${ids.fbOldId}\tus_tsx`, + `${ids.fbNewId}\tus_tsx`, + `${ids.sivbId}\tus_tsx`, + `${ids.sivbReuseId}\tus_tsx`, + `${ids.sivbqId}\tus_tsx`, + `${ids.del30Id}\tus_tsx`, + `${ids.noListedToId}\tus_tsx`, + `${ids.noQmId}\tus_tsx`, + `${ids.noSuccQmFromId}\tus_tsx`, + `${ids.noSuccQmToId}\tus_tsx`, + `${ids.arcxId}\tus_tsx`, + `${ids.xaseId}\tus_tsx`, + `${ids.batsId}\tus_tsx`, + `${ids.iexgId}\tus_tsx`, + `${ids.neoeId}\tus_tsx`, + `${ids.xtsxId}\ttsxv_cse`, + `${ids.xcnqId}\ttsxv_cse`, + '', + ].join('\n') + ); + + // Verify strict load_listing_venues_tsv compliance (headerless 2-col LF TSV, ascending positive i32). + expect(lv5000.includes('\r')).toBe(false); + expect(lv5000.endsWith('\n')).toBe(true); + const lvLines = lv5000.slice(0, -1).split('\n'); + expect(lvLines).toHaveLength(19); + let prevListingId = 0; + for (const line of lvLines) { + const cols = line.split('\t'); + expect(cols).toHaveLength(2); + expect(cols[0]).toMatch(/^[1-9]\d*$/); + const id = Number(cols[0]); + expect(id).toBeGreaterThan(prevListingId); + expect(id).toBeLessThanOrEqual(2_147_483_647); + expect(cols[1] === 'us_tsx' || cols[1] === 'tsxv_cse').toBe(true); + prevListingId = id; + } + // Assert exact delistings.tsv content. expect(dl5000).toBe( [ @@ -473,13 +619,13 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* // Assert exact stats reconciliation. const stats = res5000.delistings.stats; expect(stats).toEqual({ - rowsIn: 12, + rowsIn: 19, rowsOut: 3, otcTransfersOut: 1, terminalDelistingsOut: 2, - skippedTotal: 9, + skippedTotal: 16, skipped: { - active: 4, // AAPL, SHOP, FB new, SIVB reuse + active: 11, // AAPL, SHOP, FB new, SIVB reuse + 7 MIC-coverage active listings noOutcome: 2, // FB old, NOSUQ missingListedTo: 1, // NLDT missingOutgoingQmMapping: 1, // NOQM @@ -489,5 +635,80 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_* }); expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal); expect(res1.delistings.stats).toEqual(stats); + expect(res5000.listingVenues.rowsIn).toBe(19); + expect(res5000.listingVenues.rowsOut).toBe(19); + expect(res1.listingVenues.bytesWritten).toBe(res5000.listingVenues.bytesWritten); + }); + + test('fails closed with UNKNOWN_LISTING_MIC on an unmapped exchange MIC (XLON) and leaves existing outDir files intact', async () => { + const { pool } = await createIsolatedFixture(); + const client = await pool.connect(); + let xlonListingId = 0; + try { + await client.query('BEGIN'); + await client.query(` + INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) + VALUES ('XLON', 'XLON', 'London Stock Exchange', 'GB', 'GBP', 'Europe/London', 'XLON', 'us_100') + ON CONFLICT (mic) DO NOTHING + `); + const instRes = await client.query<{ instrument_id: number }>( + `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) + VALUES ('GB0000000011', 'G00000001', 'London Test PLC', 'common', 'GB') + RETURNING instrument_id` + ); + const listRes = await client.query<{ listing_id: number }>( + `INSERT INTO listing ( + instrument_id, mic, ticker_root, class_suffix, currency, + listed_from, listed_to, delist_reason, terminal_return + ) + VALUES ($1, 'XLON', 'LSE', '', 'GBP', '2020-01-02'::date, NULL, 'active', NULL) + RETURNING listing_id`, + [instRes.rows[0]!.instrument_id] + ); + xlonListingId = listRes.rows[0]!.listing_id; + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => {}); + throw error; + } finally { + client.release(); + } + + const outDir = await makeTempDir('curate-inputs-pg-unknown-mic-'); + const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; + const origLc = '1\tUSD\n'; + const origLv = '1\tus_tsx\n'; + const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; + await writeFile(join(outDir, CURATE_INPUT_FILES.providerMapping), origPm, 'utf8'); + await writeFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), origLc, 'utf8'); + await writeFile(join(outDir, CURATE_INPUT_FILES.listingVenues), origLv, 'utf8'); + await writeFile(join(outDir, CURATE_INPUT_FILES.delistings), origDl, 'utf8'); + + let caught: unknown; + try { + await withRecordingClient(pool, async queryable => { + await exportCurateInputs(queryable, { outDir }); + }); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(CurateInputExportError); + const err = caught as CurateInputExportError; + expect(err.code).toBe('UNKNOWN_LISTING_MIC'); + expect(err.table).toBe('listing'); + expect(err.key).toBe(`listing_id=${xlonListingId}`); + expect(err.message).toContain('XLON'); + + expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(origPm); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(origLc); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(origLv); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(origDl); + expect((await readdir(outDir)).sort()).toEqual([ + CURATE_INPUT_FILES.delistings, + CURATE_INPUT_FILES.listingCurrencies, + CURATE_INPUT_FILES.listingVenues, + CURATE_INPUT_FILES.providerMapping, + ]); }); }); diff --git a/test/unit/security-master-export-curate-inputs.test.ts b/test/unit/security-master-export-curate-inputs.test.ts index 9d3f728d..8d0ce4d5 100644 --- a/test/unit/security-master-export-curate-inputs.test.ts +++ b/test/unit/security-master-export-curate-inputs.test.ts @@ -19,16 +19,22 @@ import { formatDelistingsTsv, formatExportCurateInputsSummary, formatListingCurrenciesTsv, + formatListingVenuesTsv, formatPlainDecimal, formatProviderMappingTsv, + ISO_EXCHANGE_SEEDS, + LISTING_STATUTORY_LAG_VENUES, + LISTING_VENUE_BY_MIC, parseExportCurateInputsArgs, pinCurateInputSnapshot, + resolveListingVenueForMic, runExportCurateInputs, runExportCurateInputsCli, type ContinuityExportSourceRow, type DelistingExportRow, type ListingCurrencyExportRow, type ListingDelistingSourceRow, + type ListingVenueExportRow, type ProviderMappingExportRow, type SecurityMasterQueryable, type SecurityMasterQueryResult, @@ -93,6 +99,7 @@ async function expectExportErrorAsync( interface InMemorySecurityMasterData { readonly listings: readonly { readonly listing_id: number; + readonly mic: string | null; readonly currency: string | null; readonly listed_to: string | null; readonly delist_reason: string | null; @@ -579,6 +586,135 @@ describe('formatListingCurrenciesTsv', () => { }); }); +describe('resolveListingVenueForMic and formatListingVenuesTsv', () => { + test('maps all 11 ISO_EXCHANGE_SEEDS MICs to us_tsx or tsxv_cse with 100% coverage', () => { + const usTsxMics = ['XTSE', 'XNYS', 'XNAS', 'ARCX', 'XASE', 'BATS', 'NEOE', 'OTCM', 'IEXG']; + const tsxvCseMics = ['XTSX', 'XCNQ']; + + for (const mic of usTsxMics) { + expect(resolveListingVenueForMic(mic)).toBe('us_tsx'); + } + for (const mic of tsxvCseMics) { + expect(resolveListingVenueForMic(mic)).toBe('tsxv_cse'); + } + + const seededMics = ISO_EXCHANGE_SEEDS.map(s => s.mic).sort(compareAscii); + const mappedMics = Object.keys(LISTING_VENUE_BY_MIC).sort(compareAscii); + expect(mappedMics).toEqual(seededMics); + expect(seededMics).toHaveLength(11); + for (const seed of ISO_EXCHANGE_SEEDS) { + expect(LISTING_STATUTORY_LAG_VENUES).toContain(resolveListingVenueForMic(seed.mic)); + } + }); + + test('resolveListingVenueForMic fails closed on unknown, blank, whitespace-padded, control-char, and prototype-key MICs', () => { + for (const unknownMic of ['XLON', 'xtse', ' XTSE ', 'XTSX ', '__proto__', 'toString', 'constructor']) { + expectExportError( + () => resolveListingVenueForMic(unknownMic, 'listing', 'listing_id=42'), + 'UNKNOWN_LISTING_MIC', + 'listing', + 'listing_id=42' + ); + } + + for (const blankMic of ['', ' ', null, undefined]) { + expectExportError( + () => resolveListingVenueForMic(blankMic, 'listing', 'listing_id=42'), + 'BLANK_FIELD', + 'listing', + 'listing_id=42' + ); + } + + for (const controlMic of ['XT\tSE', 'XT\nSE', 'XT\rSE']) { + expectExportError( + () => resolveListingVenueForMic(controlMic, 'listing', 'listing_id=42'), + 'FORBIDDEN_CONTROL_CHAR', + 'listing', + 'listing_id=42' + ); + } + }); + + test('formatListingVenuesTsv sorts by ascending listing_id, handles empty input, and satisfies load_listing_venues_tsv rules', () => { + expect(formatListingVenuesTsv([])).toBe(''); + + const rows: ListingVenueExportRow[] = [ + { listingId: 10, venue: 'tsxv_cse' }, + { listingId: 2, venue: 'us_tsx' }, + { listingId: 5, venue: 'tsxv_cse' }, + { listingId: 2_147_483_647, venue: 'us_tsx' }, + ]; + const expected = '2\tus_tsx\n5\ttsxv_cse\n10\ttsxv_cse\n2147483647\tus_tsx\n'; + const actual = formatListingVenuesTsv(rows); + expect(actual).toBe(expected); + expect(formatListingVenuesTsv([...rows].reverse())).toBe(expected); + + // Cross-language load_listing_venues_tsv format verification + expect(actual.includes('\r')).toBe(false); + expect(actual.endsWith('\n')).toBe(true); + const lines = actual.slice(0, -1).split('\n'); + expect(lines).toHaveLength(rows.length); + let prevId = 0; + for (const line of lines) { + const cols = line.split('\t'); + expect(cols).toHaveLength(2); + expect(cols[0]).toMatch(/^[1-9]\d*$/); + const id = Number(cols[0]); + expect(id).toBeGreaterThan(prevId); + expect(id).toBeLessThanOrEqual(2_147_483_647); + expect(cols[1] === 'us_tsx' || cols[1] === 'tsxv_cse').toBe(true); + prevId = id; + } + }); + + test('formatListingVenuesTsv fails closed on invalid listing_id, invalid venue, control chars, and duplicate listing_id', () => { + for (const badId of [0, -3, 2_147_483_648]) { + expectExportError( + () => formatListingVenuesTsv([{ listingId: badId, venue: 'us_tsx' }]), + 'INVALID_LISTING_ID', + 'listing', + 'row#0' + ); + } + + for (const badVenue of ['', 'NYSE', 'US_TSX', ' us_tsx ', null, undefined]) { + expectExportError( + () => + formatListingVenuesTsv([ + { listingId: 1, venue: badVenue as unknown as ListingVenueExportRow['venue'] }, + ]), + 'INVALID_LISTING_VENUE', + 'listing', + 'listing_id=1' + ); + } + + for (const ctrlVenue of ['us_tsx\t', 'us_tsx\n', 'tsxv_cse\r']) { + expectExportError( + () => + formatListingVenuesTsv([ + { listingId: 1, venue: ctrlVenue as unknown as ListingVenueExportRow['venue'] }, + ]), + 'FORBIDDEN_CONTROL_CHAR', + 'listing', + 'listing_id=1' + ); + } + + expectExportError( + () => + formatListingVenuesTsv([ + { listingId: 7, venue: 'us_tsx' }, + { listingId: 7, venue: 'tsxv_cse' }, + ]), + 'DUPLICATE_LISTING_VENUE', + 'listing', + 'listing_id=7' + ); + }); +}); + describe('buildDelistingExportRows and formatDelistingsTsv', () => { test('handles OTC transfer + successor terminal delisting (SIVB -> SIVBQ -> -1), -0.3 Shumway, active/null skips, and stats conservation', () => { const listings: ListingDelistingSourceRow[] = [ @@ -760,18 +896,21 @@ describe('exportCurateInputs atomic publish and streaming', () => { const outDir = await makeTempDir('curate-inputs-atomic-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); + const lvPath = join(outDir, CURATE_INPUT_FILES.listingVenues); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; const origLc = '1\tUSD\n'; + const origLv = '1\tus_tsx\n'; const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; await writeFile(pmPath, origPm, 'utf8'); await writeFile(lcPath, origLc, 'utf8'); + await writeFile(lvPath, origLv, 'utf8'); await writeFile(dlPath, origDl, 'utf8'); const baseData: InMemorySecurityMasterData = { listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 1, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -782,11 +921,13 @@ describe('exportCurateInputs atomic publish and streaming', () => { const assertIntact = async () => { expect(await readFile(pmPath, 'utf8')).toBe(origPm); expect(await readFile(lcPath, 'utf8')).toBe(origLc); + expect(await readFile(lvPath, 'utf8')).toBe(origLv); expect(await readFile(dlPath, 'utf8')).toBe(origDl); const entries = (await readdir(outDir)).sort(); expect(entries).toEqual([ CURATE_INPUT_FILES.delistings, CURATE_INPUT_FILES.listingCurrencies, + CURATE_INPUT_FILES.listingVenues, CURATE_INPUT_FILES.providerMapping, ]); }; @@ -798,7 +939,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { ); await assertIntact(); - // 2. Mid-validation failure (tab inside source_id) + // 2a. Mid-validation failure (tab inside source_id) const badDataClient = createInMemoryQueryable({ ...baseData, providerMappings: [ @@ -813,6 +954,21 @@ describe('exportCurateInputs atomic publish and streaming', () => { ); await assertIntact(); + // 2b. Mid-validation failure (unmapped listing MIC) + const badMicClient = createInMemoryQueryable({ + ...baseData, + listings: [ + { listing_id: 1, mic: 'XLON', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + ], + }); + await expectExportErrorAsync( + () => exportCurateInputs(badMicClient, { outDir }), + 'UNKNOWN_LISTING_MIC', + 'listing', + 'listing_id=1' + ); + await assertIntact(); + // 3. Mid-rename failure on the 2nd top-level target symlink replacement (after staging->gen + 1st backup/link + 2nd backup) let renameCalls = 0; const goodClient = createInMemoryQueryable(baseData); @@ -832,7 +988,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { ).rejects.toThrow('Simulated EIO on 2nd target publish rename'); await assertIntact(); - // 4. Failure at the atomic `current` commit rename restores all 3 pre-existing files cleanly + // 4. Failure at the atomic `current` commit rename restores all 4 pre-existing files cleanly const commitFailClient = createInMemoryQueryable(baseData); await expect( exportCurateInputs(commitFailClient, { @@ -854,15 +1010,17 @@ describe('exportCurateInputs atomic publish and streaming', () => { const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); + const lvPath = join(outDir, CURATE_INPUT_FILES.listingVenues); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8'); await writeFile(lcPath, '1\tUSD\n', 'utf8'); + await writeFile(lvPath, '1\tus_tsx\n', 'utf8'); await writeFile(dlPath, 'OLD\t2023-01-01\t1\t\t-0.3\n', 'utf8'); const newData: InMemorySecurityMasterData = { listings: [ - { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 2, mic: 'XTSX', currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -886,13 +1044,14 @@ describe('exportCurateInputs atomic publish and streaming', () => { }, }); - // All three live paths reflect the new committed snapshot (no partial rollback). + // All four live paths reflect the new committed snapshot (no partial rollback). expect(await readFile(pmPath, 'utf8')).toBe('eod\tNEW.TO\t2022-01-01\t\t2\n'); expect(await readFile(lcPath, 'utf8')).toBe('2\tCAD\n'); + expect(await readFile(lvPath, 'utf8')).toBe('2\ttsxv_cse\n'); expect(await readFile(dlPath, 'utf8')).toBe(''); - // Backup #1 and #3 were deleted; #2 failed and is reported in cleanupWarnings. - expect(backupUnlinkCalls).toBe(3); + // Backups #1, #3, #4 were deleted; #2 failed and is reported in cleanupWarnings. + expect(backupUnlinkCalls).toBe(4); expect(result.cleanupWarnings).toHaveLength(1); expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup'); expect(result.cleanupWarnings[0]).toContain('.bak'); @@ -903,18 +1062,21 @@ describe('exportCurateInputs atomic publish and streaming', () => { const outDir = await makeTempDir('curate-inputs-restore-fail-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); + const lvPath = join(outDir, CURATE_INPUT_FILES.listingVenues); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; const origLc = '1\tUSD\n'; + const origLv = '1\tus_tsx\n'; const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; await writeFile(pmPath, origPm, 'utf8'); await writeFile(lcPath, origLc, 'utf8'); + await writeFile(lvPath, origLv, 'utf8'); await writeFile(dlPath, origDl, 'utf8'); const newData: InMemorySecurityMasterData = { listings: [ - { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 2, mic: 'XTSE', currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -928,7 +1090,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { outDir, fs: { rename: async (oldPath, newPath) => { - // Fail at the atomic commit point to trigger rollback of all 3 backups. + // Fail at the atomic commit point to trigger rollback of all 4 backups. if (String(newPath) === join(outDir, 'current')) { throw new Error('Simulated commit EIO'); } @@ -953,8 +1115,9 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(err.message).toContain('Simulated restore EIO'); expect(err.message).toContain('.bak'); - // The other two targets were restored intact. + // The other three targets were restored intact. expect(await readFile(lcPath, 'utf8')).toBe(origLc); + expect(await readFile(lvPath, 'utf8')).toBe(origLv); expect(await readFile(dlPath, 'utf8')).toBe(origDl); // The unrestored provider_mapping backup MUST still exist on disk with original bytes! @@ -972,7 +1135,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { // Generation 1: only SIVB active (no SIVBQ successor yet). const gen1Data: InMemorySecurityMasterData = { listings: [ - { listing_id: 4, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 4, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -983,8 +1146,8 @@ describe('exportCurateInputs atomic publish and streaming', () => { // Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings. const gen2Data: InMemorySecurityMasterData = { listings: [ - { listing_id: 4, currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null }, - { listing_id: 6, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 4, mic: 'XNAS', currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null }, + { listing_id: 6, mic: 'OTCM', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [ { from_listing_id: 4, to_listing_id: 6, effective_date: '2023-03-28', kind: 'otc_delist_transfer' }, @@ -1007,10 +1170,12 @@ describe('exportCurateInputs atomic publish and streaming', () => { const res2 = await exportCurateInputs(createInMemoryQueryable(gen2Data), { outDir }); expect(res2.generationId).not.toBe(res1.generationId); - // Consumer 1 finishes reading listing_currencies.tsv and delistings.tsv from its pinned generation 1. + // Consumer 1 finishes reading listing_currencies.tsv, listing_venues.tsv, and delistings.tsv from its pinned generation 1. const consumer1Lc = await readFile(pinned1.listingCurrencies, 'utf8'); + const consumer1Lv = await readFile(pinned1.listingVenues, 'utf8'); const consumer1Dl = await readFile(pinned1.delistings, 'utf8'); expect(consumer1Lc).toBe('4\tUSD\n'); + expect(consumer1Lv).toBe('4\tus_tsx\n'); expect(consumer1Dl).toBe(''); // Consistent with gen1 (no SIVBQ transfer referencing missing SIVBQ!) // Consumer 2 pins after Generation 2 committed and sees the full Generation 2 snapshot. @@ -1020,6 +1185,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { 'qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n' ); expect(await readFile(pinned2.listingCurrencies, 'utf8')).toBe('4\tUSD\n6\tUSD\n'); + expect(await readFile(pinned2.listingVenues, 'utf8')).toBe('4\tus_tsx\n6\tus_tsx\n'); expect(await readFile(pinned2.delistings, 'utf8')).toBe('SIVB\t2023-03-28\t4\tSIVBQ\t\n'); }); @@ -1028,7 +1194,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { const snapA: InMemorySecurityMasterData = { listings: [ - { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, + { listing_id: 10, mic: 'XNAS', currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, ], continuities: [], providerMappings: [ @@ -1037,7 +1203,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { }; const snapB: InMemorySecurityMasterData = { listings: [ - { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, + { listing_id: 20, mic: 'XTSX', currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, ], continuities: [], providerMappings: [ @@ -1053,17 +1219,20 @@ describe('exportCurateInputs atomic publish and streaming', () => { const pinned = await pinCurateInputSnapshot(outDir); const pm = await readFile(pinned.providerMapping, 'utf8'); const lc = await readFile(pinned.listingCurrencies, 'utf8'); + const lv = await readFile(pinned.listingVenues, 'utf8'); const dl = await readFile(pinned.delistings, 'utf8'); const isAllA = pinned.generationId === resA.generationId && pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' && lc === '10\tUSD\n' && + lv === '10\tus_tsx\n' && dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n'; const isAllB = pinned.generationId === resB.generationId && pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' && lc === '20\tCAD\n' && + lv === '20\ttsxv_cse\n' && dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n'; expect(isAllA || isAllB).toBe(true); @@ -1072,7 +1241,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { test('concurrent fresh-dir exports serialize publish/rollback so a failed export never deletes a committed export top-level links', async () => { const snapA: InMemorySecurityMasterData = { listings: [ - { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, + { listing_id: 10, mic: 'XNAS', currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, ], continuities: [], providerMappings: [ @@ -1081,7 +1250,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { }; const snapB: InMemorySecurityMasterData = { listings: [ - { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, + { listing_id: 20, mic: 'XTSX', currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, ], continuities: [], providerMappings: [ @@ -1145,10 +1314,14 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( '20\tCAD\n' ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + '20\ttsxv_cse\n' + ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( 'SNAP_B\t2024-01-15\t20\t\t-1\n' ); const pinned = await pinCurateInputSnapshot(outDir); + expect(await readFile(pinned.listingVenues, 'utf8')).toBe('20\ttsxv_cse\n'); expect(await readFile(pinned.delistings, 'utf8')).toBe('SNAP_B\t2024-01-15\t20\t\t-1\n'); const entries = await readdir(outDir); expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false); @@ -1215,10 +1388,14 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( '20\tCAD\n' ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + '20\ttsxv_cse\n' + ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( 'SNAP_B\t2024-01-15\t20\t\t-1\n' ); const pinned = await pinCurateInputSnapshot(outDir); + expect(await readFile(pinned.listingVenues, 'utf8')).toBe('20\ttsxv_cse\n'); expect(await readFile(pinned.providerMapping, 'utf8')).toBe( 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' ); @@ -1258,6 +1435,7 @@ describe('exportCurateInputs atomic publish and streaming', () => { listings: [ { listing_id: 1, + mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', @@ -1373,10 +1551,18 @@ describe('golden fixtures cross-language parity', () => { ); // Also verify streaming exportCurateInputs produces identical bytes with chunkSize=2. + const goldenMics = ['XNAS', 'XNAS', 'XNYS', 'XNAS', 'XNAS', 'OTCM', 'XNYS', 'XTSE'] as const; + const expectedLv = formatListingVenuesTsv( + dataset.listings.map((l, idx) => ({ + listingId: l.listingId, + venue: resolveListingVenueForMic(goldenMics[idx]!), + })) + ); const outDir = await makeTempDir('curate-inputs-golden-'); const queryable = createInMemoryQueryable({ listings: dataset.delistingListings.map((l, idx) => ({ listing_id: l.listingId, + mic: goldenMics[idx]!, currency: dataset.listings[idx]!.currency, listed_to: l.listedTo, delist_reason: l.delistReason, @@ -1400,8 +1586,15 @@ describe('golden fixtures cross-language parity', () => { const result = await exportCurateInputs(queryable, { outDir, chunkSize: 2 }); expect(await readFile(result.providerMapping.path, 'utf8')).toBe(expectedPm); expect(await readFile(result.listingCurrencies.path, 'utf8')).toBe(expectedLc); + expect(await readFile(result.listingVenues.path, 'utf8')).toBe(expectedLv); expect(await readFile(result.delistings.path, 'utf8')).toBe(expectedDl); expect(result.delistings.stats).toEqual(builtDelistings.stats); + expect(result.totalBytesWritten).toBe( + result.providerMapping.bytesWritten + + result.listingCurrencies.bytesWritten + + result.listingVenues.bytesWritten + + result.delistings.bytesWritten + ); }); }); @@ -1483,7 +1676,7 @@ describe('CLI args, safety guard, and runner', () => { const queryable = createInMemoryQueryable({ listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 1, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -1514,6 +1707,7 @@ describe('CLI args, safety guard, and runner', () => { expect(output.summary).toBe(formatExportCurateInputsSummary(output.result)); expect(stdoutText).toContain('provider_mapping.tsv: rows_in=1 rows_out=1'); expect(stdoutText).toContain('listing_currencies.tsv: rows_in=1 rows_out=1'); + expect(stdoutText).toContain('listing_venues.tsv: rows_in=1 rows_out=1'); expect(stdoutText).toContain('delistings.tsv: rows_in=1 rows_out=0'); }); @@ -1563,7 +1757,7 @@ describe('CLI args, safety guard, and runner', () => { const queryable = createInMemoryQueryable({ listings: [ - { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, + { listing_id: 1, mic: 'XNAS', currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ @@ -1586,6 +1780,9 @@ describe('CLI args, safety guard, and runner', () => { expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( 'qm\tAAPL\t2020-01-01\t\t1\n' ); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe( + '1\tus_tsx\n' + ); // Still rejects dev -> QA PostgreSQL even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true! resetStockConfig();