T-211: M2.2v — Export listing_venues.tsv and extend field-shape probe & BSON fixture exporter for M2 collections

This commit is contained in:
Studio 2026-12-04 14:09:44 -05:00
parent e6bc956e49
commit c9ab13d5a3
12 changed files with 1047 additions and 71 deletions

View file

@ -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<Record<string, ListingStatutoryLagVenue>> = 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 `<outDir>/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 `<outDir>/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 `<outDir>/generations/<generationId>`, and atomically commits
* `<outDir>/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<number, ContinuityExportSourceRow>();
@ -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<DbListingRow>(
`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<DbListingRow>(
`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,
};
}

View file

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

View file

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

View file

@ -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> | void;
}>
| {
readonly client: ReadOnlyMongoCollectionClient;
readonly close: () => Promise<void> | void;
};
readonly writeFile?: (filePath: string, content: string) => Promise<void> | 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<void> {
export function assertProbeSourceFieldShapesSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = 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<void> {
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<void> {
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,

View file

@ -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 <dir> [--chunk-size <n>] [--help]',
'',
'Options:',
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`,
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, ${CURATE_INPUT_FILES.listingVenues}, and ${CURATE_INPUT_FILES.delistings}.`,
` --chunk-size <n> 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}`,
];

View file

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

View file

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

View file

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

View file

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

View file

@ -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<string, Record<string, unknown>[]> = {
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['database']['mongodb']> = {}
): 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();
});
});