diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 9a7e4038..ba7783c5 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -313,12 +313,12 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto --te-symbol USDCAD ``` 3. **Run `tools/curate-etl` commands (`curate-bars-1d` first, then the remaining datasets):** - - `curate-etl curate-bars-1d` (`eodPrices.bson`, `qmSplits.bson`, optional `qmPrices.bson`, `--curate-inputs ./tmp/curate-inputs`) - - `curate-etl curate-adj-factors` (`qmSplits.bson`, `qmDividends.bson`, `bars_1d`, `--curate-inputs ./tmp/curate-inputs`) - - `curate-etl curate-corporate-actions` (`qmSplits.bson`, `qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`) - - `curate-etl curate-fx-1d` (`./tmp/raw-bson-fx/eodPrices.bson`, `./tmp/raw-bson-fx/teMarketData.bson`) - - `curate-etl curate-shorts` (`ceoShorts.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`) - - `curate-etl curate-events` (`qmFilings.bson`, `qmEarnings.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`) + - `curate-etl curate-bars-1d` (`--eod-prices ./tmp/raw-bson/eodPrices.bson`, `--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated` — writes `./tmp/curated/bars_1d/year=YYYY/part.parquet`) + - `curate-etl curate-adj-factors` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--bars-1d ./tmp/curated/bars_1d`, `--out ./tmp/curated`) + - `curate-etl curate-corporate-actions` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated`) + - `curate-etl curate-fx-1d` (`--eod-prices ./tmp/raw-bson-fx/eodPrices.bson`, `--te-market-data ./tmp/raw-bson-fx/teMarketData.bson`, `--out ./tmp/curated`) + - `curate-etl curate-shorts` (`--ceo-shorts ./tmp/raw-bson/ceoShorts.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--shares-short-field `) + - `curate-etl curate-events` (`--qm-filings ./tmp/raw-bson/qmFilings.bson`, `--qm-earnings ./tmp/raw-bson/qmEarnings.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--filings-form-type-field `) - **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 1,000,000-doc streaming benchmark with: diff --git a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts index 1ebd0791..8ba7e632 100644 --- a/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts +++ b/apps/stock/data-pipeline/src/security-master/export-raw-bson.ts @@ -205,32 +205,27 @@ export function createReadOnlyMongoRawBsonSource( return { async *[Symbol.asyncIterator]() { - let primaryError: unknown = undefined; let hasPrimaryError = false; try { for await (const doc of cursor) { yield doc; } } catch (error) { - primaryError = error; hasPrimaryError = true; throw error; } finally { if (typeof cursor.close === 'function') { - try { - await cursor.close(); - } catch (closeError) { - if (!hasPrimaryError) { - // Only surface close errors if iteration itself succeeded. - primaryError = closeError; - hasPrimaryError = true; + if (hasPrimaryError) { + try { + await cursor.close(); + } catch { + // Preserve primary iteration error when close also fails. } + } else { + await cursor.close(); } } } - if (hasPrimaryError) { - throw primaryError; - } }, }; }, diff --git a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts index 84df40ba..17ba87cf 100644 --- a/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts +++ b/apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts @@ -149,14 +149,18 @@ function readFlagValue( if (value.length === 0) { throw usageError(`Missing value for ${flag}`); } + if (value.startsWith('--')) { + throw usageError(`Invalid value for ${flag}: "${value}" must not start with "--"`); + } return { value, nextIndex: index }; } const next = argv[index + 1]; - if (!next || next.trim().length === 0 || next.startsWith('--')) { + const trimmedNext = next?.trim() ?? ''; + if (trimmedNext.length === 0 || trimmedNext.startsWith('--')) { throw usageError(`Missing value for ${flag}`); } - return { value: next.trim(), nextIndex: index + 1 }; + return { value: trimmedNext, nextIndex: index + 1 }; } export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRawBsonArgs { @@ -180,6 +184,7 @@ export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRaw for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === '--help') { + markSeen('--help'); help = true; continue; } diff --git a/apps/stock/data-pipeline/test/export-raw-bson.test.ts b/apps/stock/data-pipeline/test/export-raw-bson.test.ts index 75661fd0..e1fc3b59 100644 --- a/apps/stock/data-pipeline/test/export-raw-bson.test.ts +++ b/apps/stock/data-pipeline/test/export-raw-bson.test.ts @@ -585,6 +585,69 @@ describe('exportRawBsonCollection', () => { expect(res.docsWritten).toBe(1); expect(closeMock).toHaveBeenCalledTimes(1); }); + + // Limited export with rejecting cursor.close() must surface the close error, + // clean up the temp file, and leave any pre-existing output file byte-identical. + const rejectingCloseClient: ReadOnlyMongoRawBsonClient = { + isReadOnly: () => true, + getCollection: () => ({ + find: () => ({ + close: async () => { + throw new Error('Cursor close rejected after limit break'); + }, + async *[Symbol.asyncIterator]() { + for (const d of docs) { + yield d; + } + }, + }), + }), + }; + const rejectingSource = createReadOnlyMongoRawBsonSource(rejectingCloseClient); + + await withTempDir(async outDir => { + const existingPath = join(outDir, 'qmFilings.bson'); + const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'preserve-on-close-error' })); + await writeFile(existingPath, sentinel); + + await expect( + exportRawBsonCollection(rejectingSource, { + collection: 'qmFilings', + outDir, + limit: 1, + }) + ).rejects.toThrow('Cursor close rejected after limit break'); + + expect(await readdir(outDir)).toEqual(['qmFilings.bson']); + expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); + }); + + // When iteration itself fails AND cursor.close() rejects, the primary iteration error wins. + const dualFailureClient: ReadOnlyMongoRawBsonClient = { + isReadOnly: () => true, + getCollection: () => ({ + find: () => ({ + close: async () => { + throw new Error('Secondary cursor close failure'); + }, + async *[Symbol.asyncIterator]() { + yield docs[0]; + throw new Error('Primary cursor iteration failure'); + }, + }), + }), + }; + const dualFailureSource = createReadOnlyMongoRawBsonSource(dualFailureClient); + + await withTempDir(async outDir => { + await expect( + exportRawBsonCollection(dualFailureSource, { + collection: 'qmFilings', + outDir, + }) + ).rejects.toThrow('Primary cursor iteration failure'); + expect(await readdir(outDir)).toEqual([]); + }); }); test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { diff --git a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts index 289b8087..a0c6ab21 100644 --- a/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts +++ b/apps/stock/data-pipeline/test/run-export-raw-bson.test.ts @@ -1,5 +1,5 @@ import { describe, expect, mock, test } from 'bun:test'; -import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { StockAppConfig } from '@stock-bot/stock-config'; @@ -133,6 +133,19 @@ describe('parseExportRawBsonArgs', () => { expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices']) ).toThrow(/Duplicate collection/); + expect(() => parseExportRawBsonArgs(['--help', '--help'])).toThrow(/Duplicate flag: --help/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol=--help']) + ).toThrow(/Invalid value for --eod-symbol/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol', '--help']) + ).toThrow(/Missing value for --eod-symbol/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol=--limit']) + ).toThrow(/Invalid value for --te-symbol/); + expect(() => + parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol', '--limit']) + ).toThrow(/Missing value for --te-symbol/); }); test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => { @@ -345,4 +358,42 @@ describe('runExportRawBson & runCli', () => { expect(assertSafetyMock).not.toHaveBeenCalled(); expect(createClientMock).not.toHaveBeenCalled(); }); + + test('runCli rejects flag-shaped --eod-symbol and --te-symbol values before config or MongoDB access and preserves existing output', async () => { + const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-flag-val-')); + try { + const existingEodPath = join(outDir, 'eodPrices.bson'); + const sentinel = Uint8Array.from(BSON.serialize({ eodSearchCode: 'CAD.FOREX', close: 1.44 })); + await writeFile(existingEodPath, sentinel); + + const initConfigMock = mock(() => { + throw new Error('initializeConfig must not be called on malformed filter'); + }); + const createClientMock = mock(() => { + throw new Error('createMongoClient must not be called on malformed filter'); + }); + + const invalidInvocations: string[][] = [ + ['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol=--help'], + ['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol', '--help'], + ['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol=--help'], + ['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol', '--help'], + ]; + + for (const argv of invalidInvocations) { + await expect( + runCli(argv, { + initializeConfig: initConfigMock as never, + createMongoClient: createClientMock, + }) + ).rejects.toThrow(/(?:Invalid|Missing) value for --(?:eod|te)-symbol/); + } + + expect(initConfigMock).not.toHaveBeenCalled(); + expect(createClientMock).not.toHaveBeenCalled(); + expect(Uint8Array.from(await readFile(existingEodPath))).toEqual(sentinel); + } finally { + await rm(outDir, { recursive: true, force: true }); + } + }); });