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:33:13 -05:00
parent 12da9aa899
commit ba20f9a2e5
8 changed files with 345 additions and 63 deletions

View file

@ -87,7 +87,8 @@ export type CurateInputExportErrorCode =
| 'DUPLICATE_OTC_CONTINUITY'
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
| 'PUBLISH_LOCK_TIMEOUT'
| 'PUBLISH_ROLLBACK_FAILED';
| 'PUBLISH_ROLLBACK_FAILED'
| 'INCOMPLETE_SNAPSHOT';
export interface CurateInputExportErrorOptions {
readonly code: CurateInputExportErrorCode;
@ -1319,7 +1320,7 @@ async function acquirePublishLock(
*/
export async function pinCurateInputSnapshot(
outDir: string,
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath'>
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath' | 'access'>
): Promise<PinnedCurateInputSnapshot> {
if (typeof outDir !== 'string' || outDir.trim().length === 0) {
throw new CurateInputExportError({
@ -1332,17 +1333,41 @@ export async function pinCurateInputSnapshot(
}
const normalizedOutDir = outDir.trim();
const fsRealpath = fsHooks?.realpath ?? realpath;
const fsAccess = fsHooks?.access ?? access;
const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK);
const generationDir = await fsRealpath(currentLink);
const generationId = basename(generationDir);
const providerMapping = join(generationDir, CURATE_INPUT_FILES.providerMapping);
const listingCurrencies = join(generationDir, CURATE_INPUT_FILES.listingCurrencies);
const listingVenues = join(generationDir, CURATE_INPUT_FILES.listingVenues);
const delistings = join(generationDir, CURATE_INPUT_FILES.delistings);
try {
await fsAccess(listingVenues);
} catch (error) {
if ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') {
throw new CurateInputExportError({
code: 'INCOMPLETE_SNAPSHOT',
table: 'publish',
key: generationId,
field: CURATE_INPUT_FILES.listingVenues,
detail:
`generation "${generationId}" under "${normalizedOutDir}" is missing ${CURATE_INPUT_FILES.listingVenues} ` +
'(legacy M1 three-file snapshot); re-run exportCurateInputs to refresh the export',
cause: error,
});
}
throw error;
}
return {
outDir: normalizedOutDir,
generationId,
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),
providerMapping,
listingCurrencies,
listingVenues,
delistings,
};
}

View file

@ -134,6 +134,7 @@ export {
export {
assertExportRawBsonSafety,
DEFAULT_RAW_BSON_EXPORT_COLLECTIONS,
EXPORT_RAW_BSON_USAGE,
formatExportRawBsonSummary,
parseExportRawBsonArgs,
@ -147,6 +148,11 @@ export {
type RunExportRawBsonOutput,
} from './run-export-raw-bson';
export {
assertReadOnlyMongoDiagnosticSafety,
type ReadOnlyMongoDiagnosticSafetyOptions,
} from './read-only-mongo-safety';
export {
escapeSqlLiteral,
generateExchangeSeedSql,

View file

@ -2,12 +2,9 @@ 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 {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety';
import {
DEFAULT_FIELD_SHAPE_LIMIT,
FIELD_SHAPE_PROBE_COLLECTIONS,
@ -280,28 +277,14 @@ 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,
},
assertReadOnlyMongoDiagnosticSafety(
config,
{
operationLabel: 'probe source field shapes',
diagnosticLabel: 'Source field-shape probe',
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
env
);
}
export async function runCli(

View file

@ -0,0 +1,82 @@
import { assertEnvironmentSafety, type StockAppConfig } from '@stock-bot/stock-config';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
export interface ReadOnlyMongoDiagnosticSafetyOptions {
readonly operationLabel: string;
readonly diagnosticLabel: string;
}
/**
* Shared safety guard for strictly read-only MongoDB diagnostic CLIs
* (`probe-source-field-shapes` and `run-export-raw-bson`).
*
* Enforces:
* 1. MongoDB is enabled and configured with `readOnly === true`.
* 2. Environment safety for `dataPipeline` (with PostgreSQL disabled and
* `STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE` stripped).
* 3. The exact effective URI resolved by `resolveReadOnlyMongoClientConfig`
* (falling back from unset/blank `readUri` to `uri`) cannot target QA
* MongoDB with admin credentials (`trading_admin`), regardless of `NODE_ENV`.
*/
export function assertReadOnlyMongoDiagnosticSafety(
config: StockAppConfig,
options: ReadOnlyMongoDiagnosticSafetyOptions,
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 ${options.operationLabel}`);
}
if (mongo.readOnly !== true) {
throw new Error(
`${options.diagnosticLabel} requires read-only MongoDB configuration (database.mongodb.readOnly === true)`
);
}
const effectiveMongoConfig = resolveReadOnlyMongoClientConfig(config);
const effectiveUri = effectiveMongoConfig.uri;
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
const mongoOnlyConfig: StockAppConfig = {
...config,
database: {
...config.database,
postgres: {
...config.database.postgres,
enabled: false,
},
mongodb: {
...mongo,
uri: effectiveUri ?? mongo.uri,
readUri: effectiveUri,
},
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
if (mongoOnlyConfig.environment !== 'development') {
try {
assertEnvironmentSafety(
{
...mongoOnlyConfig,
environment: 'development',
},
'dataPipeline',
safeEnv
);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
if (detail.includes('development data-pipeline')) {
throw new Error(
detail.replace(
'development data-pipeline',
`${config.environment} ${options.diagnosticLabel}`
),
{ cause: error }
);
}
throw error;
}
}
}

View file

@ -1,10 +1,6 @@
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
import {
assertEnvironmentSafety,
initializeStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import {
createReadOnlyMongoRawBsonSource,
DEFAULT_RAW_BSON_BATCH_SIZE,
@ -19,13 +15,32 @@ import {
type ReadOnlyMongoRawBsonClient,
} from './export-raw-bson';
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
import { assertReadOnlyMongoDiagnosticSafety } from './read-only-mongo-safety';
/**
* Default collection set when `--collections` is omitted. Preserves the bounded
* M1 set so omitting `--collections` does not trigger an unbounded dump of M2
* collections (e.g. `eodIntraday1M`). All 14 M1+M2 collections remain
* selectable via `--collections`.
*/
export const DEFAULT_RAW_BSON_EXPORT_COLLECTIONS: readonly RawBsonExportCollection[] =
Object.freeze([
'eodPrices',
'qmSplits',
'qmDividends',
'qmPrices',
'teMarketData',
'ceoShorts',
'qmFilings',
'qmEarnings',
] as const);
export const EXPORT_RAW_BSON_USAGE = [
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
'',
'Options:',
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`,
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${DEFAULT_RAW_BSON_EXPORT_COLLECTIONS.join(',')}; M2 collections require explicit selection: qmFinancials,qmFinancials-old,ceoPosts,teData,eodIntraday1M,qmIntraday).`,
' --eod-symbol <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
@ -242,7 +257,7 @@ export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRaw
}
const resolvedCollections: readonly RawBsonExportCollection[] =
collections ?? [...RAW_BSON_EXPORT_COLLECTIONS];
collections ?? [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS];
if (eodSymbol !== undefined) {
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
@ -275,28 +290,14 @@ export function assertExportRawBsonSafety(
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 export raw BSON collections');
}
if (mongo.readOnly !== true) {
throw new Error(
'Raw BSON exporter 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,
},
assertReadOnlyMongoDiagnosticSafety(
config,
{
operationLabel: 'export raw BSON collections',
diagnosticLabel: 'Raw BSON exporter',
},
};
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
env
);
}
export function formatExportRawBsonSummary(

View file

@ -12,6 +12,7 @@ import {
} from '../src/security-master/export-raw-bson';
import {
assertExportRawBsonSafety,
DEFAULT_RAW_BSON_EXPORT_COLLECTIONS,
EXPORT_RAW_BSON_USAGE,
parseExportRawBsonArgs,
runCli,
@ -99,12 +100,31 @@ describe('parseExportRawBsonArgs', () => {
expect(parsedDefault).toEqual({
help: false,
outDir: './tmp/all',
collections: [...RAW_BSON_EXPORT_COLLECTIONS],
collections: [...DEFAULT_RAW_BSON_EXPORT_COLLECTIONS],
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
});
expect(parsedDefault.help).toBe(false);
if (!parsedDefault.help) {
expect(parsedDefault.collections).toHaveLength(14);
expect(parsedDefault.collections).toHaveLength(8);
expect(parsedDefault.collections).not.toContain('eodIntraday1M');
expect(parsedDefault.collections).not.toContain('qmFinancials');
expect(parsedDefault.collections).not.toContain('ceoPosts');
}
const parsedAll14 = parseExportRawBsonArgs([
'--out-dir',
'./tmp/all-14',
'--collections',
RAW_BSON_EXPORT_COLLECTIONS.join(','),
]);
expect(parsedAll14).toEqual({
help: false,
outDir: './tmp/all-14',
collections: [...RAW_BSON_EXPORT_COLLECTIONS],
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
});
if (!parsedAll14.help) {
expect(parsedAll14.collections).toHaveLength(14);
}
const parsedM2 = parseExportRawBsonArgs([
@ -228,6 +248,37 @@ describe('assertExportRawBsonSafety', () => {
{ STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' }
)
).toThrow(/Safety guard/);
// QA profile with no MONGODB_READ_URI (or blank readUri) falls back to trading_admin
// and must be rejected regardless of NODE_ENV=qa.
const qaAdminNoReadUri = {
...createBaseConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: undefined,
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
const qaAdminBlankReadUri = {
...createBaseConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: ' ',
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
const qaWithReadUri = {
...createBaseConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
expect(() => assertExportRawBsonSafety(qaAdminNoReadUri, {})).toThrow(/Safety guard/);
expect(() => assertExportRawBsonSafety(qaAdminBlankReadUri, {})).toThrow(/Safety guard/);
expect(() => assertExportRawBsonSafety(qaWithReadUri, {})).not.toThrow();
});
});
@ -428,4 +479,27 @@ describe('runExportRawBson & runCli', () => {
await rm(outDir, { recursive: true, force: true });
}
});
test('runCli rejects QA profile with no MONGODB_READ_URI before connecting to MongoDB', async () => {
const createClientMock = mock(() => {
throw new Error('createMongoClient must not be called when QA admin credentials are active');
});
const qaAdminNoReadUri = {
...createBaseConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: undefined,
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
await expect(
runCli(['--out-dir', '/tmp/unused-qa-bson', '--collections', 'eodPrices'], {
initializeConfig: (() => qaAdminNoReadUri) as never,
createMongoClient: createClientMock,
})
).rejects.toThrow(/Safety guard/);
expect(createClientMock).not.toHaveBeenCalled();
});
});

View file

@ -1004,5 +1004,46 @@ describe('CLI arg parsing and headless probe runner', () => {
})
).rejects.toThrow(/read-only MongoDB configuration/);
expect(clientNeverMock).not.toHaveBeenCalled();
// QA profile with no MONGODB_READ_URI (or whitespace-only readUri) falls back to trading_admin
// and must be rejected before connecting, regardless of NODE_ENV=qa.
const qaAdminNoReadUri = {
...createConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: undefined,
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
const qaAdminBlankReadUri = {
...createConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: ' ',
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
const qaWithReadUri = {
...createConfig({
uri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
readOnly: true,
}),
environment: 'qa',
} as unknown as StockAppConfig;
expect(() => assertProbeSourceFieldShapesSafety(qaAdminNoReadUri, {})).toThrow(/Safety guard/);
expect(() => assertProbeSourceFieldShapesSafety(qaAdminBlankReadUri, {})).toThrow(
/Safety guard/
);
expect(() => assertProbeSourceFieldShapesSafety(qaWithReadUri, {})).not.toThrow();
await expect(
runProbeSourceFieldShapesCli(['--out', './tmp/qa-blocked.md', '--collections', 'ceoPosts'], {
initializeConfig: (() => qaAdminNoReadUri) as never,
createMongoClient: clientNeverMock,
})
).rejects.toThrow(/Safety guard/);
expect(clientNeverMock).not.toHaveBeenCalled();
});
});

View file

@ -1,5 +1,16 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtemp, open, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises';
import {
mkdir,
mkdtemp,
open,
readdir,
readFile,
rename,
rm,
symlink,
unlink,
writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import {
@ -10,7 +21,9 @@ import {
import {
assertExportCurateInputsSafety,
buildDelistingExportRows,
CURATE_INPUT_CURRENT_LINK,
CURATE_INPUT_FILES,
CURATE_INPUT_GENERATIONS_DIR,
CURATE_INPUT_PUBLISH_LOCK,
CurateInputExportError,
DEFAULT_EXPORT_CHUNK_SIZE,
@ -1521,6 +1534,63 @@ describe('exportCurateInputs atomic publish and streaming', () => {
'chunkSize'
);
});
test('pinCurateInputSnapshot fails closed with INCOMPLETE_SNAPSHOT on legacy M1 three-file generation and succeeds after refresh', async () => {
const outDir = await makeTempDir('curate-inputs-legacy-m1-');
const legacyGenId = 'gen-m1-legacy';
const legacyGenDir = join(outDir, CURATE_INPUT_GENERATIONS_DIR, legacyGenId);
await mkdir(legacyGenDir, { recursive: true });
await writeFile(join(legacyGenDir, CURATE_INPUT_FILES.providerMapping), 'qm\tAAPL\t2020-01-01\t\t1\n', 'utf8');
await writeFile(join(legacyGenDir, CURATE_INPUT_FILES.listingCurrencies), '1\tUSD\n', 'utf8');
await writeFile(join(legacyGenDir, CURATE_INPUT_FILES.delistings), '', 'utf8');
await symlink(
join(CURATE_INPUT_GENERATIONS_DIR, legacyGenId),
join(outDir, CURATE_INPUT_CURRENT_LINK)
);
let caught: unknown;
try {
await pinCurateInputSnapshot(outDir);
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(CurateInputExportError);
const err = caught as CurateInputExportError;
expect(err.code).toBe('INCOMPLETE_SNAPSHOT');
expect(err.table).toBe('publish');
expect(err.key).toBe(legacyGenId);
expect(err.field).toBe(CURATE_INPUT_FILES.listingVenues);
expect(err.message).toContain('listing_venues.tsv');
expect(err.message).toContain('refresh the export');
// Refreshing the export publishes a complete 4-file generation that pins cleanly.
const refreshedClient = createInMemoryQueryable({
listings: [
{
listing_id: 1,
mic: 'XNAS',
currency: 'USD',
listed_to: null,
delist_reason: 'active',
terminal_return: null,
},
],
continuities: [],
providerMappings: [
{
source: 'qm',
source_id: 'AAPL',
valid_from: '2020-01-01',
valid_to: null,
listing_id: 1,
},
],
});
await exportCurateInputs(refreshedClient, { outDir });
const pinned = await pinCurateInputSnapshot(outDir);
expect(await readFile(pinned.listingVenues, 'utf8')).toBe('1\tus_tsx\n');
expect(await readFile(pinned.providerMapping, 'utf8')).toBe('qm\tAAPL\t2020-01-01\t\t1\n');
});
});
describe('golden fixtures cross-language parity', () => {