diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 8f3262c9..929e9a3d 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -142,3 +142,39 @@ bun test test/unit/security-master-run.test.ts - **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):** - Workload: `100,000` synthetic source records (`50,000` EOD + `25,000` IB + `25,000` QM, `75,000` bar spans, `50,000` security types) composed end to end through Stage A, Stage B, Pass 6, Pass 4 pair derivation, MatchReport + Markdown/CSV/SQL rendering, and `PersistSecurityMasterInput` assembly. - Observed throughput: `208,502 records/s` (`479.6 ms` wall time, asserted floor `>= 10,000 records/s`). + +## Running the security master +`apps/stock/data-pipeline/src/security-master/run-security-master.ts` runs the full read-only MongoDB security-master pipeline (`read-exchanges` -> `read-sources` -> `compute-bar-spans` -> `composeSecurityMasterRun`) and writes deterministic report artifacts, with opt-in PostgreSQL persistence via `--persist`. + +### Dry run (read-only MongoDB, zero PostgreSQL connections) +```bash +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \ + --as-of 2026-01-15 \ + --out-dir ./tmp/security-master-report +``` + +### Persist to isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`) +Ensure the `master` track migrations have been applied to dev PostgreSQL first (`bun run db:migrate --track master`), then run with `--persist`: + +```bash +NODE_ENV=development \ +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ +POSTGRES_HOST=localhost \ +POSTGRES_PORT=5433 \ +POSTGRES_DB=trading_bot_dev \ + bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \ + --as-of 2026-01-15 \ + --out-dir ./tmp/security-master-report \ + --persist +``` + +- **Safety guards:** MongoDB is always opened with `mongoReadOnly: true` via `MONGODB_READ_URI`. Without `--persist`, no PostgreSQL client is constructed. With `--persist`, `assertEnvironmentSafety()` runs before opening PostgreSQL (with `STOCK_BOT_ALLOW_DEV_ON_QA_DB` stripped) so `development` runs cannot write to QA PostgreSQL (`localhost:5432/trading_bot`). +- **Pass 4 status:** Pass 4 cross-sectional price cross-check input (`sampleCloses` / `fxRates`) is **not yet wired** into this CLI; `composeSecurityMasterRun` is invoked without sample closes and Pass 4 is explicitly reported as `skipped` (`pass4: null`). + +### Output files (`--out-dir`) +All four files are deterministic and byte-identical for identical inputs (no wall-clock timestamps or output paths): +- `match-report.md` — Human-readable match report covering exchange coverage, per-source/per-country resolution, unresolved breakdowns, Pass 4 (`skipped`), Pass 6 delisting chains, and conflicts. +- `conflicts.csv` — Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6. +- `override-template.sql` — Commented SQL template for director-reviewed `override` entries. +- `run-stats.json` — Canonical ASCII-key-sorted JSON summary of exchange, reader, security-type, bar-span, composer, and report stats (`pass4Wired: false`). diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 4bcf0994..c10ee95e 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -215,6 +215,19 @@ export { type StageBComposeStepStats, } from './run'; +export { + formatRunSecurityMasterSummary, + parseRunSecurityMasterArgs, + RUN_SECURITY_MASTER_USAGE, + runSecurityMaster, + SECURITY_MASTER_OUTPUT_FILES, + type ParsedRunSecurityMasterArgs, + type RunSecurityMasterDeps, + type RunSecurityMasterOptions, + type RunSecurityMasterOutput, + type SecurityMasterPostgresHandle, +} from './run-security-master'; + export { buildSecurityTypeByIsin, buildSecurityTypeByIsinForStageA, diff --git a/apps/stock/data-pipeline/src/security-master/run-security-master.ts b/apps/stock/data-pipeline/src/security-master/run-security-master.ts new file mode 100644 index 00000000..1834900e --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run-security-master.ts @@ -0,0 +1,642 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { getLogger } from '@stock-bot/logger'; +import { MongoDBClient } from '@stock-bot/mongodb'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { assertEnvironmentSafety, initializeStockConfig } from '@stock-bot/stock-config'; +import { + computeBarSpans, + normalizeBarDate, + type BarSpanAggregateReader, + type ComputeBarSpansOptions, + type ComputeBarSpansResult, +} from '../normalization/bar-spans'; +import { + classifySourceExchanges, + compareAscii, + EXCHANGE_SOURCES, + ISO_EXCHANGE_SEEDS, + normalizeRawExchangeDoc, + type ExchangeClassificationResult, + type ExchangeSource, + type SourceExchangeRecord, +} from './exchange-pass1'; +import { + resolveReadOnlyMongoClientConfig, + SOURCE_EXCHANGE_COLLECTIONS, +} from './generate-exchange-seed'; +import { + canonicalizeJsonValue, + persistSecurityMaster, + type PersistSecurityMasterResult, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, +} from './persist'; +import { composeSecurityMasterRun, type ComposeSecurityMasterRunResult } from './run'; +import { + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + readSecurityMasterSources, + type ExchangeSourceLookup, + type ReadOnlyMongoCollectionClient, + type SecurityMasterSourcesResult, +} from './source-symbol-readers'; + +export const SECURITY_MASTER_OUTPUT_FILES = Object.freeze({ + matchReport: 'match-report.md', + conflictsCsv: 'conflicts.csv', + overrideTemplateSql: 'override-template.sql', + runStatsJson: 'run-stats.json', +} as const); + +export const RUN_SECURITY_MASTER_USAGE = [ + 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of --out-dir [--persist] [--help]', + '', + 'Options:', + ' --as-of Required. Calendar reference date for Pass 6 delisting classification.', + ' --out-dir Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.', + ' --persist Optional. Persist security-master rows to PostgreSQL after running assertEnvironmentSafety() (default: off).', + ' --help Show this help message and exit.', +].join('\n'); + +export type ParsedRunSecurityMasterArgs = + | { readonly help: true } + | { + readonly help: false; + readonly asOfDate: string; + readonly outDir: string; + readonly persist: boolean; + }; + +export interface SecurityMasterPostgresHandle { + readonly queryable: SecurityMasterQueryable; + close(): Promise | void; +} + +export interface RunSecurityMasterDeps { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly barSpanReader: BarSpanAggregateReader; + readonly closeMongo?: () => Promise | void; + readonly exchangeClassification?: ExchangeClassificationResult; + readonly exchangeLookup?: ExchangeSourceLookup; + readonly assertSafety?: () => void; + readonly createPostgresClient?: () => + | Promise + | SecurityMasterPostgresHandle; + readonly persistFn?: typeof persistSecurityMaster; + readonly writeFile?: (filePath: string, content: string) => Promise | void; + readonly writeStdout?: (text: string) => void; +} + +export interface RunSecurityMasterOptions { + readonly asOfDate: string; + readonly outDir: string; + readonly persist?: boolean; + readonly countries?: readonly string[] | null; + readonly batchSize?: number; + readonly barSpans?: Omit; +} + +export interface RunSecurityMasterOutput { + readonly asOfDate: string; + readonly outDir: string; + readonly persist: boolean; + readonly filesWritten: readonly string[]; + readonly exchanges: ExchangeClassificationResult; + readonly exchangeCountsByCollection: Readonly>; + readonly sources: SecurityMasterSourcesResult; + readonly barSpans: ComputeBarSpansResult; + readonly composed: ComposeSecurityMasterRunResult; + readonly persistResult: PersistSecurityMasterResult | null; + readonly runStatsJson: string; + readonly summary: string; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +function isValidAsOfDate(value: string): boolean { + return EXACT_YMD_PATTERN.test(value) && normalizeBarDate(value) === value; +} + +function usageError(message: string): Error { + return new Error(`${message}\n\n${RUN_SECURITY_MASTER_USAGE}`); +} + +function wrapStepError(step: string, error: unknown): Error { + const detail = error instanceof Error ? error.message : String(error); + return new Error(`Security master step "${step}" failed: ${detail}`, { cause: error }); +} + +function collectSortedUniqueIds(ids: readonly string[]): string[] { + const unique = new Set(); + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + if (typeof id === 'string' && id.length > 0) { + unique.add(id); + } + } + return Array.from(unique).sort(compareAscii); +} + +async function defaultWriteFile(filePath: string, content: string): Promise { + await mkdir(dirname(filePath), { recursive: true }); + await writeFile(filePath, content, 'utf8'); +} + +export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSecurityMasterArgs { + let help = false; + let asOfDate: string | undefined; + let outDir: string | undefined; + let persist = false; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help') { + help = true; + continue; + } + if (arg === '--persist') { + persist = true; + continue; + } + if (arg === '--as-of') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --as-of'); + } + asOfDate = value; + i += 1; + continue; + } + if (arg?.startsWith('--as-of=')) { + const value = arg.slice('--as-of='.length); + if (value.trim().length === 0) { + throw usageError('Missing value for --as-of'); + } + asOfDate = value; + continue; + } + if (arg === '--out-dir') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --out-dir'); + } + outDir = value; + i += 1; + continue; + } + if (arg?.startsWith('--out-dir=')) { + const value = arg.slice('--out-dir='.length); + if (value.trim().length === 0) { + throw usageError('Missing value for --out-dir'); + } + outDir = value; + continue; + } + throw usageError(`Unknown argument: ${String(arg)}`); + } + + if (help) { + return { help: true }; + } + + if (asOfDate === undefined) { + throw usageError('Missing required argument: --as-of '); + } + if (!isValidAsOfDate(asOfDate)) { + throw usageError( + `Invalid --as-of date "${asOfDate}": expected a valid calendar date in YYYY-MM-DD format` + ); + } + if (outDir === undefined || outDir.trim().length === 0) { + throw usageError('Missing required argument: --out-dir '); + } + + return { + help: false, + asOfDate, + outDir, + persist, + }; +} + +export function formatRunSecurityMasterSummary( + params: Pick< + RunSecurityMasterOutput, + 'asOfDate' | 'outDir' | 'persist' | 'filesWritten' | 'composed' + > +): string { + const { asOfDate, outDir, persist, composed } = params; + const resolutionParts = composed.report.resolutionBySource.map(row => { + const pct = + row.eligibleResolvedPct === null + ? 'n/a' + : `${(row.eligibleResolvedPct * 100).toFixed(1)}%`; + return `${row.source}=${pct} (${row.matched}/${row.eligibleTotal})`; + }); + + const fileNames = [ + SECURITY_MASTER_OUTPUT_FILES.matchReport, + SECURITY_MASTER_OUTPUT_FILES.conflictsCsv, + SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql, + SECURITY_MASTER_OUTPUT_FILES.runStatsJson, + ]; + + const lines = [ + `Security master run complete (as-of ${asOfDate})`, + ` Instruments: ${composed.stageA.instruments.length} | Listings: ${composed.stageB.listings.length} | Conflicts: ${composed.report.conflicts.length}`, + ` Resolution (eligible): ${resolutionParts.length > 0 ? resolutionParts.join(', ') : 'none'}`, + ` Pass 4 price cross-check: ${composed.stats.pass4.status} (sample closes not yet wired)`, + ` Files written (${outDir}): ${fileNames.join(', ')}`, + ` Persisted: ${persist ? 'yes' : 'no (dry-run)'}`, + ]; + + return `${lines.join('\n')}\n`; +} + +export async function runSecurityMaster( + deps: RunSecurityMasterDeps, + options: RunSecurityMasterOptions +): Promise { + const persist = options.persist === true; + let mongoCloseError: unknown = null; + let output: RunSecurityMasterOutput; + + try { + if (!isValidAsOfDate(options.asOfDate)) { + throw wrapStepError( + 'validate-options', + new Error( + `Invalid asOfDate "${options.asOfDate}": expected a valid calendar date in YYYY-MM-DD format` + ) + ); + } + if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) { + throw wrapStepError('validate-options', new Error('outDir must be a non-empty string')); + } + + // Step 1: Environment safety check before opening PostgreSQL or reading Mongo when --persist is requested. + if (persist) { + try { + if (typeof deps.assertSafety !== 'function') { + throw new Error( + 'Persisting security master requires an assertSafety guard to be configured' + ); + } + if (typeof deps.createPostgresClient !== 'function') { + throw new Error( + 'Persisting security master requires a createPostgresClient factory to be configured' + ); + } + deps.assertSafety(); + } catch (error) { + throw wrapStepError('env-safety', error); + } + } + + // Step 2: Read-only exchange classification (Pass 1) and lookup construction. + let sourceReader: ReturnType; + let exchanges: ExchangeClassificationResult; + let exchangeLookup: ExchangeSourceLookup; + const exchangeCountsByCollection: Record = { + eod: 0, + ib: 0, + qm: 0, + ceo: 0, + }; + + try { + sourceReader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient); + + if (deps.exchangeClassification !== undefined) { + exchanges = deps.exchangeClassification; + } else { + const normalizedRecords: SourceExchangeRecord[] = []; + for (const source of EXCHANGE_SOURCES) { + const collectionName = SOURCE_EXCHANGE_COLLECTIONS[source]; + const cursor = await sourceReader.find>(collectionName, {}); + let count = 0; + for await (const doc of cursor) { + count += 1; + normalizedRecords.push(normalizeRawExchangeDoc(source, doc)); + } + exchangeCountsByCollection[source] = count; + } + exchanges = classifySourceExchanges(normalizedRecords, { + knownExchanges: ISO_EXCHANGE_SEEDS, + }); + } + + exchangeLookup = deps.exchangeLookup ?? createExchangeSourceLookup(exchanges.mapped); + } catch (error) { + throw wrapStepError('read-exchanges', error); + } + + // Step 3: Stream read-only symbol collections into Stage A / Stage B inputs. + let sources: SecurityMasterSourcesResult; + try { + sources = await readSecurityMasterSources(sourceReader, { + exchangeLookup, + countries: options.countries, + batchSize: options.batchSize, + }); + } catch (error) { + throw wrapStepError('read-sources', error); + } + + // Step 4: Compute targeted observed bar spans for in-scope EOD and QM listings. + let barSpans: ComputeBarSpansResult; + try { + const eodIds = collectSortedUniqueIds( + sources.stageBInput.eodListings.map(entry => entry.sourceId) + ); + const qmIds = collectSortedUniqueIds( + sources.stageBInput.tickerSources + .filter(entry => entry.source === 'qm') + .map(entry => entry.sourceId) + ); + barSpans = await computeBarSpans(deps.barSpanReader, { + sources: ['eod', 'qm'], + ...options.barSpans, + sourceIdsBySource: { + eod: eodIds, + qm: qmIds, + }, + }); + } catch (error) { + throw wrapStepError('compute-bar-spans', error); + } + + // Step 5: Compose Stage A -> Stage B -> Pass 6 -> Report + PersistInput (Pass 4 omitted). + let composed: ComposeSecurityMasterRunResult; + try { + composed = composeSecurityMasterRun( + { + sources, + barSpans, + exchanges, + }, + { + asOfDate: options.asOfDate, + } + ); + } catch (error) { + throw wrapStepError('compose', error); + } + + // Step 6: Write deterministic artifacts into outDir. + const statsArtifact = { + asOfDate: options.asOfDate, + pass4Wired: false, + exchanges: { + countsByCollection: exchangeCountsByCollection, + mapped: exchanges.mapped.length, + unresolved: exchanges.unresolved.length, + total: exchanges.mapped.length + exchanges.unresolved.length, + }, + readers: sources.stats, + securityTypes: { + stats: sources.securityTypeStats, + loaderStats: sources.securityTypeLoaderStats, + unknownCount: sources.unknownSecurityTypes.length, + conflictCount: sources.securityTypeConflicts.length, + }, + barSpans: { + bySource: barSpans.bySource, + skipped: barSpans.skipped, + totalRowsRead: barSpans.totalRowsRead, + totalSpans: barSpans.totalSpans, + }, + compose: composed.stats, + reportSummary: { + instruments: composed.stageA.instruments.length, + listings: composed.stageB.listings.length, + providerMappings: composed.stageB.providerMappings.length, + conflicts: composed.report.conflicts.length, + exchangeCoverage: composed.report.exchangeCoverage, + resolutionBySource: composed.report.resolutionBySource, + resolutionByCountry: composed.report.resolutionByCountry, + meetsExitThresholds: composed.report.meetsExitThresholds, + }, + }; + const runStatsJson = `${JSON.stringify(canonicalizeJsonValue(statsArtifact), null, 2)}\n`; + + const writer = deps.writeFile ?? defaultWriteFile; + const filesToWrite: ReadonlyArray = [ + [join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), composed.reportMarkdown], + [join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), composed.conflictsCsv], + [ + join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql), + composed.overrideTemplateSql, + ], + [join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), runStatsJson], + ]; + const filesWritten = filesToWrite.map(([filePath]) => filePath); + + try { + for (const [filePath, content] of filesToWrite) { + await writer(filePath, content); + } + } catch (error) { + throw wrapStepError('write-files', error); + } + + // Step 7: Optional persistence to PostgreSQL (only when --persist is enabled). + let persistResult: PersistSecurityMasterResult | null = null; + if (persist) { + try { + const createPg = deps.createPostgresClient; + if (typeof createPg !== 'function') { + throw new Error( + 'Persisting security master requires a createPostgresClient factory to be configured' + ); + } + const pgHandle = await createPg(); + let pgCloseError: unknown = null; + try { + const persistFn = deps.persistFn ?? persistSecurityMaster; + persistResult = await persistFn(pgHandle.queryable, composed.persistInput); + } finally { + try { + await pgHandle.close(); + } catch (closeError) { + pgCloseError = closeError; + } + } + if (pgCloseError !== null) { + throw pgCloseError; + } + } catch (error) { + throw wrapStepError('persist', error); + } + } + + // Step 8: Emit concise one-screen summary after all steps succeed. + const summary = formatRunSecurityMasterSummary({ + asOfDate: options.asOfDate, + outDir: options.outDir, + persist, + filesWritten, + composed, + }); + const writeStdout = + deps.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(summary); + + output = { + asOfDate: options.asOfDate, + outDir: options.outDir, + persist, + filesWritten, + exchanges, + exchangeCountsByCollection, + sources, + barSpans, + composed, + persistResult, + runStatsJson, + summary, + }; + } finally { + if (deps.closeMongo) { + try { + await deps.closeMongo(); + } catch (closeError) { + mongoCloseError = closeError; + } + } + } + + if (mongoCloseError !== null) { + throw wrapStepError('close-mongo', mongoCloseError); + } + + return output; +} + +export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { + const parsed = parseRunSecurityMasterArgs(argv); + if (parsed.help) { + process.stdout.write(`${RUN_SECURITY_MASTER_USAGE}\n`); + return; + } + + const logger = getLogger('security-master-run-cli'); + const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + const mongoConfig = resolveReadOnlyMongoClientConfig(config); + const mongo = new MongoDBClient(mongoConfig, logger); + + await mongo.connect(); + + const assertSafety = (): void => { + if (!config.database.postgres.enabled) { + throw new Error('PostgreSQL is disabled in configuration; cannot run with --persist'); + } + const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = process.env; + assertEnvironmentSafety(config, 'dataPipeline', safeEnv); + }; + + const createPostgresClient = async (): Promise => { + const pg = config.database.postgres; + const pgClient = new PostgreSQLClient( + { + host: pg.host, + port: pg.port, + database: pg.database, + username: pg.user, + password: pg.password, + poolSettings: { + min: 1, + max: Math.max(1, pg.poolSize), + idleTimeoutMillis: pg.idleTimeout, + }, + ssl: { + enabled: pg.ssl, + rejectUnauthorized: true, + }, + timeouts: { + connection: pg.connectionTimeout, + }, + }, + logger + ); + + await pgClient.connect(); + try { + const pool = pgClient.connectionPool; + if (!pool) { + throw new Error('PostgreSQL connection pool was not initialized after connect()'); + } + const poolClient = await pool.connect(); + const queryable: SecurityMasterQueryable = { + query>( + text: string, + values?: readonly unknown[] + ): Promise> { + return poolClient.query( + text, + values === undefined ? undefined : [...values] + ) as unknown as Promise>; + }, + release: () => { + poolClient.release(); + }, + }; + let closed = false; + return { + queryable, + async close(): Promise { + if (closed) { + return; + } + closed = true; + let releaseError: unknown = null; + try { + poolClient.release(); + } catch (error) { + releaseError = error; + } + try { + await pgClient.disconnect(); + } catch (disconnectError) { + if (releaseError === null) { + throw disconnectError; + } + } + if (releaseError !== null) { + throw releaseError; + } + }, + }; + } catch (error) { + await pgClient.disconnect().catch(() => {}); + throw error; + } + }; + + await runSecurityMaster( + { + mongoCollectionClient: mongo, + barSpanReader: mongo, + closeMongo: () => mongo.disconnect(), + assertSafety, + createPostgresClient, + }, + { + asOfDate: parsed.asOfDate, + outDir: parsed.outDir, + persist: parsed.persist, + } + ); +} + +if (import.meta.main) { + runCli().catch(error => { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`Error: ${message}\n`); + process.exit(1); + }); +} diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts new file mode 100644 index 00000000..22c151f9 --- /dev/null +++ b/test/unit/security-master-run-cli.test.ts @@ -0,0 +1,919 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { assertEnvironmentSafety, stockAppSchema } from '@stock-bot/stock-config'; +import { + computeBarSpans, + type BarSpanAggregateReader, + type GroupedBarSpanRow, +} from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { + classifySourceExchanges, + compareAscii, + composeSecurityMasterRun, + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + EXCHANGE_SOURCES, + ISO_EXCHANGE_SEEDS, + normalizeRawExchangeDoc, + parseRunSecurityMasterArgs, + readSecurityMasterSources, + RUN_SECURITY_MASTER_USAGE, + runSecurityMaster, + SECURITY_MASTER_OUTPUT_FILES, + SOURCE_EXCHANGE_COLLECTIONS, + type PersistSecurityMasterInput, + type PersistSecurityMasterResult, + type ReadOnlyMongoCollectionClient, + type SecurityMasterPostgresHandle, + type SecurityMasterQueryable, + type SourceExchangeRecord, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const cliSourcePath = fileURLToPath( + new URL( + '../../apps/stock/data-pipeline/src/security-master/run-security-master.ts', + import.meta.url + ) +); + +const tempDirs: string[] = []; + +function createTempDir(prefix = 'sm-run-cli-'): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) { + rmSync(dir, { recursive: true, force: true }); + } + } +}); + +interface FakeMongoFixture { + readonly collections: Readonly[]>>; + readonly barSpanRowsByCollection?: Readonly>; +} + +function makeAsyncCursor(docs: readonly Record[]) { + let closed = false; + return { + async *[Symbol.asyncIterator](): AsyncIterator> { + for (const doc of docs) { + if (closed) { + break; + } + yield doc; + } + }, + async close(): Promise { + closed = true; + }, + }; +} + +function extractRequestedIdsFromPipeline(pipeline: readonly Record[]): Set | null { + for (const stage of pipeline) { + const match = stage.$match; + if (match && typeof match === 'object') { + for (const value of Object.values(match as Record)) { + if (value && typeof value === 'object' && Array.isArray((value as { $in?: unknown }).$in)) { + return new Set(((value as { $in: unknown[] }).$in).map(String)); + } + } + } + } + return null; +} + +function createStrictReadOnlyFakeMongo( + fixture: FakeMongoFixture, + options: { + readonly readOnly?: boolean; + readonly failCollection?: string; + readonly failAggregate?: boolean; + } = {} +): { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly barSpanReader: BarSpanAggregateReader; + readonly aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }>; + readonly findCalls: string[]; +} { + const readOnly = options.readOnly ?? true; + const aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }> = []; + const findCalls: string[] = []; + + const target = { + isReadOnly(): boolean { + return readOnly; + }, + getCollection(collectionName: string) { + const colTarget = { + find(_filter: Record = {}) { + findCalls.push(collectionName); + if (options.failCollection === collectionName) { + throw new Error(`Simulated Mongo find failure on ${collectionName}`); + } + const docs = fixture.collections[collectionName] ?? []; + return makeAsyncCursor(docs); + }, + }; + + return new Proxy(colTarget, { + get(obj, prop, receiver) { + if (prop === 'find') { + return Reflect.get(obj, prop, receiver); + } + throw new Error(`Forbidden MongoDB collection method called: ${String(prop)}`); + }, + }); + }, + aggregate = Record>( + collectionName: string, + pipeline: Record[] + ): AsyncIterable { + aggregateCalls.push({ collectionName, pipeline }); + if (options.failAggregate) { + throw new Error(`Simulated Mongo aggregate failure on ${collectionName}`); + } + const allRows = fixture.barSpanRowsByCollection?.[collectionName] ?? []; + const requestedIds = extractRequestedIdsFromPipeline(pipeline); + const filtered = + requestedIds === null + ? allRows + : allRows.filter(row => typeof row._id === 'string' && requestedIds.has(row._id)); + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (const row of filtered) { + yield row as unknown as T; + } + }, + }; + }, + }; + + const proxy = new Proxy(target, { + get(obj, prop, receiver) { + if (prop === 'isReadOnly' || prop === 'getCollection' || prop === 'aggregate') { + return Reflect.get(obj, prop, receiver); + } + throw new Error(`Forbidden MongoDB client method called: ${String(prop)}`); + }, + }); + + return { + mongoCollectionClient: proxy as unknown as ReadOnlyMongoCollectionClient, + barSpanReader: proxy as unknown as BarSpanAggregateReader, + aggregateCalls, + findCalls, + }; +} + +function buildUsCaFixture(): FakeMongoFixture { + return { + collections: { + eodExchanges: [ + { Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' }, + { Code: 'TO', Name: 'Toronto Exchange', Country: 'Canada', Currency: 'CAD', OperatingMIC: 'XTSE' }, + ], + ibExchanges: [ + { exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' }, + { exchange: 'TSE', country: 'CA', currency: 'CAD', mic: 'XTSE' }, + ], + qmExchanges: [ + { exchange: 'NSD', country: 'US', currency: 'USD' }, + { exchange: 'TSX', country: 'CA', currency: 'CAD' }, + ], + ceoExchanges: [], + eodSymbols: [ + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Cusip: '037833100', + Name: 'Apple Inc.', + Type: 'Common Stock', + delisted: false, + }, + { + eodSearchCode: 'SHOP.TO', + Code: 'SHOP', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA82509L1076', + Cusip: '82509L107', + Name: 'Shopify Inc.', + Type: 'Common Stock', + delisted: false, + }, + ], + ibSymbols: [ + { + conid: 265598, + symbol: 'AAPL', + localSymbol: 'AAPL', + primaryExchange: 'NASDAQ', + country: 'US', + currency: 'USD', + isin: 'US0378331005', + cusip: '037833100', + name: 'Apple Inc.', + }, + ], + qmSymbols: [ + { + qmSearchCode: 'AAPL:US', + symbol: 'AAPL', + exchange: 'NSD', + countryCode: 'US', + currency: 'USD', + name: 'Apple Inc.', + active: true, + }, + { + // Unresolved symbol: no matching EOD/IB instrument or listing on XTSE. + qmSearchCode: 'MYSTERY:CA', + symbol: 'MYSTERY', + exchange: 'TSX', + countryCode: 'CA', + currency: 'CAD', + name: 'Mystery Corp', + active: true, + }, + ], + ceoSymbols: [], + eodSymbolChange: [], + }, + barSpanRowsByCollection: { + eodPrices: [ + { _id: 'AAPL.US', firstBarDate: '2015-01-02', lastBarDate: '2026-01-14', barCount: 2770 }, + { _id: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2026-01-14', barCount: 2680 }, + ], + qmPrices: [ + { _id: 'AAPL:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 }, + { _id: 'MYSTERY:CA', firstBarDate: '2022-01-03', lastBarDate: '2025-12-31', barCount: 990 }, + ], + }, + }; +} + +function makeFakePersistResult(): PersistSecurityMasterResult { + return { + instrumentsInserted: 2, + instrumentsUpdated: 0, + instrumentsUnchanged: 0, + instrumentsSkipped: 0, + identifierHistoryInserted: 4, + identifierHistoryUnchanged: 0, + listingsInserted: 2, + listingsUpdated: 0, + listingsUnchanged: 0, + listingsSkipped: 0, + listingSymbolHistoryInserted: 2, + listingSymbolHistoryUpdated: 0, + listingSymbolHistoryUnchanged: 0, + providerMappingsInserted: 4, + providerMappingsUpdated: 0, + providerMappingsUnchanged: 0, + providerMappingsSkipped: 0, + overridesApplied: 0, + conflictsInserted: 0, + conflictsUnchanged: 0, + conflictsDeduplicated: 0, + pass6OutcomesApplied: 2, + pass6OutcomesSkipped: 0, + continuitiesInserted: 0, + continuitiesUpdated: 0, + continuitiesUnchanged: 0, + continuitiesSkipped: 0, + skippedByReason: { + instruments: { missing_canonical_name: 0, missing_security_type: 0 }, + listings: { skipped_instrument: 0, missing_instrument: 0, unknown_mic: 0 }, + providerMappings: { missing_listing: 0 }, + pass6Outcomes: { missing_listing: 0 }, + continuities: { + missing_from_listing: 0, + missing_to_listing: 0, + missing_both_listings: 0, + }, + }, + instrumentIdByIsin: new Map(), + listingIdByKey: new Map(), + }; +} + +function assertObjectKeysSortedAscii(value: unknown, path = '$'): void { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + assertObjectKeysSortedAscii(value[i], `${path}[${i}]`); + } + return; + } + if (value !== null && typeof value === 'object') { + const keys = Object.keys(value as Record); + const sorted = [...keys].sort(compareAscii); + expect(keys, `Keys not ASCII-sorted at ${path}`).toEqual(sorted); + for (const key of keys) { + assertObjectKeysSortedAscii((value as Record)[key], `${path}.${key}`); + } + } +} + +describe('parseRunSecurityMasterArgs', () => { + test('parses required space-separated args with default persist=false', () => { + const parsed = parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './tmp/out']); + expect(parsed).toEqual({ + help: false, + asOfDate: '2026-01-15', + outDir: './tmp/out', + persist: false, + }); + }); + + test('parses = syntax, leap day, and --persist flag', () => { + const parsed = parseRunSecurityMasterArgs([ + '--as-of=2024-02-29', + '--out-dir=/tmp/sm-report', + '--persist', + ]); + expect(parsed).toEqual({ + help: false, + asOfDate: '2024-02-29', + outDir: '/tmp/sm-report', + persist: true, + }); + }); + + test('returns { help: true } for --help without requiring other flags', () => { + expect(parseRunSecurityMasterArgs(['--help'])).toEqual({ help: true }); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--as-of'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--out-dir'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--persist'); + }); + + test('rejects missing --as-of or --out-dir', () => { + expect(() => parseRunSecurityMasterArgs(['--out-dir', './out'])).toThrow(/--as-of/); + expect(() => parseRunSecurityMasterArgs(['--as-of', '2026-01-15'])).toThrow(/--out-dir/); + }); + + test('rejects invalid calendar dates, compact dates, and timestamps', () => { + for (const badDate of ['2026-13-40', '20260101', '2023-02-29', '2026-01-15T00:00:00Z']) { + expect(() => + parseRunSecurityMasterArgs(['--as-of', badDate, '--out-dir', './out']) + ).toThrow(/Invalid --as-of date/); + } + }); + + test('rejects unknown flags, positional args, and flags missing values', () => { + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--unknown']) + ).toThrow(/Unknown argument: --unknown/); + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', 'positional']) + ).toThrow(/Unknown argument: positional/); + expect(() => + parseRunSecurityMasterArgs(['--as-of', '--out-dir', '/tmp']) + ).toThrow(/Missing value for --as-of/); + expect(() => + parseRunSecurityMasterArgs(['--as-of=2026-01-15', '--out-dir=']) + ).toThrow(/Missing value for --out-dir/); + expect(() => + parseRunSecurityMasterArgs(['--as-of=', '--out-dir=/tmp']) + ).toThrow(/Missing value for --as-of/); + }); +}); + +describe('runSecurityMaster', () => { + test('happy path writes all four files matching composeSecurityMasterRun byte-for-byte', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = join(createTempDir(), 'nested-report'); + const stdoutChunks: string[] = []; + let mongoClosed = 0; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { + asOfDate: '2026-01-15', + outDir, + } + ); + + // Independently compute expected composeSecurityMasterRun output from the same fixture. + const refMongo = createStrictReadOnlyFakeMongo(fixture); + const refReader = createReadOnlyMongoSourceSymbolReader(refMongo.mongoCollectionClient); + const exchangeRecords: SourceExchangeRecord[] = []; + for (const source of EXCHANGE_SOURCES) { + const cursor = await refReader.find>( + SOURCE_EXCHANGE_COLLECTIONS[source], + {} + ); + for await (const doc of cursor) { + exchangeRecords.push(normalizeRawExchangeDoc(source, doc)); + } + } + const expectedExchanges = classifySourceExchanges(exchangeRecords, { + knownExchanges: ISO_EXCHANGE_SEEDS, + }); + const expectedSources = await readSecurityMasterSources(refReader, { + exchangeLookup: createExchangeSourceLookup(expectedExchanges.mapped), + }); + const expectedBarSpans = await computeBarSpans(refMongo.barSpanReader, { + sources: ['eod', 'qm'], + sourceIdsBySource: { + eod: ['AAPL.US', 'SHOP.TO'], + qm: ['AAPL:US', 'MYSTERY:CA'], + }, + }); + const expectedComposed = composeSecurityMasterRun( + { + sources: expectedSources, + barSpans: expectedBarSpans, + exchanges: expectedExchanges, + }, + { asOfDate: '2026-01-15' } + ); + + const matchReportContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), + 'utf8' + ); + const conflictsCsvContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), + 'utf8' + ); + const overrideTemplateContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql), + 'utf8' + ); + const runStatsContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), + 'utf8' + ); + + expect(matchReportContent).toBe(expectedComposed.reportMarkdown); + expect(conflictsCsvContent).toBe(expectedComposed.conflictsCsv); + expect(overrideTemplateContent).toBe(expectedComposed.overrideTemplateSql); + + expect(runStatsContent.endsWith('\n')).toBe(true); + const parsedStats = JSON.parse(runStatsContent) as Record; + assertObjectKeysSortedAscii(parsedStats); + expect(parsedStats.asOfDate).toBe('2026-01-15'); + expect(parsedStats.pass4Wired).toBe(false); + expect(result.composed.pass4).toBeNull(); + expect(result.composed.stageA.instruments.length).toBe(2); + expect(result.composed.stageB.unresolved.some(u => u.sourceId === 'MYSTERY:CA')).toBe(true); + + expect(mongoClosed).toBe(1); + const summaryText = stdoutChunks.join(''); + expect(summaryText).toContain('Instruments: 2'); + expect(summaryText).toContain('Persisted: no (dry-run)'); + expect(summaryText).toContain('match-report.md'); + expect(summaryText).toContain('skipped'); + }); + + test('produces byte-identical files across repeated runs in different output directories', async () => { + const fixture = buildUsCaFixture(); + const outDir1 = createTempDir('sm-replay-1-'); + const outDir2 = createTempDir('sm-replay-2-'); + + const mongo1 = createStrictReadOnlyFakeMongo(fixture); + const mongo2 = createStrictReadOnlyFakeMongo(fixture); + + await runSecurityMaster( + { + mongoCollectionClient: mongo1.mongoCollectionClient, + barSpanReader: mongo1.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: outDir1 } + ); + await runSecurityMaster( + { + mongoCollectionClient: mongo2.mongoCollectionClient, + barSpanReader: mongo2.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: outDir2 } + ); + + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + const content1 = readFileSync(join(outDir1, filename), 'utf8'); + const content2 = readFileSync(join(outDir2, filename), 'utf8'); + expect(content2, `${filename} differed between runs`).toBe(content1); + } + }); + + test('dry run never invokes PostgreSQL factory or persist function', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir(); + let pgFactoryCalls = 0; + let queryCalls = 0; + let persistCalls = 0; + let mongoClosed = 0; + + const fakeQueryable: SecurityMasterQueryable = { + async query() { + queryCalls += 1; + return { rows: [] }; + }, + }; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + createPostgresClient: () => { + pgFactoryCalls += 1; + return { queryable: fakeQueryable, close: () => {} }; + }, + persistFn: async () => { + persistCalls += 1; + return makeFakePersistResult(); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir, persist: false } + ); + + expect(result.persist).toBe(false); + expect(result.persistResult).toBeNull(); + expect(pgFactoryCalls).toBe(0); + expect(queryCalls).toBe(0); + expect(persistCalls).toBe(0); + expect(mongoClosed).toBe(1); + }); + + test('--persist invokes env-safety guard before PostgreSQL factory and calls persistFn once', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir(); + const callOrder: string[] = []; + const capturedInputs: PersistSecurityMasterInput[] = []; + const stdoutChunks: string[] = []; + + const fakeQueryable: SecurityMasterQueryable = { + async query() { + return { rows: [] }; + }, + }; + let receivedQueryable: SecurityMasterQueryable | null = null; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + callOrder.push('closeMongo'); + }, + assertSafety: () => { + callOrder.push('assertSafety'); + }, + createPostgresClient: (): SecurityMasterPostgresHandle => { + callOrder.push('createPostgresClient'); + return { + queryable: fakeQueryable, + close: () => { + callOrder.push('closePostgres'); + }, + }; + }, + persistFn: async (queryable, input) => { + callOrder.push('persistFn'); + receivedQueryable = queryable; + capturedInputs.push(input); + return makeFakePersistResult(); + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { asOfDate: '2026-01-15', outDir, persist: true } + ); + + expect(callOrder).toEqual([ + 'assertSafety', + 'createPostgresClient', + 'persistFn', + 'closePostgres', + 'closeMongo', + ]); + expect(capturedInputs).toHaveLength(1); + expect(capturedInputs[0]).toEqual(result.composed.persistInput); + expect(receivedQueryable === fakeQueryable).toBe(true); + expect(result.persistResult).not.toBeNull(); + expect(stdoutChunks.join('')).toContain('Persisted: yes'); + }); + + test('env-safety guard throwing rejects with step name, never opens PostgreSQL, and closes Mongo', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir(); + let pgFactoryCalls = 0; + let mongoClosed = 0; + const stdoutChunks: string[] = []; + const safetyErr = new Error('Safety guard: blocked QA PostgreSQL'); + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => { + throw safetyErr; + }, + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('should not be called'); + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { asOfDate: '2026-01-15', outDir, persist: true } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('env-safety'); + expect((caught as Error).cause).toBe(safetyErr); + expect(pgFactoryCalls).toBe(0); + expect(mongoClosed).toBe(1); + expect(stdoutChunks).toHaveLength(0); + }); + + test('real assertEnvironmentSafety rejects development config targeting QA PostgreSQL 5432/trading_bot', () => { + const devQaPgConfig = stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: 'development', + service: { + name: 'data-pipeline', + port: 2002, + }, + log: { + level: 'info', + }, + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5432, + database: 'trading_bot', + user: 'trading_user', + password: 'dev_password', + }, + mongodb: { + enabled: true, + uri: 'mongodb://localhost:27018/stock_dev', + readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock', + readOnly: true, + database: 'stock_dev', + }, + questdb: { enabled: false }, + dragonfly: { enabled: false }, + }, + providers: {}, + features: {}, + }); + + expect(() => assertEnvironmentSafety(devQaPgConfig, 'dataPipeline', {})).toThrow( + /Safety guard: development environment cannot target QA PostgreSQL/ + ); + }); + + test('reader, bar-span, file-write, and persist failures wrap step name, suppress summary, and close clients', async () => { + const fixture = buildUsCaFixture(); + + // 1. Reader failure (source symbol collection) + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture, { failCollection: 'eodSymbols' }); + let mongoClosed = 0; + const stdout: string[] = []; + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('read-sources'); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + + // 2. Bar-span failure + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture, { failAggregate: true }); + let mongoClosed = 0; + const stdout: string[] = []; + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('compute-bar-spans'); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + + // 3. File-write failure + secondary closeMongo error does not mask primary error + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + let mongoClosed = 0; + const stdout: string[] = []; + const writeErr = new Error('ENOSPC: disk full'); + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + throw new Error('secondary disconnect error'); + }, + writeFile: () => { + throw writeErr; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('write-files'); + expect((caught as Error).cause).toBe(writeErr); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + + // 4. Persist failure closes both PostgreSQL handle and MongoDB client + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + let mongoClosed = 0; + let pgClosed = 0; + const stdout: string[] = []; + const persistErr = new Error('deadlock detected'); + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => { + pgClosed += 1; + }, + }), + persistFn: async () => { + throw persistErr; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('persist'); + expect((caught as Error).cause).toBe(persistErr); + expect(pgClosed).toBe(1); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + }); + + test('rejects non-read-only Mongo client and static source contains zero write/index/drop tokens', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { readOnly: false }); + let mongoClosed = 0; + + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + + expect((caught as Error).message).toContain('read-exchanges'); + expect((caught as Error).message).toContain('read-only'); + expect(mongoClosed).toBe(1); + + const sourceText = readFileSync(cliSourcePath, 'utf8'); + const forbiddenPattern = /\b(insert|update|delete|drop|createIndex|bulkWrite)\b/i; + expect(forbiddenPattern.test(sourceText)).toBe(false); + expect(/(insert|update|delete|drop|createIndex|bulkWrite)/i.test(sourceText)).toBe(false); + }); + + test('empty sources succeed, write all four files with zero stats, and skip bar-span aggregates', async () => { + const emptyFixture: FakeMongoFixture = { collections: {} }; + const fakeMongo = createStrictReadOnlyFakeMongo(emptyFixture); + const outDir = createTempDir(); + let mongoClosed = 0; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(fakeMongo.aggregateCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + expect(result.composed.stageA.instruments).toHaveLength(0); + expect(result.composed.stageB.listings).toHaveLength(0); + expect(result.composed.report.conflicts).toHaveLength(0); + + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + const content = readFileSync(join(outDir, filename), 'utf8'); + expect(typeof content).toBe('string'); + } + + const parsedStats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { + barSpans: { totalRowsRead: number; totalSpans: number }; + reportSummary: { instruments: number; listings: number; conflicts: number }; + }; + expect(parsedStats.barSpans.totalRowsRead).toBe(0); + expect(parsedStats.barSpans.totalSpans).toBe(0); + expect(parsedStats.reportSummary.instruments).toBe(0); + expect(parsedStats.reportSummary.listings).toBe(0); + expect(parsedStats.reportSummary.conflicts).toBe(0); + }); +});