diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 0d31cee1..a714a1f5 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -64,6 +64,21 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto - **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside inclusive `[1 - 0.02, 1 + 0.02]`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`. - **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload. +## Pass 4a Sample-Close & USD/CAD Reader (`sample-closes.ts`) +`apps/stock/data-pipeline/src/security-master/sample-closes.ts` provides the read-only MongoDB reader (`buildSampleCloseFilter`, `readSampleCloses`) that streams cross-sectional sample closes from `eodPrices`, `qmPrices`, and `CAD.FOREX` into `SampleCloseRecord[]` and `FxRateByDateRecord[]` for `crossCheckPrices`: + +- **Date storage finding & `$in` type:** `eodPrices` (`apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts`) explicitly enforces and persists `date` as an exact `YYYY-MM-DD` string. `qmPrices` (`apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts`) copies the provider's `price.date` field verbatim and derives a BSON `Date` separately in `dateTime`, so exact `YYYY-MM-DD` formatting on `qmPrices.date` is an assumption based on the QuoteMedia payload until verified against live QA MongoDB or a captured provider fixture. Keeping the approved string query, `buildSampleCloseFilter` emits date-first `{ date: { $in: string[] } }` filters (sorted `YYYY-MM-DD` strings, aligning with `BAR_SPAN_COLLECTIONS` in `src/normalization/bar-spans.ts` and `design/DATA-CONTRACTS.md`) so queries use `{ date: 1, eodSearchCode: 1 }` and `{ qmSearchCode: 1, date: 1 }`. On decode, both `Date` instances and string dates are normalized to UTC `YYYY-MM-DD` via `normalizeBarDate`; because any format or BSON-type mismatch on `date` would exclude rows before decode, row counts should be verified on the first live read-only Pass 4 run. +- **Read-only streaming, raw prices, and FX isolation:** Uses `ReadOnlySourceSymbolReader` (rejecting non-read-only readers before any `find` and rejecting buffered array results with `TypeError`), closes cursors in `finally` on success and error, projects only `_id: 0`, id, `date`, and raw `close` (`eodPrices` / `CAD.FOREX`) or raw `unadjustedclose` (`qmPrices` — never `close` or `adjustedclose`), strips `CAD.FOREX` from equity reads so FX never leaks into `closes`, preserves untrimmed non-blank IDs (T-49), chunks large ID sets (`idChunkSize`, default `10,000`), skips empty sources (`findsRun: 0`), and reconciles `docsRead === emitted + skippedTotal` per source. +- **Local synthetic benchmark (zero MongoDB):** Run the headless 500,025-doc streaming benchmark with: + +```bash +bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts +``` + +- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** + - Workload: `500,025` synthetic docs (`25` sample dates × `20,000` IDs split `10,000` `eodPrices` + `10,000` `qmPrices`, plus `25` `CAD.FOREX` FX docs). + - Observed throughput: `2,627,752 docs/s` (`190.3 ms` elapsed, `25.36 MiB` heap delta). + ## Security Master Persistence (`persistSecurityMaster`) `apps/stock/data-pipeline/src/security-master/persist.ts` persists in-memory Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 (`delisting-chains`) results into the `master` track PostgreSQL tables inside a single transaction guarded by `pg_advisory_xact_lock(0x534d5053, hashtext(current_schema()))`: @@ -191,3 +206,27 @@ All four files are deterministic and byte-identical for identical inputs (no wal - `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`). + +## Read-Only Source Field-Shape Probe (`source-field-shapes.ts`) +`apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` and its CLI `probe-source-field-shapes.ts` sample raw MongoDB collections read-only to report exact field names, BSON/JS value types (`string`, `int`, `double`, `bool`, `date`, `null`, `objectId`, `array`, `object`, `other`), one-level nested `parent.child` keys, string pattern classes (`ymd`, `isoDatetime`, `numeric`, `emptyOrWhitespace`, `other`), and bounded sanitized examples (never emitted for `_id` / `_id.*`). + +- **Bounded read-only contract:** Initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`), refuses non-read-only readers before issuing any query, and runs strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` (default `limit = 1,000`, max `10,000`) over allowlisted collections (`ceoShorts`, `qmSplits`, `qmDividends`, `qmFilings`, `qmEarnings`, `qmPrices`, `eodPrices`, `teMarketData`) — no aggregations, no `$sample`, no writes, and no index operations. +- **Host live-run command (read-only QA MongoDB):** + +```bash +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts \ + --out ./tmp/source-field-shapes.md \ + --limit 1000 +``` + +- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 80,000-doc streaming benchmark (`8` collections × `10,000` limit) with: + +```bash +bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts +``` + +- **Recorded baselines (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** + - Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`. + - Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta). + - After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta). diff --git a/apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts b/apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts new file mode 100644 index 00000000..d3513ba7 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts @@ -0,0 +1,358 @@ +/** + * Reproducible headless benchmark for Pass 4b `runSecurityMaster` end-to-end wiring. + * Streams 20,000 EOD<->QM candidate pairs x 25 sample dates (1,000,025 sample-close/FX docs) + * through in-memory async-generator fake readers with zero database or disk writes. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/run-security-master-pass4-benchmark.ts + */ + +import type { + BarSpanAggregateReader, + GroupedBarSpanRow, +} from '../src/normalization/bar-spans'; +import { + FX_USD_CAD_SOURCE_ID, + runSecurityMaster, + type ReadOnlyMongoCollectionClient, +} from '../src/security-master'; + +const PAIR_COUNT = 20_000; +const SAMPLE_DATE_COUNT = 25; +const MISMATCH_EVERY = 200; // 100 ratio_mismatch pairs, 19,900 confirmed pairs +const AS_OF_DATE = '2026-01-15'; +const FIRST_BAR_DATE = '2020-01-02'; +const LAST_BAR_DATE = '2026-01-14'; + +function computeIsinCheckDigit(isinBody11: string): string { + let digits = ''; + for (let i = 0; i < isinBody11.length; i++) { + const code = isinBody11.charCodeAt(i); + if (code >= 65 && code <= 90) { + digits += String(code - 55); + } else { + digits += isinBody11[i] ?? ''; + } + } + let sum = 0; + let doubleDigit = true; + for (let i = digits.length - 1; i >= 0; i--) { + let val = digits.charCodeAt(i) - 48; + if (doubleDigit) { + val *= 2; + if (val > 9) { + val -= 9; + } + } + sum += val; + doubleDigit = !doubleDigit; + } + return String((10 - (sum % 10)) % 10); +} + +function makeSyntheticIsin(index: number): string { + const body = `US${String(100_000_000 + index).padStart(9, '0')}`; + return `${body}${computeIsinCheckDigit(body)}`; +} + +function makePureLetterTicker(index: number): string { + let n = index; + const c3 = String.fromCharCode(65 + (n % 26)); + n = Math.floor(n / 26); + const c2 = String.fromCharCode(65 + (n % 26)); + n = Math.floor(n / 26); + const c1 = String.fromCharCode(65 + (n % 26)); + n = Math.floor(n / 26); + const c0 = String.fromCharCode(65 + (n % 26)); + return `${c0}${c1}${c2}${c3}`; +} + +function deterministicClose(pairIndex: number, dateIndex: number): number { + // Deterministic non-constant trajectory per pair so log-return variance is strictly positive. + const base = 20 + (pairIndex % 180); + const wave = ((pairIndex * 31 + dateIndex * 17) % 37) * 0.45; + const trend = dateIndex * (0.35 + (pairIndex % 7) * 0.05); + return Number((base + wave + trend).toFixed(4)); +} + +function createBenchmarkMongo(pairCount: number): { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly barSpanReader: BarSpanAggregateReader; +} { + const tickers = new Array(pairCount); + const isins = new Array(pairCount); + const eodIndexById = new Map(); + const qmIndexById = new Map(); + + for (let i = 0; i < pairCount; i++) { + const ticker = makePureLetterTicker(i); + tickers[i] = ticker; + isins[i] = makeSyntheticIsin(i); + eodIndexById.set(`${ticker}.US`, i); + qmIndexById.set(`${ticker}:US`, i); + } + + const eodExchanges = [ + { Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' }, + ]; + const ibExchanges = [{ exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' }]; + const qmExchanges = [{ exchange: 'NSD', country: 'US', currency: 'USD' }]; + + const mongoCollectionClient: ReadOnlyMongoCollectionClient = { + isReadOnly(): boolean { + return true; + }, + getCollection(collectionName: string) { + return { + find = Record>( + filter: Record = {} + ) { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + if (collectionName === 'eodExchanges') { + for (const doc of eodExchanges) { + yield doc as unknown as T; + } + return; + } + if (collectionName === 'ibExchanges') { + for (const doc of ibExchanges) { + yield doc as unknown as T; + } + return; + } + if (collectionName === 'qmExchanges') { + for (const doc of qmExchanges) { + yield doc as unknown as T; + } + return; + } + if ( + collectionName === 'ceoExchanges' || + collectionName === 'ibSymbols' || + collectionName === 'ceoSymbols' || + collectionName === 'eodSymbolChange' + ) { + return; + } + if (collectionName === 'eodSymbols') { + for (let i = 0; i < pairCount; i++) { + const ticker = tickers[i]; + const isin = isins[i]; + if (ticker === undefined || isin === undefined) { + continue; + } + yield { + eodSearchCode: `${ticker}.US`, + Code: ticker, + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: isin, + Name: `Bench Corp ${ticker}`, + Type: 'Common Stock', + delisted: false, + } as unknown as T; + } + return; + } + if (collectionName === 'qmSymbols') { + for (let i = 0; i < pairCount; i++) { + const ticker = tickers[i]; + if (ticker === undefined) { + continue; + } + yield { + qmSearchCode: `${ticker}:US`, + symbol: ticker, + exchange: 'NSD', + countryCode: 'US', + currency: 'USD', + name: `Bench Corp ${ticker}`, + active: true, + } as unknown as T; + } + return; + } + + const dates = ((filter.date as { $in?: string[] } | undefined)?.$in ?? []) as string[]; + if (collectionName === 'eodPrices') { + const ids = + ((filter.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[]; + if (ids.length === 1 && ids[0] === FX_USD_CAD_SOURCE_ID) { + for (let d = 0; d < dates.length; d++) { + yield { + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date: dates[d], + close: Number((1.34 + (d % 7) * 0.005).toFixed(4)), + } as unknown as T; + } + return; + } + for (let d = 0; d < dates.length; d++) { + const date = dates[d]; + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + if (id === undefined) { + continue; + } + const idx = eodIndexById.get(id); + if (idx === undefined) { + continue; + } + yield { + eodSearchCode: id, + date, + close: deterministicClose(idx, d), + } as unknown as T; + } + } + return; + } + + if (collectionName === 'qmPrices') { + const ids = + ((filter.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []) as string[]; + for (let d = 0; d < dates.length; d++) { + const date = dates[d]; + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + if (id === undefined) { + continue; + } + const idx = qmIndexById.get(id); + if (idx === undefined) { + continue; + } + const baseClose = deterministicClose(idx, d); + const mult = idx % MISMATCH_EVERY === 0 ? 2 : 1; + yield { + qmSearchCode: id, + date, + unadjustedclose: Number((baseClose * mult).toFixed(4)), + } as unknown as T; + } + } + } + }, + async close(): Promise { + // No-op for in-memory benchmark cursor. + }, + }; + }, + }; + }, + }; + + const barSpanReader: BarSpanAggregateReader = { + aggregate = Record>( + collectionName: string, + pipeline: Record[] + ): AsyncIterable { + let requestedIds: string[] = []; + for (const stage of pipeline) { + const match = stage.$match as Record | undefined; + if (match && typeof match === 'object') { + for (const value of Object.values(match)) { + if ( + value && + typeof value === 'object' && + Array.isArray((value as { $in?: unknown }).$in) + ) { + requestedIds = (value as { $in: string[] }).$in; + } + } + } + } + const isEod = collectionName === 'eodPrices'; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < requestedIds.length; i++) { + const id = requestedIds[i]; + if (id === undefined) { + continue; + } + const exists = isEod ? eodIndexById.has(id) : qmIndexById.has(id); + if (!exists) { + continue; + } + const row: GroupedBarSpanRow = { + _id: id, + firstBarDate: FIRST_BAR_DATE, + lastBarDate: LAST_BAR_DATE, + barCount: 1510, + }; + yield row as unknown as T; + } + }, + }; + }, + }; + + return { mongoCollectionClient, barSpanReader }; +} + +async function main(): Promise { + const { mongoCollectionClient, barSpanReader } = createBenchmarkMongo(PAIR_COUNT); + + if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { + Bun.gc(true); + } + const heapBefore = process.memoryUsage().heapUsed; + const startedAt = performance.now(); + + const result = await runSecurityMaster( + { + mongoCollectionClient, + barSpanReader, + writeFile: () => {}, + writeStdout: () => {}, + }, + { + asOfDate: AS_OF_DATE, + outDir: '/virtual/benchmark-out', + batchSize: 5_000, + pass4: { enabled: true, sampleDateCount: SAMPLE_DATE_COUNT }, + } + ); + + const elapsedMs = performance.now() - startedAt; + const heapAfter = process.memoryUsage().heapUsed; + const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); + + if (result.composed.pass4 === null || result.sampleCloses === null) { + throw new Error('Benchmark failed: Pass 4 did not execute'); + } + + const expectedMismatches = Math.ceil(PAIR_COUNT / MISMATCH_EVERY); + const expectedConfirmed = PAIR_COUNT - expectedMismatches; + const { pairsIn, byVerdict } = result.composed.pass4.stats; + if ( + pairsIn !== PAIR_COUNT || + byVerdict.confirmed !== expectedConfirmed || + byVerdict.ratio_mismatch !== expectedMismatches + ) { + throw new Error( + `Benchmark verdict mismatch: pairsIn=${pairsIn}, confirmed=${byVerdict.confirmed} (expected ${expectedConfirmed}), ratio_mismatch=${byVerdict.ratio_mismatch} (expected ${expectedMismatches})` + ); + } + + const totalDocsRead = + result.sampleCloses.stats.eod.docsRead + + result.sampleCloses.stats.qm.docsRead + + result.sampleCloses.stats.fx.docsRead; + const pairsPerSec = Math.round(PAIR_COUNT / (elapsedMs / 1000)); + const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000)); + + const lines = [ + 'Pass 4b runSecurityMaster benchmark (in-memory async cursor, zero DB, zero disk)', + ` Workload: ${PAIR_COUNT.toLocaleString('en-US')} EOD<->QM pairs x ${SAMPLE_DATE_COUNT} dates (${totalDocsRead.toLocaleString('en-US')} sample-close/FX docs)`, + ` Verdicts: confirmed=${byVerdict.confirmed.toLocaleString('en-US')}, ratio_mismatch=${byVerdict.ratio_mismatch.toLocaleString('en-US')}, low_correlation=${byVerdict.low_correlation}, insufficient_data=${byVerdict.insufficient_data}`, + ` Elapsed: ${elapsedMs.toFixed(1)} ms`, + ` Throughput: ${pairsPerSec.toLocaleString('en-US')} pairs/s | ${docsPerSec.toLocaleString('en-US')} docs/s`, + ` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`, + ]; + process.stdout.write(`${lines.join('\n')}\n`); +} + +await main(); diff --git a/apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts b/apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts new file mode 100644 index 00000000..b2428c16 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts @@ -0,0 +1,187 @@ +/** + * Reproducible headless benchmark for Pass 4a `readSampleCloses`. + * Streams 500,025 synthetic documents (25 sample dates × 20,000 IDs split across + * eodPrices + qmPrices, plus 25 CAD.FOREX FX documents) through an in-memory + * async-generator fake reader with zero MongoDB or network dependencies. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts + */ + +import { + FX_USD_CAD_SOURCE_ID, + readSampleCloses, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SampleCloseSourceReadStats, +} from '../src/security-master/sample-closes'; + +const SAMPLE_DATE_COUNT = 25; +const EOD_ID_COUNT = 10_000; +const QM_ID_COUNT = 10_000; + +function buildSampleDates(count: number): string[] { + const dates: string[] = []; + let year = 2024; + let month = 1; + let day = 2; + while (dates.length < count) { + dates.push( + `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}` + ); + day += 14; + if (day > 28) { + day -= 28; + month += 1; + if (month > 12) { + month = 1; + year += 1; + } + } + } + return dates; +} + +function buildIds(prefix: string, suffix: string, count: number): string[] { + const ids = new Array(count); + for (let i = 0; i < count; i++) { + ids[i] = `${prefix}${String(i).padStart(5, '0')}${suffix}`; + } + return ids; +} + +function assertStatsReconcile(label: string, stats: SampleCloseSourceReadStats): void { + const skipSum = + stats.skipped.missingId + + stats.skipped.unrequestedId + + stats.skipped.invalidDate + + stats.skipped.unrequestedDate + + stats.skipped.invalidClose; + if (stats.skippedTotal !== skipSum || stats.docsRead !== stats.emitted + stats.skippedTotal) { + throw new Error( + `Stats reconciliation failed for ${label}: docsRead=${stats.docsRead}, emitted=${stats.emitted}, skippedTotal=${stats.skippedTotal}, skipSum=${skipSum}` + ); + } +} + +function createStreamingBenchmarkReader( + sampleDates: readonly string[], + eodIds: readonly string[], + qmIds: readonly string[] +): ReadOnlySourceSymbolReader { + return { + isReadOnly(): boolean { + return true; + }, + find = Record>( + collectionName: string, + filter?: Record + ): ReadOnlySourceSymbolCursor { + const idFilter = + collectionName === 'eodPrices' + ? ((filter?.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) + : ((filter?.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []); + + const isFxCall = + collectionName === 'eodPrices' && + idFilter.length === 1 && + idFilter[0] === FX_USD_CAD_SOURCE_ID; + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + if (isFxCall) { + for (let d = 0; d < sampleDates.length; d++) { + yield { + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date: sampleDates[d], + close: 1.34 + (d % 7) * 0.005, + } as unknown as T; + } + return; + } + + if (collectionName === 'eodPrices') { + const ids = idFilter.length > 0 ? idFilter : eodIds; + for (let d = 0; d < sampleDates.length; d++) { + const date = sampleDates[d]; + for (let i = 0; i < ids.length; i++) { + yield { + eodSearchCode: ids[i], + date, + close: 10 + ((i + d) % 250) + 0.25, + } as unknown as T; + } + } + return; + } + + if (collectionName === 'qmPrices') { + const ids = idFilter.length > 0 ? idFilter : qmIds; + for (let d = 0; d < sampleDates.length; d++) { + const date = sampleDates[d]; + for (let i = 0; i < ids.length; i++) { + yield { + qmSearchCode: ids[i], + date, + unadjustedclose: 10 + ((i + d) % 250) + 0.25, + } as unknown as T; + } + } + } + }, + async close(): Promise { + // No-op for in-memory benchmark cursor. + }, + }; + }, + }; +} + +async function main(): Promise { + const sampleDates = buildSampleDates(SAMPLE_DATE_COUNT); + const eodIds = buildIds('EOD', '.US', EOD_ID_COUNT); + const qmIds = buildIds('QM', '', QM_ID_COUNT); + const reader = createStreamingBenchmarkReader(sampleDates, eodIds, qmIds); + + if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { + Bun.gc(true); + } + const heapBefore = process.memoryUsage().heapUsed; + const startedAt = performance.now(); + + const result = await readSampleCloses(reader, { + sampleDates, + sourceIdsBySource: { eod: eodIds, qm: qmIds }, + batchSize: 5_000, + }); + + const elapsedMs = performance.now() - startedAt; + const heapAfter = process.memoryUsage().heapUsed; + const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); + + assertStatsReconcile('eod', result.stats.eod); + assertStatsReconcile('qm', result.stats.qm); + assertStatsReconcile('fx', result.stats.fx); + + const totalDocsRead = + result.stats.eod.docsRead + result.stats.qm.docsRead + result.stats.fx.docsRead; + const expectedEquityDocs = SAMPLE_DATE_COUNT * (EOD_ID_COUNT + QM_ID_COUNT); + if (result.closes.length !== expectedEquityDocs || result.fxRates.length !== SAMPLE_DATE_COUNT) { + throw new Error( + `Unexpected emitted counts: closes=${result.closes.length} (expected ${expectedEquityDocs}), fxRates=${result.fxRates.length} (expected ${SAMPLE_DATE_COUNT})` + ); + } + + const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000)); + const lines = [ + 'Pass 4a sample-closes benchmark (in-memory async cursor, zero MongoDB)', + ` Workload: ${totalDocsRead.toLocaleString('en-US')} docs (${SAMPLE_DATE_COUNT} dates x ${(EOD_ID_COUNT + QM_ID_COUNT).toLocaleString('en-US')} ids + ${SAMPLE_DATE_COUNT} FX)`, + ` Emitted: ${result.closes.length.toLocaleString('en-US')} closes, ${result.fxRates.length.toLocaleString('en-US')} fxRates`, + ` Elapsed: ${elapsedMs.toFixed(1)} ms`, + ` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`, + ` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`, + ]; + process.stdout.write(`${lines.join('\n')}\n`); +} + +await main(); diff --git a/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts b/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts new file mode 100644 index 00000000..ddb6ba75 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts @@ -0,0 +1,167 @@ +/** + * Reproducible headless benchmark for `readFieldShapes` + `renderFieldShapesMarkdown`. + * Streams 80,000 fixed-seed synthetic documents (8 allowlisted collections × 10,000 limit) + * with mixed BSON/JS types, one-level nested objects, and all 5 string pattern classes + * through an in-memory async-generator fake reader with zero MongoDB or network dependencies. + * + * Usage: + * bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts + */ + +import { + FIELD_SHAPE_PROBE_COLLECTIONS, + FIELD_VALUE_TYPES, + MAX_FIELD_SHAPE_LIMIT, + readFieldShapes, + renderFieldShapesMarkdown, + STRING_PATTERN_CLASSES, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +const DOCS_PER_COLLECTION = MAX_FIELD_SHAPE_LIMIT; + +function mulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function makeSyntheticDoc(collectionIndex: number, docIndex: number, rng: () => number): Record { + const r = rng(); + const day = String((docIndex % 28) + 1).padStart(2, '0'); + const month = String(((docIndex + collectionIndex) % 12) + 1).padStart(2, '0'); + const dateStr = `2025-${month}-${day}`; + const isoStr = `${dateStr}T14:30:00Z`; + + const doc: Record = { + _id: { + _bsontype: 'ObjectId', + toString: () => + `${String(collectionIndex).padStart(2, '0')}${String(docIndex).padStart(22, '0')}`, + }, + symbol: `SYM${String(docIndex % 2000).padStart(4, '0')}`, + date: r < 0.85 ? dateStr : r < 0.95 ? isoStr : '', + value: + r < 0.5 + ? { _bsontype: 'Double', toString: () => (10 + (docIndex % 500) * 0.25).toFixed(2) } + : r < 0.8 + ? { _bsontype: 'Int32', toString: () => String(docIndex % 10000) } + : r < 0.92 + ? String((docIndex % 1000) / 10) + : null, + active: docIndex % 5 !== 0, + updatedAt: new Date(1735689600000 + (docIndex % 365) * 86_400_000), + meta: { + exchange: docIndex % 2 === 0 ? 'NYSE' : 'TSX', + version: { _bsontype: 'Int32', toString: () => '2' }, + }, + }; + + if (docIndex % 7 === 0) { + doc.tags = ['equity', 'na']; + } + return doc; +} + +function createSyntheticBenchmarkReader(): ReadOnlySourceSymbolReader { + return { + isReadOnly(): boolean { + return true; + }, + find = Record>( + collectionName: string, + _filter?: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + const colIdx = FIELD_SHAPE_PROBE_COLLECTIONS.indexOf( + collectionName as (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number] + ); + const count = Math.min(DOCS_PER_COLLECTION, options?.limit ?? DOCS_PER_COLLECTION); + const rng = mulberry32(0x5eed108 + (colIdx + 1) * 7919); + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < count; i++) { + yield makeSyntheticDoc(colIdx, i, rng) as T; + } + }, + async close(): Promise { + // No-op for in-memory benchmark cursor. + }, + }; + }, + }; +} + +async function main(): Promise { + const reader = createSyntheticBenchmarkReader(); + + if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { + Bun.gc(true); + } + const heapBefore = process.memoryUsage().heapUsed; + const startedAt = performance.now(); + + const result = await readFieldShapes(reader, { + limit: DOCS_PER_COLLECTION, + batchSize: 2_000, + }); + const markdown = renderFieldShapesMarkdown(result); + + const elapsedMs = performance.now() - startedAt; + const heapAfter = process.memoryUsage().heapUsed; + const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); + + const expectedTotal = FIELD_SHAPE_PROBE_COLLECTIONS.length * DOCS_PER_COLLECTION; + if (result.totalDocsSampled !== expectedTotal) { + throw new Error( + `Unexpected totalDocsSampled=${result.totalDocsSampled} (expected ${expectedTotal})` + ); + } + + for (const col of result.collections) { + for (const field of col.fields) { + if (field.presentCount + field.missingCount !== col.docCount) { + throw new Error(`Presence mismatch on ${col.collection}.${field.field}`); + } + let typeSum = 0; + for (const typeName of FIELD_VALUE_TYPES) { + typeSum += field.typeCounts[typeName]; + } + if (typeSum !== field.presentCount) { + throw new Error(`Type sum mismatch on ${col.collection}.${field.field}`); + } + if (field.stringStats !== null) { + let patternSum = 0; + for (const p of STRING_PATTERN_CLASSES) { + patternSum += field.stringStats.patterns[p]; + } + if (patternSum !== field.typeCounts.string) { + throw new Error(`Pattern sum mismatch on ${col.collection}.${field.field}`); + } + } + if ((field.field === '_id' || field.field.startsWith('_id.')) && field.examples.length > 0) { + throw new Error(`_id example leaked on ${col.collection}.${field.field}`); + } + } + } + + const docsPerSec = Math.round(result.totalDocsSampled / (elapsedMs / 1000)); + const lines = [ + 'Source field-shapes probe benchmark (in-memory async cursor, zero MongoDB)', + ` Workload: ${result.totalDocsSampled.toLocaleString('en-US')} docs (${FIELD_SHAPE_PROBE_COLLECTIONS.length} collections x ${DOCS_PER_COLLECTION.toLocaleString('en-US')} limit)`, + ` Markdown: ${markdown.length.toLocaleString('en-US')} chars`, + ` Elapsed: ${elapsedMs.toFixed(1)} ms`, + ` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`, + ` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`, + ]; + process.stdout.write(`${lines.join('\n')}\n`); +} + +await main(); diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 7fd47256..7cefbc51 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -217,18 +217,40 @@ export { export { assertSecurityMasterPersistSafety, + buildSampleDateCalendar, formatRunSecurityMasterSummary, parseRunSecurityMasterArgs, RUN_SECURITY_MASTER_USAGE, runSecurityMaster, SECURITY_MASTER_OUTPUT_FILES, type ParsedRunSecurityMasterArgs, + type Pass4SkippedReason, type RunSecurityMasterDeps, type RunSecurityMasterOptions, type RunSecurityMasterOutput, + type RunSecurityMasterPass4Options, + type RunSecurityMasterPass4Summary, type SecurityMasterPostgresHandle, } from './run-security-master'; +export { + buildSampleCloseFilter, + DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE, + EOD_SAMPLE_CLOSES_PROJECTION, + FX_USD_CAD_SOURCE_ID, + MAX_SAMPLE_DATES, + QM_SAMPLE_CLOSES_PROJECTION, + readSampleCloses, + type ReadSampleClosesOptions, + type ReadSampleClosesResult, + type ReadSampleClosesStats, + type SampleCloseSkipCounts, + type SampleCloseSkipReason, + type SampleCloseSource, + type SampleCloseSourceIdsBySource, + type SampleCloseSourceReadStats, +} from './sample-closes'; + export { buildSecurityTypeByIsin, buildSecurityTypeByIsinForStageA, @@ -243,6 +265,47 @@ export { type UnknownSecurityTypeCount, } from './security-type'; +export { + parseProbeSourceFieldShapesArgs, + PROBE_SOURCE_FIELD_SHAPES_USAGE, + runCli as runProbeSourceFieldShapesCli, + runSourceFieldShapesProbe, + type ParsedProbeSourceFieldShapesArgs, + type RunSourceFieldShapesProbeDeps, + type RunSourceFieldShapesProbeOptions, + type RunSourceFieldShapesProbeOutput, +} from './probe-source-field-shapes'; + +export { + DEFAULT_FIELD_SHAPE_LIMIT, + DEFAULT_MAX_EXAMPLE_LENGTH, + DEFAULT_MAX_EXAMPLES, + FIELD_SHAPE_PROBE_COLLECTIONS, + FIELD_VALUE_TYPES, + isFieldShapeProbeCollection, + MAX_EXAMPLE_LENGTH_CAP, + MAX_EXAMPLES_CAP, + MAX_FIELD_SHAPE_LIMIT, + normalizeProbeCollections, + readFieldShapes, + renderFieldShapesMarkdown, + STRING_PATTERN_CLASSES, + summarizeFieldShapes, + UnknownProbeCollectionError, + type CollectionFieldShapesProbeResult, + type CollectionFieldShapesSummary, + type FieldShapeProbeCollection, + type FieldShapeSummary, + type FieldStringStats, + type FieldValueType, + type FieldValueTypeCounts, + type ReadFieldShapesOptions, + type ReadFieldShapesResult, + type StringPatternClass, + type StringPatternCounts, + type SummarizeFieldShapesOptions, +} from './source-field-shapes'; + export { adaptCeoSymbolDoc, adaptEodSymbolChangeDoc, diff --git a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts new file mode 100644 index 00000000..b3fbcfca --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts @@ -0,0 +1,291 @@ +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 { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; +import { + DEFAULT_FIELD_SHAPE_LIMIT, + FIELD_SHAPE_PROBE_COLLECTIONS, + MAX_FIELD_SHAPE_LIMIT, + normalizeProbeCollections, + readFieldShapes, + renderFieldShapesMarkdown, + type FieldShapeProbeCollection, + type ReadFieldShapesResult, +} from './source-field-shapes'; +import { + createReadOnlyMongoSourceSymbolReader, + type ReadOnlyMongoCollectionClient, +} from './source-symbol-readers'; + +export const PROBE_SOURCE_FIELD_SHAPES_USAGE = [ + 'Usage: bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --out [--limit ] [--collections ] [--help]', + '', + 'Options:', + ' --out Required. Output Markdown report file path.', + ` --limit Optional. Max documents sampled per collection (1..${MAX_FIELD_SHAPE_LIMIT}, default: ${DEFAULT_FIELD_SHAPE_LIMIT}).`, + ` --collections Optional. Comma-separated allowlisted collections (default: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(',')}).`, + ' --help Show this help message and exit.', +].join('\n'); + +export type ParsedProbeSourceFieldShapesArgs = + | { readonly help: true } + | { + readonly help: false; + readonly outPath: string; + readonly limit: number; + readonly collections: readonly FieldShapeProbeCollection[]; + }; + +export interface RunSourceFieldShapesProbeDeps { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly closeMongo?: () => Promise | void; + readonly writeFile?: (filePath: string, content: string) => Promise | void; + readonly writeStdout?: (text: string) => void; +} + +export interface RunSourceFieldShapesProbeOptions { + readonly outPath: string; + readonly limit?: number; + readonly collections?: readonly string[]; + readonly maxExamples?: number; + readonly maxExampleLength?: number; + readonly batchSize?: number; +} + +export interface RunSourceFieldShapesProbeOutput { + readonly outPath: string; + readonly result: ReadFieldShapesResult; + readonly markdown: string; + readonly summary: string; +} + +const STRICT_INT_PATTERN = /^-?\d+$/; + +function usageError(message: string): Error { + return new Error(`${message}\n\n${PROBE_SOURCE_FIELD_SHAPES_USAGE}`); +} + +function parseLimitArg(raw: string): number { + if (!STRICT_INT_PATTERN.test(raw)) { + throw usageError( + `Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}` + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_FIELD_SHAPE_LIMIT) { + throw usageError( + `Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}` + ); + } + return parsed; +} + +function parseCollectionsArg(raw: string): FieldShapeProbeCollection[] { + const parts = raw + .split(',') + .map(part => part.trim()) + .filter(part => part.length > 0); + if (parts.length === 0) { + throw usageError('Missing value for --collections'); + } + return normalizeProbeCollections(parts); +} + +export function parseProbeSourceFieldShapesArgs( + argv: readonly string[] +): ParsedProbeSourceFieldShapesArgs { + let help = false; + let outPath: string | undefined; + let limit = DEFAULT_FIELD_SHAPE_LIMIT; + let collectionsRaw: string[] | undefined; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help') { + help = true; + continue; + } + if (arg === '--out') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --out'); + } + outPath = value.trim(); + i += 1; + continue; + } + if (arg?.startsWith('--out=')) { + const value = arg.slice('--out='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --out'); + } + outPath = value; + continue; + } + if (arg === '--limit') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --limit'); + } + limit = parseLimitArg(value.trim()); + i += 1; + continue; + } + if (arg?.startsWith('--limit=')) { + const value = arg.slice('--limit='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --limit'); + } + limit = parseLimitArg(value); + continue; + } + if (arg === '--collections') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --collections'); + } + const parsed = parseCollectionsArg(value); + collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed; + i += 1; + continue; + } + if (arg?.startsWith('--collections=')) { + const value = arg.slice('--collections='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --collections'); + } + const parsed = parseCollectionsArg(value); + collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed; + continue; + } + throw usageError(`Unknown argument: ${String(arg)}`); + } + + if (help) { + return { help: true }; + } + + if (outPath === undefined || outPath.trim().length === 0) { + throw usageError('Missing required argument: --out '); + } + + const collections = normalizeProbeCollections(collectionsRaw); + return { + help: false, + outPath, + limit, + collections, + }; +} + +async function defaultWriteFile(filePath: string, content: string): Promise { + await mkdir(dirname(filePath), { recursive: true }); + await writeFile(filePath, content, 'utf8'); +} + +export async function runSourceFieldShapesProbe( + deps: RunSourceFieldShapesProbeDeps, + options: RunSourceFieldShapesProbeOptions +): Promise { + let primaryError: unknown = undefined; + let hasPrimaryError = false; + let output: RunSourceFieldShapesProbeOutput | undefined; + + try { + if (typeof options.outPath !== 'string' || options.outPath.trim().length === 0) { + throw new Error('outPath must be a non-empty string'); + } + + const reader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient); + const result = await readFieldShapes(reader, { + limit: options.limit, + collections: options.collections, + maxExamples: options.maxExamples, + maxExampleLength: options.maxExampleLength, + batchSize: options.batchSize, + }); + + const markdown = renderFieldShapesMarkdown(result); + const writer = deps.writeFile ?? defaultWriteFile; + await writer(options.outPath, markdown); + + const summary = [ + `Source field-shape probe complete (limit=${result.limit})`, + ` Collections: ${result.collections.length} | Documents sampled: ${result.totalDocsSampled}`, + ` Report written: ${options.outPath}`, + ].join('\n'); + + output = { + outPath: options.outPath, + result, + markdown, + summary: `${summary}\n`, + }; + } catch (error) { + primaryError = error; + hasPrimaryError = true; + } finally { + if (deps.closeMongo) { + try { + await deps.closeMongo(); + } catch (closeError) { + if (!hasPrimaryError) { + primaryError = closeError; + hasPrimaryError = true; + } + } + } + } + + if (hasPrimaryError) { + throw primaryError; + } + if (output === undefined) { + throw new Error('Source field-shape probe completed without producing output'); + } + + const writeStdout = + deps.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(output.summary); + + return output; +} + +export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { + const parsed = parseProbeSourceFieldShapesArgs(argv); + if (parsed.help) { + process.stdout.write(`${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); + + await mongo.connect(); + await runSourceFieldShapesProbe( + { + mongoCollectionClient: mongo, + closeMongo: () => mongo.disconnect(), + }, + { + outPath: parsed.outPath, + limit: parsed.limit, + collections: parsed.collections, + } + ); +} + +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/apps/stock/data-pipeline/src/security-master/run-security-master.ts b/apps/stock/data-pipeline/src/security-master/run-security-master.ts index d8090a05..ce107fa7 100644 --- a/apps/stock/data-pipeline/src/security-master/run-security-master.ts +++ b/apps/stock/data-pipeline/src/security-master/run-security-master.ts @@ -36,7 +36,18 @@ import { type SecurityMasterQueryable, type SecurityMasterQueryResult, } from './persist'; +import { + DEFAULT_SAMPLE_DATE_COUNT, + selectSampleDates, + type PriceCrossCheckVerdictCounts, +} from './price-cross-check'; import { composeSecurityMasterRun, type ComposeSecurityMasterRunResult } from './run'; +import { + MAX_SAMPLE_DATES, + readSampleCloses, + type ReadSampleClosesResult, + type ReadSampleClosesStats, +} from './sample-closes'; import { createExchangeSourceLookup, createReadOnlyMongoSourceSymbolReader, @@ -54,13 +65,15 @@ export const SECURITY_MASTER_OUTPUT_FILES = Object.freeze({ } 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]', + 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of --out-dir [--persist] [--skip-price-cross-check] [--sample-dates ] [--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 isolated dev PostgreSQL after running safety guards (default: off).', - ' --help Show this help message and exit.', + ' --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 isolated dev PostgreSQL after running safety guards (default: off).', + ' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).', + ` --sample-dates Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`, + ' --help Show this help message and exit.', ].join('\n'); export type ParsedRunSecurityMasterArgs = @@ -70,8 +83,27 @@ export type ParsedRunSecurityMasterArgs = readonly asOfDate: string; readonly outDir: string; readonly persist: boolean; + readonly skipPriceCrossCheck: boolean; + readonly sampleDateCount: number; }; +export interface RunSecurityMasterPass4Options { + readonly enabled?: boolean; + readonly sampleDateCount?: number; +} + +export type Pass4SkippedReason = 'disabled' | 'no_sample_dates' | 'no_candidate_pairs'; + +export interface RunSecurityMasterPass4Summary { + readonly sampleDates: readonly string[]; + readonly candidatePairs: number; + readonly eodIdsRequested: number; + readonly qmIdsRequested: number; + readonly stats: ReadSampleClosesStats | null; + readonly byVerdict: PriceCrossCheckVerdictCounts | null; + readonly skippedReason: Pass4SkippedReason | null; +} + export interface SecurityMasterPostgresHandle { readonly queryable: SecurityMasterQueryable; close(): Promise | void; @@ -88,6 +120,8 @@ export interface RunSecurityMasterDeps { | Promise | SecurityMasterPostgresHandle; readonly persistFn?: typeof persistSecurityMaster; + readonly readSampleClosesFn?: typeof readSampleCloses; + readonly composeFn?: typeof composeSecurityMasterRun; readonly writeFile?: (filePath: string, content: string) => Promise | void; readonly writeStdout?: (text: string) => void; } @@ -99,6 +133,7 @@ export interface RunSecurityMasterOptions { readonly countries?: readonly string[] | null; readonly batchSize?: number; readonly barSpans?: Omit; + readonly pass4?: RunSecurityMasterPass4Options; } export interface RunSecurityMasterOutput { @@ -110,6 +145,8 @@ export interface RunSecurityMasterOutput { readonly exchangeCountsByCollection: Readonly>; readonly sources: SecurityMasterSourcesResult; readonly barSpans: ComputeBarSpansResult; + readonly sampleCloses: ReadSampleClosesResult | null; + readonly pass4: RunSecurityMasterPass4Summary; readonly composed: ComposeSecurityMasterRunResult; readonly persistResult: PersistSecurityMasterResult | null; readonly runStatsJson: string; @@ -117,6 +154,166 @@ export interface RunSecurityMasterOutput { } const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const STRICT_INT_PATTERN = /^-?\d+$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function parseYmdComponents(value: string): { year: number; month: number; day: number } | null { + if (!EXACT_YMD_PATTERN.test(value)) { + return null; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + if (year < 1 || year > 9999 || month < 1 || month > 12) { + return null; + } + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + if (day < 1 || day > maxDay) { + return null; + } + return { year, month, day }; +} + +function daysFromCivil(year: number, month: number, day: number): number { + const y = month <= 2 ? year - 1 : year; + const era = Math.floor(y / 400); + const yoe = y - era * 400; + const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1; + const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy; + return era * 146097 + doe - 719468; +} + +function civilFromDays(daysSinceEpoch: number): { year: number; month: number; day: number } { + const shifted = daysSinceEpoch + 719468; + const era = Math.floor(shifted / 146097); + const doe = shifted - era * 146097; + const yoe = Math.floor( + (doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365 + ); + const y = yoe + era * 400; + const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100)); + const mp = Math.floor((5 * doy + 2) / 153); + const day = doy - Math.floor((153 * mp + 2) / 5) + 1; + const month = mp + (mp < 10 ? 3 : -9); + const year = y + (month <= 2 ? 1 : 0); + return { year, month, day }; +} + +function formatUtcYmd(year: number, month: number, day: number): string { + const y = String(year).padStart(4, '0'); + const m = month < 10 ? `0${String(month)}` : String(month); + const d = day < 10 ? `0${String(day)}` : String(day); + return `${y}-${m}-${d}`; +} + +/** + * Builds a deterministic ascending Mon-Fri YYYY-MM-DD calendar over the overlapping + * date window where both EOD and QM have observed bars, clamped to `asOfDate`. + */ +export function buildSampleDateCalendar( + barSpans: Pick, + asOfDate: string +): string[] { + if (!barSpans || !barSpans.index || !isValidAsOfDate(asOfDate)) { + return []; + } + + let minEodFirst: string | null = null; + let maxEodLast: string | null = null; + let minQmFirst: string | null = null; + let maxQmLast: string | null = null; + + for (const span of barSpans.index) { + if ( + !span || + typeof span.barCount !== 'number' || + !Number.isFinite(span.barCount) || + span.barCount <= 0 + ) { + continue; + } + if (span.source !== 'eod' && span.source !== 'qm') { + continue; + } + if ( + parseYmdComponents(span.firstBarDate) === null || + parseYmdComponents(span.lastBarDate) === null || + span.firstBarDate > span.lastBarDate + ) { + continue; + } + if (span.source === 'eod') { + if (minEodFirst === null || span.firstBarDate < minEodFirst) { + minEodFirst = span.firstBarDate; + } + if (maxEodLast === null || span.lastBarDate > maxEodLast) { + maxEodLast = span.lastBarDate; + } + } else { + if (minQmFirst === null || span.firstBarDate < minQmFirst) { + minQmFirst = span.firstBarDate; + } + if (maxQmLast === null || span.lastBarDate > maxQmLast) { + maxQmLast = span.lastBarDate; + } + } + } + + if (minEodFirst === null || maxEodLast === null || minQmFirst === null || maxQmLast === null) { + return []; + } + + const start = minEodFirst > minQmFirst ? minEodFirst : minQmFirst; + const overlapEnd = maxEodLast < maxQmLast ? maxEodLast : maxQmLast; + const end = overlapEnd < asOfDate ? overlapEnd : asOfDate; + + if (start > end) { + return []; + } + + const startParts = parseYmdComponents(start); + const endParts = parseYmdComponents(end); + if (startParts === null || endParts === null) { + return []; + } + + const startDay = daysFromCivil(startParts.year, startParts.month, startParts.day); + const endDay = daysFromCivil(endParts.year, endParts.month, endParts.day); + const calendar: string[] = []; + + for (let dayNum = startDay; dayNum <= endDay; dayNum++) { + const dow = (((dayNum + 4) % 7) + 7) % 7; + if (dow >= 1 && dow <= 5) { + const civil = civilFromDays(dayNum); + calendar.push(formatUtcYmd(civil.year, civil.month, civil.day)); + } + } + + return calendar; +} + +function parseSampleDateCountArg(raw: string): number { + if (!STRICT_INT_PATTERN.test(raw)) { + throw usageError( + `Invalid --sample-dates value "${raw}": expected an integer between 1 and ${MAX_SAMPLE_DATES}` + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_SAMPLE_DATES) { + throw usageError( + `Invalid --sample-dates value "${raw}": expected an integer between 1 and ${MAX_SAMPLE_DATES}` + ); + } + return parsed; +} function isValidAsOfDate(value: string): boolean { return EXACT_YMD_PATTERN.test(value) && normalizeBarDate(value) === value; @@ -152,6 +349,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe let asOfDate: string | undefined; let outDir: string | undefined; let persist = false; + let skipPriceCrossCheck = false; + let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; @@ -163,6 +362,27 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe persist = true; continue; } + if (arg === '--skip-price-cross-check') { + skipPriceCrossCheck = true; + continue; + } + if (arg === '--sample-dates') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --sample-dates'); + } + sampleDateCount = parseSampleDateCountArg(value); + i += 1; + continue; + } + if (arg?.startsWith('--sample-dates=')) { + const value = arg.slice('--sample-dates='.length); + if (value.trim().length === 0) { + throw usageError('Missing value for --sample-dates'); + } + sampleDateCount = parseSampleDateCountArg(value); + continue; + } if (arg === '--as-of') { const value = argv[i + 1]; if (!value || value.trim().length === 0 || value.startsWith('--')) { @@ -221,6 +441,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe asOfDate, outDir, persist, + skipPriceCrossCheck, + sampleDateCount, }; } @@ -262,9 +484,9 @@ export function formatRunSecurityMasterSummary( params: Pick< RunSecurityMasterOutput, 'asOfDate' | 'outDir' | 'persist' | 'filesWritten' | 'composed' - > + > & { readonly pass4?: RunSecurityMasterPass4Summary } ): string { - const { asOfDate, outDir, persist, composed } = params; + const { asOfDate, outDir, persist, composed, pass4 } = params; const resolutionParts = composed.report.resolutionBySource.map(row => { const pct = row.eligibleResolvedPct === null @@ -280,11 +502,25 @@ export function formatRunSecurityMasterSummary( SECURITY_MASTER_OUTPUT_FILES.runStatsJson, ]; + const pass4StatusLabel = + composed.stats.pass4.status === 'skipped' && pass4?.skippedReason + ? `skipped (${pass4.skippedReason})` + : composed.stats.pass4.status; + const pass4DateCount = pass4?.sampleDates.length ?? 0; + const byVerdict = composed.pass4?.stats.byVerdict ?? pass4?.byVerdict ?? null; + const pass4Line = + ` Pass 4 price cross-check: ${pass4StatusLabel} ` + + `(dates=${pass4DateCount}, ` + + `confirmed=${byVerdict?.confirmed ?? 0}, ` + + `ratio_mismatch=${byVerdict?.ratio_mismatch ?? 0}, ` + + `low_correlation=${byVerdict?.low_correlation ?? 0}, ` + + `insufficient_data=${byVerdict?.insufficient_data ?? 0})`; + 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)`, + pass4Line, ` Files written (${outDir}): ${fileNames.join(', ')}`, ` Persisted: ${persist ? 'yes' : 'no (dry-run)'}`, ]; @@ -313,6 +549,37 @@ export async function runSecurityMaster( throw wrapStepError('validate-options', new Error('outDir must be a non-empty string')); } + let pass4Enabled = true; + let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT; + if (options.pass4 !== undefined) { + if (options.pass4 === null || typeof options.pass4 !== 'object') { + throw wrapStepError('validate-options', new Error('pass4 options must be an object')); + } + if (options.pass4.enabled !== undefined) { + if (typeof options.pass4.enabled !== 'boolean') { + throw wrapStepError('validate-options', new Error('pass4.enabled must be a boolean')); + } + pass4Enabled = options.pass4.enabled; + } + if (options.pass4.sampleDateCount !== undefined) { + const count = options.pass4.sampleDateCount; + if ( + typeof count !== 'number' || + !Number.isSafeInteger(count) || + count < 1 || + count > MAX_SAMPLE_DATES + ) { + throw wrapStepError( + 'validate-options', + new Error( + `Invalid pass4.sampleDateCount "${String(count)}": expected a positive safe integer <= ${MAX_SAMPLE_DATES}` + ) + ); + } + sampleDateCount = count; + } + } + // Step 1: Environment safety check before opening PostgreSQL or reading Mongo when --persist is requested. if (persist) { try { @@ -405,10 +672,11 @@ export async function runSecurityMaster( throw wrapStepError('compute-bar-spans', error); } - // Step 5: Compose Stage A -> Stage B -> Pass 6 -> Report + PersistInput (Pass 4 omitted). + // Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs. + const composeFn = deps.composeFn ?? composeSecurityMasterRun; let composed: ComposeSecurityMasterRunResult; try { - composed = composeSecurityMasterRun( + composed = composeFn( { sources, barSpans, @@ -422,10 +690,100 @@ export async function runSecurityMaster( throw wrapStepError('compose', error); } + // Step 5b: Read targeted sample closes + USD/CAD FX and re-compose with Pass 4 when applicable. + let pass4Wired = false; + let sampleCloses: ReadSampleClosesResult | null = null; + let pass4SampleDates: string[] = []; + let pass4EodIds: string[] = []; + let pass4QmIds: string[] = []; + let pass4SkippedReason: Pass4SkippedReason | null = null; + const candidatePairsCount = composed.pass4CandidatePairs.length; + + if (!pass4Enabled) { + pass4SkippedReason = 'disabled'; + } else { + const calendar = buildSampleDateCalendar(barSpans, options.asOfDate); + pass4SampleDates = + calendar.length > 0 ? selectSampleDates(calendar, { count: sampleDateCount }) : []; + + if (pass4SampleDates.length === 0) { + pass4SkippedReason = 'no_sample_dates'; + } else { + const eodRawIds: string[] = []; + const qmRawIds: string[] = []; + for (let i = 0; i < composed.pass4CandidatePairs.length; i++) { + const pair = composed.pass4CandidatePairs[i]; + if (!pair) { + continue; + } + if (pair.left.source === 'eod') { + eodRawIds.push(pair.left.sourceId); + } else if (pair.left.source === 'qm') { + qmRawIds.push(pair.left.sourceId); + } + if (pair.right.source === 'eod') { + eodRawIds.push(pair.right.sourceId); + } else if (pair.right.source === 'qm') { + qmRawIds.push(pair.right.sourceId); + } + } + pass4EodIds = collectSortedUniqueIds(eodRawIds); + pass4QmIds = collectSortedUniqueIds(qmRawIds); + + if (candidatePairsCount === 0 || (pass4EodIds.length === 0 && pass4QmIds.length === 0)) { + pass4SkippedReason = 'no_candidate_pairs'; + } else { + const readSampleClosesFn = deps.readSampleClosesFn ?? readSampleCloses; + try { + sampleCloses = await readSampleClosesFn(sourceReader, { + sampleDates: pass4SampleDates, + sourceIdsBySource: { + eod: pass4EodIds, + qm: pass4QmIds, + }, + includeFx: true, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }); + pass4Wired = true; + } catch (error) { + throw wrapStepError('read-sample-closes', error); + } + + try { + composed = composeFn( + { + sources, + barSpans, + exchanges, + sampleCloses: sampleCloses.closes, + fxRates: sampleCloses.fxRates, + }, + { + asOfDate: options.asOfDate, + } + ); + } catch (error) { + throw wrapStepError('compose', error); + } + } + } + } + + const pass4Summary: RunSecurityMasterPass4Summary = { + sampleDates: pass4SampleDates, + candidatePairs: candidatePairsCount, + eodIdsRequested: pass4EodIds.length, + qmIdsRequested: pass4QmIds.length, + stats: sampleCloses?.stats ?? null, + byVerdict: composed.pass4?.stats.byVerdict ?? null, + skippedReason: pass4SkippedReason, + }; + // Step 6: Write deterministic artifacts into outDir. const statsArtifact = { asOfDate: options.asOfDate, - pass4Wired: false, + pass4Wired, + pass4: pass4Summary, exchanges: { countsByCollection: exchangeCountsByCollection, mapped: exchanges.mapped.length, @@ -516,6 +874,7 @@ export async function runSecurityMaster( persist, filesWritten, composed, + pass4: pass4Summary, }); output = { @@ -527,6 +886,8 @@ export async function runSecurityMaster( exchangeCountsByCollection, sources, barSpans, + sampleCloses, + pass4: pass4Summary, composed, persistResult, runStatsJson, @@ -664,6 +1025,10 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P asOfDate: parsed.asOfDate, outDir: parsed.outDir, persist: parsed.persist, + pass4: { + enabled: !parsed.skipPriceCrossCheck, + sampleDateCount: parsed.sampleDateCount, + }, } ); } diff --git a/apps/stock/data-pipeline/src/security-master/sample-closes.ts b/apps/stock/data-pipeline/src/security-master/sample-closes.ts new file mode 100644 index 00000000..98270938 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/sample-closes.ts @@ -0,0 +1,519 @@ +import { + BAR_SPAN_COLLECTIONS, + normalizeBarDate, + type BarSpanSource, +} from '../normalization/bar-spans'; +import { compareAscii } from './exchange-pass1'; +import type { FxRateByDateRecord, SampleCloseRecord } from './price-cross-check'; +import type { + ReadOnlySourceSymbolCursor, + ReadOnlySourceSymbolReader, + SourceSymbolFindOptions, +} from './source-symbol-readers'; + +export type SampleCloseSource = BarSpanSource; + +export const MAX_SAMPLE_DATES = 64; +export const DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE = 10_000; +export const FX_USD_CAD_SOURCE_ID = 'CAD.FOREX'; + +export const EOD_SAMPLE_CLOSES_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + [BAR_SPAN_COLLECTIONS.eod.idField]: 1, + [BAR_SPAN_COLLECTIONS.eod.dateField]: 1, + close: 1, +}); + +export const QM_SAMPLE_CLOSES_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + [BAR_SPAN_COLLECTIONS.qm.idField]: 1, + [BAR_SPAN_COLLECTIONS.qm.dateField]: 1, + unadjustedclose: 1, +}); + +export interface SampleCloseSourceIdsBySource { + readonly eod: readonly string[]; + readonly qm: readonly string[]; +} + +export interface ReadSampleClosesOptions { + readonly sampleDates: readonly string[]; + readonly sourceIdsBySource: SampleCloseSourceIdsBySource; + readonly includeFx?: boolean; + readonly batchSize?: number; + readonly idChunkSize?: number; +} + +export interface SampleCloseSkipCounts { + missingId: number; + unrequestedId: number; + invalidDate: number; + unrequestedDate: number; + invalidClose: number; +} + +export type SampleCloseSkipReason = keyof SampleCloseSkipCounts; + +export interface SampleCloseSourceReadStats { + collection: string; + findsRun: number; + docsRead: number; + emitted: number; + skippedTotal: number; + skipped: SampleCloseSkipCounts; +} + +export interface ReadSampleClosesStats { + eod: SampleCloseSourceReadStats; + qm: SampleCloseSourceReadStats; + fx: SampleCloseSourceReadStats; +} + +export interface ReadSampleClosesResult { + sampleDates: string[]; + closes: SampleCloseRecord[]; + fxRates: FxRateByDateRecord[]; + stats: ReadSampleClosesStats; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +function isSampleCloseSource(value: unknown): value is SampleCloseSource { + return value === 'eod' || value === 'qm'; +} + +function isPlainRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function isAsyncIterable(value: unknown): value is AsyncIterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.asyncIterator] === 'function' + ); +} + +function validatePositiveSafeInt(value: unknown, name: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`); + } + return value; +} + +function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { + if ( + reader === null || + reader === undefined || + typeof reader !== 'object' || + typeof reader.isReadOnly !== 'function' || + typeof reader.find !== 'function' || + reader.isReadOnly() !== true + ) { + throw new Error( + 'Sample close reader requires a read-only MongoDB reader (isReadOnly() must be true)' + ); + } +} + +/** + * Validates, deduplicates, and ASCII-sorts exact Gregorian `YYYY-MM-DD` sample dates. + * Rejects empty lists, malformed/padded/rollover dates, and lists exceeding `MAX_SAMPLE_DATES`. + */ +function normalizeSampleDates(sampleDates: readonly string[]): string[] { + if (!Array.isArray(sampleDates)) { + throw new RangeError('sampleDates must be a non-empty array of YYYY-MM-DD strings'); + } + if (sampleDates.length === 0) { + throw new RangeError('sampleDates must not be empty'); + } + + const unique = new Set(); + for (let i = 0; i < sampleDates.length; i++) { + const raw = sampleDates[i]; + if ( + typeof raw !== 'string' || + !EXACT_YMD_PATTERN.test(raw) || + normalizeBarDate(raw) !== raw + ) { + throw new RangeError( + `sampleDates[${i}] must be a valid exact YYYY-MM-DD date, received ${JSON.stringify(raw)}` + ); + } + unique.add(raw); + } + + if (unique.size > MAX_SAMPLE_DATES) { + throw new RangeError( + `sampleDates exceeds maximum allowed count of ${MAX_SAMPLE_DATES} (received ${unique.size})` + ); + } + + return Array.from(unique).sort(compareAscii); +} + +/** + * Validates, deduplicates, and ASCII-sorts requested source IDs without trimming non-blank strings + * (T-49). Whitespace-only entries are dropped; `CAD.FOREX` is excluded when `excludeFx` is true. + */ +function normalizeRequestedIds( + rawIds: readonly string[], + fieldName: string, + options?: { readonly excludeFx?: boolean } +): string[] { + if (!Array.isArray(rawIds)) { + throw new TypeError(`${fieldName} must be an array of strings`); + } + + const excludeFx = options?.excludeFx === true; + const unique = new Set(); + for (let i = 0; i < rawIds.length; i++) { + const raw = rawIds[i]; + if (typeof raw !== 'string') { + throw new TypeError(`${fieldName}[${i}] must be a string, received ${typeof raw}`); + } + if (raw.trim().length === 0) { + continue; + } + if (excludeFx && raw === FX_USD_CAD_SOURCE_ID) { + continue; + } + unique.add(raw); + } + + return Array.from(unique).sort(compareAscii); +} + +function createEmptySkipCounts(): SampleCloseSkipCounts { + return { + missingId: 0, + unrequestedId: 0, + invalidDate: 0, + unrequestedDate: 0, + invalidClose: 0, + }; +} + +function createSourceStats(collection: string): SampleCloseSourceReadStats { + return { + collection, + findsRun: 0, + docsRead: 0, + emitted: 0, + skippedTotal: 0, + skipped: createEmptySkipCounts(), + }; +} + +function recordSkip(stats: SampleCloseSourceReadStats, reason: SampleCloseSkipReason): void { + stats.skipped[reason] += 1; + stats.skippedTotal += 1; +} + +function wrapCollectionReadError(collectionName: string, error: unknown): Error { + const detail = error instanceof Error ? error.message : String(error); + const message = detail.includes(collectionName) + ? detail + : `Failed reading collection "${collectionName}": ${detail}`; + return new Error(message, { cause: error }); +} + +async function streamSampleCloseFind( + reader: ReadOnlySourceSymbolReader, + collectionName: string, + filter: Record, + findOptions: SourceSymbolFindOptions, + onDoc: (doc: unknown) => void +): Promise { + assertReadOnlyReader(reader); + let closableHandle: Pick>, 'close'> | null = + null; + let primaryError: unknown = undefined; + let hasPrimaryError = false; + let isInvalidCursorError = false; + + try { + const rawCursor = await reader.find>( + collectionName, + filter, + findOptions + ); + if ( + rawCursor !== null && + (typeof rawCursor === 'object' || typeof rawCursor === 'function') + ) { + closableHandle = rawCursor as Pick< + ReadOnlySourceSymbolCursor>, + 'close' + >; + } + if (Array.isArray(rawCursor) || !isAsyncIterable>(rawCursor)) { + isInvalidCursorError = true; + throw new TypeError( + `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)` + ); + } + for await (const doc of rawCursor) { + onDoc(doc); + } + } catch (error) { + primaryError = error; + hasPrimaryError = true; + } finally { + if (closableHandle !== null && typeof closableHandle.close === 'function') { + try { + await closableHandle.close(); + } catch (closeError) { + if (!hasPrimaryError) { + primaryError = closeError; + hasPrimaryError = true; + } + } + } + } + + if (hasPrimaryError) { + if (isInvalidCursorError) { + throw primaryError; + } + throw wrapCollectionReadError(collectionName, primaryError); + } +} + +function compareSampleCloses(a: SampleCloseRecord, b: SampleCloseRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.date, b.date) || + a.close - b.close + ); +} + +function compareFxRates(a: FxRateByDateRecord, b: FxRateByDateRecord): number { + return compareAscii(a.date, b.date) || a.usdCad - b.usdCad; +} + +/** + * Builds a plain date-first MongoDB `find` filter for Pass 4 sample-close queries: + * `{ date: { $in: [...] } }`, optionally AND-ed with `{ eodSearchCode | qmSearchCode: { $in: [...] } }`. + * + * `eodPrices` (`price-storage.ts`) enforces `YYYY-MM-DD` strings for `date`, while + * `qmPrices` (`prices.action.ts`) copies the provider's `date` field verbatim (assumed + * `YYYY-MM-DD`, with BSON `Date` stored separately in `dateTime`), so `$in` emits sorted + * `YYYY-MM-DD` strings. + */ +export function buildSampleCloseFilter( + source: SampleCloseSource, + sampleDates: readonly string[], + sourceIds?: readonly string[] +): Record { + if (!isSampleCloseSource(source)) { + throw new RangeError(`Unsupported sample close source: "${String(source)}"`); + } + + const normalizedDates = normalizeSampleDates(sampleDates); + const spec = BAR_SPAN_COLLECTIONS[source]; + const filter: Record = { + [spec.dateField]: { $in: normalizedDates }, + }; + + if (sourceIds !== undefined) { + const normalizedIds = normalizeRequestedIds(sourceIds, 'sourceIds'); + filter[spec.idField] = { $in: normalizedIds }; + } + + return filter; +} + +/** + * Streams read-only Pass 4 sample closes from `eodPrices` (raw `close`), `qmPrices` + * (raw `unadjustedclose`), and USD/CAD FX rates from `eodPrices` (`CAD.FOREX`) using + * date-first `{ date: { $in: sampleDates } }` filters over `ReadOnlySourceSymbolReader`. + */ +export async function readSampleCloses( + reader: ReadOnlySourceSymbolReader, + options: ReadSampleClosesOptions +): Promise { + assertReadOnlyReader(reader); + + if (options === null || typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + if (options.sourceIdsBySource === null || typeof options.sourceIdsBySource !== 'object') { + throw new TypeError('options.sourceIdsBySource must be an object'); + } + + const sampleDates = normalizeSampleDates(options.sampleDates); + const sampleDateSet = new Set(sampleDates); + + const eodIds = normalizeRequestedIds(options.sourceIdsBySource.eod, 'sourceIdsBySource.eod', { + excludeFx: true, + }); + const qmIds = normalizeRequestedIds(options.sourceIdsBySource.qm, 'sourceIdsBySource.qm'); + + const includeFx = options.includeFx ?? true; + if (typeof includeFx !== 'boolean') { + throw new TypeError('options.includeFx must be a boolean'); + } + + const batchSize = + options.batchSize !== undefined + ? validatePositiveSafeInt(options.batchSize, 'options.batchSize') + : undefined; + const idChunkSize = + options.idChunkSize !== undefined + ? validatePositiveSafeInt(options.idChunkSize, 'options.idChunkSize') + : DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE; + + const eodFindOptions: SourceSymbolFindOptions = + batchSize !== undefined + ? { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, batchSize } + : { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION } }; + const qmFindOptions: SourceSymbolFindOptions = + batchSize !== undefined + ? { projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, batchSize } + : { projection: { ...QM_SAMPLE_CLOSES_PROJECTION } }; + + const stats: ReadSampleClosesStats = { + eod: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection), + qm: createSourceStats(BAR_SPAN_COLLECTIONS.qm.collection), + fx: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection), + }; + + const closes: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + + const readEquitySource = async ( + source: SampleCloseSource, + ids: readonly string[], + findOptions: SourceSymbolFindOptions + ): Promise => { + if (ids.length === 0) { + return; + } + + const spec = BAR_SPAN_COLLECTIONS[source]; + const closeField = source === 'eod' ? 'close' : 'unadjustedclose'; + const sourceStats = stats[source]; + + for (let offset = 0; offset < ids.length; offset += idChunkSize) { + const chunkIds = ids.slice(offset, offset + idChunkSize); + const chunkIdSet = new Set(chunkIds); + const filter = buildSampleCloseFilter(source, sampleDates, chunkIds); + sourceStats.findsRun += 1; + + await streamSampleCloseFind(reader, spec.collection, filter, findOptions, doc => { + sourceStats.docsRead += 1; + + if (!isPlainRecord(doc)) { + recordSkip(sourceStats, 'missingId'); + return; + } + + const rawId = doc[spec.idField]; + if (typeof rawId !== 'string' || rawId.trim().length === 0) { + recordSkip(sourceStats, 'missingId'); + return; + } + + if (!chunkIdSet.has(rawId)) { + recordSkip(sourceStats, 'unrequestedId'); + return; + } + + const rawDate = doc[spec.dateField]; + const normalizedDate = + typeof rawDate === 'string' && sampleDateSet.has(rawDate) + ? rawDate + : normalizeBarDate(rawDate); + if (normalizedDate === null) { + recordSkip(sourceStats, 'invalidDate'); + return; + } + if (!sampleDateSet.has(normalizedDate)) { + recordSkip(sourceStats, 'unrequestedDate'); + return; + } + + const rawClose = doc[closeField]; + if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) { + recordSkip(sourceStats, 'invalidClose'); + return; + } + + closes.push({ + source, + sourceId: rawId, + date: normalizedDate, + close: rawClose, + }); + sourceStats.emitted += 1; + }); + } + }; + + await readEquitySource('eod', eodIds, eodFindOptions); + await readEquitySource('qm', qmIds, qmFindOptions); + + if (includeFx) { + const eodSpec = BAR_SPAN_COLLECTIONS.eod; + const fxFilter = buildSampleCloseFilter('eod', sampleDates, [FX_USD_CAD_SOURCE_ID]); + stats.fx.findsRun += 1; + + await streamSampleCloseFind(reader, eodSpec.collection, fxFilter, eodFindOptions, doc => { + stats.fx.docsRead += 1; + + if (!isPlainRecord(doc)) { + recordSkip(stats.fx, 'missingId'); + return; + } + + const rawId = doc[eodSpec.idField]; + if (typeof rawId !== 'string' || rawId.trim().length === 0) { + recordSkip(stats.fx, 'missingId'); + return; + } + + if (rawId !== FX_USD_CAD_SOURCE_ID) { + recordSkip(stats.fx, 'unrequestedId'); + return; + } + + const rawDate = doc[eodSpec.dateField]; + const normalizedDate = + typeof rawDate === 'string' && sampleDateSet.has(rawDate) + ? rawDate + : normalizeBarDate(rawDate); + if (normalizedDate === null) { + recordSkip(stats.fx, 'invalidDate'); + return; + } + if (!sampleDateSet.has(normalizedDate)) { + recordSkip(stats.fx, 'unrequestedDate'); + return; + } + + const rawClose = doc.close; + if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) { + recordSkip(stats.fx, 'invalidClose'); + return; + } + + fxRates.push({ + date: normalizedDate, + usdCad: rawClose, + }); + stats.fx.emitted += 1; + }); + } + + closes.sort(compareSampleCloses); + fxRates.sort(compareFxRates); + + return { + sampleDates, + closes, + fxRates, + stats, + }; +} diff --git a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts new file mode 100644 index 00000000..da009d68 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts @@ -0,0 +1,915 @@ +import { compareAscii } from './exchange-pass1'; +import type { + ReadOnlySourceSymbolCursor, + ReadOnlySourceSymbolReader, + SourceSymbolFindOptions, +} from './source-symbol-readers'; + +export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([ + 'ceoShorts', + 'qmSplits', + 'qmDividends', + 'qmFilings', + 'qmEarnings', + 'qmPrices', + 'eodPrices', + 'teMarketData', +] as const); + +export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]; + +export const FIELD_VALUE_TYPES = Object.freeze([ + 'string', + 'int', + 'double', + 'bool', + 'date', + 'null', + 'objectId', + 'array', + 'object', + 'other', +] as const); + +export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number]; + +export const STRING_PATTERN_CLASSES = Object.freeze([ + 'ymd', + 'isoDatetime', + 'numeric', + 'emptyOrWhitespace', + 'other', +] as const); + +export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number]; + +export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000; +export const MAX_FIELD_SHAPE_LIMIT = 10_000; +export const DEFAULT_MAX_EXAMPLES = 3; +export const MAX_EXAMPLES_CAP = 10; +export const DEFAULT_MAX_EXAMPLE_LENGTH = 48; +export const MAX_EXAMPLE_LENGTH_CAP = 120; + +const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet = new Set( + FIELD_SHAPE_PROBE_COLLECTIONS +); + +export class UnknownProbeCollectionError extends Error { + readonly collectionName: string; + readonly allowedCollections: readonly FieldShapeProbeCollection[]; + + constructor(collectionName: string) { + super( + `Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}` + ); + this.name = 'UnknownProbeCollectionError'; + this.collectionName = collectionName; + this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export type FieldValueTypeCounts = Record; +export type StringPatternCounts = Record; + +export interface FieldStringStats { + minLength: number; + maxLength: number; + patterns: StringPatternCounts; +} + +export interface FieldShapeSummary { + field: string; + presentCount: number; + missingCount: number; + typeCounts: FieldValueTypeCounts; + stringStats: FieldStringStats | null; + examples: string[]; +} + +export interface SummarizeFieldShapesOptions { + readonly maxExamples?: number; + readonly maxExampleLength?: number; +} + +export interface CollectionFieldShapesSummary { + docCount: number; + fields: FieldShapeSummary[]; +} + +export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions { + readonly collections?: readonly string[]; + readonly limit?: number; + readonly batchSize?: number; +} + +export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary { + collection: FieldShapeProbeCollection; +} + +export interface ReadFieldShapesResult { + limit: number; + maxExamples: number; + maxExampleLength: number; + totalDocsSampled: number; + collections: CollectionFieldShapesProbeResult[]; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const STRICT_ISO_DATETIME_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/; +const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function isValidCalendarDate(year: number, month: number, day: number): boolean { + if (year < 1 || year > 9999 || month < 1 || month > 12) { + return false; + } + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + return day >= 1 && day <= maxDay; +} + +function isValidYmd(value: string): boolean { + if (!EXACT_YMD_PATTERN.test(value)) { + return false; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + return isValidCalendarDate(year, month, day); +} + +function isValidIsoDatetime(value: string): boolean { + const match = STRICT_ISO_DATETIME_PATTERN.exec(value); + if (match === null) { + return false; + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hour = Number(match[4]); + const minute = Number(match[5]); + const second = Number(match[6]); + + if (!isValidCalendarDate(year, month, day)) { + return false; + } + if (hour > 23 || minute > 59 || second > 59) { + return false; + } + if (match[7] !== undefined) { + const tzHour = Number(match[8]); + const tzMinute = Number(match[9]); + if (tzHour > 23 || tzMinute > 59) { + return false; + } + } + return true; +} + +function classifyStringPattern(value: string): StringPatternClass { + if (value.length === 0 || value.trim().length === 0) { + return 'emptyOrWhitespace'; + } + if (value.length === 10 && isValidYmd(value)) { + return 'ymd'; + } + if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) { + return 'isoDatetime'; + } + if (NUMERIC_STRING_PATTERN.test(value)) { + return 'numeric'; + } + return 'other'; +} + +function createEmptyTypeCounts(): FieldValueTypeCounts { + return { + string: 0, + int: 0, + double: 0, + bool: 0, + date: 0, + null: 0, + objectId: 0, + array: 0, + object: 0, + other: 0, + }; +} + +function createEmptyStringPatternCounts(): StringPatternCounts { + return { + ymd: 0, + isoDatetime: 0, + numeric: 0, + emptyOrWhitespace: 0, + other: 0, + }; +} + +function isNonPlainBuiltInObject(value: object): boolean { + return ( + value instanceof Date || + Array.isArray(value) || + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + value instanceof RegExp || + value instanceof Map || + value instanceof Set + ); +} + +function getBsonTypeTag(value: object): string | null { + const tag = (value as { _bsontype?: unknown })._bsontype; + return typeof tag === 'string' && tag.length > 0 ? tag : null; +} + +function isPlainNestedObject(value: unknown): value is Record { + if (value === null || typeof value !== 'object') { + return false; + } + if (isNonPlainBuiltInObject(value)) { + return false; + } + if (getBsonTypeTag(value) !== null) { + return false; + } + return true; +} + +function classifyValueType(value: unknown): FieldValueType { + if (value === null) { + return 'null'; + } + const primitiveType = typeof value; + if (primitiveType === 'string') { + return 'string'; + } + if (primitiveType === 'boolean') { + return 'bool'; + } + if (primitiveType === 'number') { + return Number.isInteger(value) ? 'int' : 'double'; + } + if (primitiveType === 'bigint') { + return 'int'; + } + if (primitiveType !== 'object') { + return 'other'; + } + + const obj = value as object; + if (obj instanceof Date) { + return 'date'; + } + if (Array.isArray(obj)) { + return 'array'; + } + + const bsonTag = getBsonTypeTag(obj); + if (bsonTag !== null) { + if (bsonTag === 'Int32' || bsonTag === 'Long') { + return 'int'; + } + if (bsonTag === 'Double') { + return 'double'; + } + if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') { + return 'objectId'; + } + return 'other'; + } + + if (isNonPlainBuiltInObject(obj)) { + return 'other'; + } + + return 'object'; +} + +function escapeFieldSegment(segment: string): string { + if (!segment.includes('.') && !segment.includes('\\')) { + return segment; + } + return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.'); +} + +function formatFieldPath(parentKey: string, childKey?: string): string { + const escapedParent = escapeFieldSegment(parentKey); + return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`; +} + +function sanitizeAndTruncateExample(raw: string, maxLength: number): string { + let cleaned = ''; + for (let i = 0; i < raw.length; i++) { + const code = raw.charCodeAt(i); + if (code === 9 || code === 10 || code === 13) { + cleaned += ' '; + } else if (code >= 32 && code !== 127) { + cleaned += raw[i]; + } + } + if (cleaned.length <= maxLength) { + return cleaned; + } + if (maxLength <= 3) { + return cleaned.slice(0, maxLength); + } + return `${cleaned.slice(0, maxLength - 3)}...`; +} + +function extractScalarExample( + value: unknown, + valueType: FieldValueType, + maxExampleLength: number +): string | null { + if (valueType === 'null' || valueType === 'array' || valueType === 'object') { + return null; + } + + let raw: string | null = null; + if (valueType === 'string') { + raw = value as string; + } else if (valueType === 'bool') { + raw = (value as boolean) ? 'true' : 'false'; + } else if (valueType === 'int' || valueType === 'double') { + if (typeof value === 'number' || typeof value === 'bigint') { + raw = String(value); + } else if (value !== null && typeof value === 'object') { + raw = String(value); + } + } else if (valueType === 'date' && value instanceof Date) { + raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString(); + } else if (valueType === 'objectId') { + raw = String(value); + } else if (valueType === 'other' && value !== null && typeof value === 'object') { + const bsonTag = getBsonTypeTag(value); + if (bsonTag === 'Decimal128' || bsonTag === 'UUID') { + raw = String(value); + } + } + + if (raw === null) { + return null; + } + return sanitizeAndTruncateExample(raw, maxExampleLength); +} + +function validateBoundedInt(value: unknown, name: string, min: number, max: number): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) { + throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`); + } + return value; +} + +function validatePositiveSafeInt(value: unknown, name: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`); + } + return value; +} + +function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): { + maxExamples: number; + maxExampleLength: number; +} { + if (options !== undefined && (options === null || typeof options !== 'object')) { + throw new TypeError('options must be an object'); + } + const maxExamples = + options?.maxExamples !== undefined + ? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP) + : DEFAULT_MAX_EXAMPLES; + const maxExampleLength = + options?.maxExampleLength !== undefined + ? validateBoundedInt( + options.maxExampleLength, + 'options.maxExampleLength', + 1, + MAX_EXAMPLE_LENGTH_CAP + ) + : DEFAULT_MAX_EXAMPLE_LENGTH; + return { maxExamples, maxExampleLength }; +} + +interface MutableFieldAccumulator { + presentCount: number; + typeCounts: FieldValueTypeCounts; + stringStats: FieldStringStats | null; + examples: string[]; +} + +/** + * Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes` + * and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field. + */ +class FieldShapeAccumulator { + private readonly maxExamples: number; + private readonly maxExampleLength: number; + private readonly fields = new Map(); + private docCount = 0; + + constructor(maxExamples: number, maxExampleLength: number) { + this.maxExamples = maxExamples; + this.maxExampleLength = maxExampleLength; + } + + addDocument(doc: unknown): void { + this.docCount += 1; + if (!isPlainNestedObject(doc)) { + return; + } + + const keys = Object.keys(doc); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key === undefined) { + continue; + } + const value = doc[key]; + if (value === undefined) { + continue; + } + + const suppressExamples = key === '_id'; + const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples); + if (valueType === 'object' && isPlainNestedObject(value)) { + const childKeys = Object.keys(value); + for (let j = 0; j < childKeys.length; j++) { + const childKey = childKeys[j]; + if (childKey === undefined) { + continue; + } + const childValue = value[childKey]; + if (childValue === undefined) { + continue; + } + this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples); + } + } + } + } + + finalize(): CollectionFieldShapesSummary { + const sortedNames = Array.from(this.fields.keys()).sort(compareAscii); + const summaries: FieldShapeSummary[] = []; + for (let i = 0; i < sortedNames.length; i++) { + const fieldName = sortedNames[i]; + if (fieldName === undefined) { + continue; + } + const acc = this.fields.get(fieldName); + if (acc === undefined) { + continue; + } + summaries.push({ + field: fieldName, + presentCount: acc.presentCount, + missingCount: this.docCount - acc.presentCount, + typeCounts: { ...acc.typeCounts }, + stringStats: + acc.stringStats === null + ? null + : { + minLength: acc.stringStats.minLength, + maxLength: acc.stringStats.maxLength, + patterns: { ...acc.stringStats.patterns }, + }, + examples: [...acc.examples], + }); + } + + return { + docCount: this.docCount, + fields: summaries, + }; + } + + private recordFieldValue( + fieldPath: string, + value: unknown, + suppressExamples: boolean + ): FieldValueType { + let acc = this.fields.get(fieldPath); + if (acc === undefined) { + acc = { + presentCount: 0, + typeCounts: createEmptyTypeCounts(), + stringStats: null, + examples: [], + }; + this.fields.set(fieldPath, acc); + } + + const valueType = classifyValueType(value); + acc.presentCount += 1; + acc.typeCounts[valueType] += 1; + + if (valueType === 'string') { + const str = value as string; + const len = str.length; + if (acc.stringStats === null) { + acc.stringStats = { + minLength: len, + maxLength: len, + patterns: createEmptyStringPatternCounts(), + }; + } else { + if (len < acc.stringStats.minLength) { + acc.stringStats.minLength = len; + } + if (len > acc.stringStats.maxLength) { + acc.stringStats.maxLength = len; + } + } + acc.stringStats.patterns[classifyStringPattern(str)] += 1; + } + + if (this.maxExamples > 0 && !suppressExamples) { + const example = extractScalarExample(value, valueType, this.maxExampleLength); + if (example !== null) { + this.insertExample(acc.examples, example); + } + } + + return valueType; + } + + private insertExample(examples: string[], candidate: string): void { + const len = examples.length; + const last = len > 0 ? examples[len - 1] : undefined; + if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) { + return; + } + + let insertAt = len; + for (let i = 0; i < len; i++) { + const existing = examples[i]; + if (existing === undefined) { + continue; + } + const cmp = compareAscii(candidate, existing); + if (cmp === 0) { + return; + } + if (cmp < 0) { + insertAt = i; + break; + } + } + + examples.splice(insertAt, 0, candidate); + if (examples.length > this.maxExamples) { + examples.pop(); + } + } +} + +/** + * Pure, deterministic summarizer for field names, BSON/JS value types, string patterns, + * and bounded sanitized examples across an iterable of documents from one collection. + */ +export function summarizeFieldShapes( + docs: Iterable>, + options?: SummarizeFieldShapesOptions +): CollectionFieldShapesSummary { + if ( + docs === null || + docs === undefined || + typeof (docs as unknown as Record)[Symbol.iterator] !== 'function' + ) { + throw new TypeError('docs must be an Iterable of document objects'); + } + const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options); + const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength); + for (const doc of docs) { + accumulator.addDocument(doc); + } + return accumulator.finalize(); +} + +export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection { + return ALLOWED_PROBE_COLLECTION_SET.has(value); +} + +export function normalizeProbeCollections( + collections?: readonly string[] +): FieldShapeProbeCollection[] { + const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections; + if (!Array.isArray(source) || source.length === 0) { + throw new RangeError('collections must be a non-empty array of allowed probe collection names'); + } + const unique = new Set(); + for (let i = 0; i < source.length; i++) { + const name = source[i]; + if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) { + throw new UnknownProbeCollectionError(String(name)); + } + unique.add(name); + } + return Array.from(unique).sort(compareAscii); +} + +function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { + if ( + reader === null || + reader === undefined || + typeof reader !== 'object' || + typeof reader.isReadOnly !== 'function' || + typeof reader.find !== 'function' || + reader.isReadOnly() !== true + ) { + throw new Error( + 'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)' + ); + } +} + +function isAsyncIterable(value: unknown): value is AsyncIterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.asyncIterator] === 'function' + ); +} + +function wrapCollectionReadError(collectionName: string, error: unknown): Error { + const detail = error instanceof Error ? error.message : String(error); + const message = detail.includes(collectionName) + ? detail + : `Failed reading collection "${collectionName}": ${detail}`; + return new Error(message, { cause: error }); +} + +async function streamBoundedCollectionIntoAccumulator( + reader: ReadOnlySourceSymbolReader, + collectionName: FieldShapeProbeCollection, + limit: number, + findOptions: SourceSymbolFindOptions, + accumulator: FieldShapeAccumulator +): Promise { + assertReadOnlyReader(reader); + let closableHandle: Pick>, 'close'> | null = + null; + let primaryError: unknown = undefined; + let hasPrimaryError = false; + let isInvalidCursorError = false; + + try { + const rawCursor = await reader.find>(collectionName, {}, findOptions); + if ( + rawCursor !== null && + (typeof rawCursor === 'object' || typeof rawCursor === 'function') + ) { + closableHandle = rawCursor as Pick< + ReadOnlySourceSymbolCursor>, + 'close' + >; + } + if (Array.isArray(rawCursor) || !isAsyncIterable>(rawCursor)) { + isInvalidCursorError = true; + throw new TypeError( + `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)` + ); + } + + let seen = 0; + if (limit > 0) { + for await (const doc of rawCursor) { + accumulator.addDocument(doc); + seen += 1; + if (seen >= limit) { + break; + } + } + } + } catch (error) { + primaryError = error; + hasPrimaryError = true; + } finally { + if (closableHandle !== null && typeof closableHandle.close === 'function') { + try { + await closableHandle.close(); + } catch (closeError) { + if (!hasPrimaryError) { + primaryError = closeError; + hasPrimaryError = true; + } + } + } + } + + if (hasPrimaryError) { + if (isInvalidCursorError) { + throw primaryError; + } + throw wrapCollectionReadError(collectionName, primaryError); + } +} + +/** + * Bounded, read-only MongoDB field-shape probe over allowlisted source collections. + * Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` + * with zero aggregations, `$sample`, writes, or index operations. + */ +export async function readFieldShapes( + reader: ReadOnlySourceSymbolReader, + options?: ReadFieldShapesOptions +): Promise { + assertReadOnlyReader(reader); + + if (options !== undefined && (options === null || typeof options !== 'object')) { + throw new TypeError('options must be an object'); + } + + const limit = + options?.limit !== undefined + ? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT) + : DEFAULT_FIELD_SHAPE_LIMIT; + const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options); + const batchSize = + options?.batchSize !== undefined + ? validatePositiveSafeInt(options.batchSize, 'options.batchSize') + : undefined; + const collections = normalizeProbeCollections(options?.collections); + + const findOptions: SourceSymbolFindOptions = { + limit, + promoteValues: false, + promoteLongs: false, + ...(batchSize !== undefined ? { batchSize } : {}), + }; + + const results: CollectionFieldShapesProbeResult[] = []; + let totalDocsSampled = 0; + + for (const collection of collections) { + const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength); + await streamBoundedCollectionIntoAccumulator( + reader, + collection, + limit, + findOptions, + accumulator + ); + const summary = accumulator.finalize(); + totalDocsSampled += summary.docCount; + results.push({ + collection, + docCount: summary.docCount, + fields: summary.fields, + }); + } + + return { + limit, + maxExamples, + maxExampleLength, + totalDocsSampled, + collections: results, + }; +} + +function formatHtmlCodeElement(value: string): string { + const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => { + switch (ch) { + case '&': + return '&'; + case '<': + return '<'; + case '>': + return '>'; + case '|': + return '|'; + default: + return `&#${ch.charCodeAt(0)};`; + } + }); + return `${escaped}`; +} + +function formatMarkdownCodeCell(value: string): string { + const normalized = value.replace(/\r\n|\r|\n/g, ' '); + // Empty spans cannot be written with backtick fences; values containing `\|` + // would become `\\|` under pipe escaping, which GFM/micromark parses as an + // escaped backslash followed by a cell-splitting pipe. Use an HTML + // element with entity-encoded pipes and Markdown metacharacters instead. + if (normalized.length === 0 || normalized.includes('\\|')) { + return formatHtmlCodeElement(normalized); + } + const tableSafe = normalized.replace(/\|/g, '\\|'); + let maxBacktickRun = 0; + let currentRun = 0; + for (let i = 0; i < tableSafe.length; i++) { + if (tableSafe.charCodeAt(i) === 96) { + currentRun += 1; + if (currentRun > maxBacktickRun) { + maxBacktickRun = currentRun; + } + } else { + currentRun = 0; + } + } + const fence = '`'.repeat(maxBacktickRun + 1); + const startsWithBacktick = tableSafe.charCodeAt(0) === 96; + const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96; + const startsAndEndsWithSpace = + tableSafe.charCodeAt(0) === 32 && + tableSafe.charCodeAt(tableSafe.length - 1) === 32 && + tableSafe.trim().length > 0; + const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace; + return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`; +} + +function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string { + const parts: string[] = []; + for (const typeName of FIELD_VALUE_TYPES) { + const count = typeCounts[typeName]; + if (count > 0) { + parts.push(`${typeName}: ${count}`); + } + } + return parts.length > 0 ? parts.join(', ') : '—'; +} + +function formatStringStatsCell(stringStats: FieldStringStats | null): string { + if (stringStats === null) { + return '—'; + } + const parts: string[] = []; + for (const pattern of STRING_PATTERN_CLASSES) { + const count = stringStats.patterns[pattern]; + if (count > 0) { + parts.push(`${pattern}: ${count}`); + } + } + const patternText = parts.length > 0 ? parts.join(', ') : 'none'; + return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`; +} + +function formatExamplesCell(examples: readonly string[]): string { + if (examples.length === 0) { + return '—'; + } + return examples.map(formatMarkdownCodeCell).join(', '); +} + +/** + * Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or + * filesystem paths). Identical results always produce byte-identical Markdown. + */ +export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string { + const sortedCollections = [...result.collections].sort((a, b) => + compareAscii(a.collection, b.collection) + ); + + const lines: string[] = [ + '# Source Field Shapes Report', + '', + '- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)', + `- **Sample limit per collection:** ${result.limit}`, + `- **Collections probed:** ${sortedCollections.length}`, + `- **Total documents sampled:** ${result.totalDocsSampled}`, + ]; + + for (const col of sortedCollections) { + lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, ''); + + if (col.docCount === 0) { + lines.push('_No documents sampled._'); + continue; + } + + const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field)); + if (sortedFields.length === 0) { + lines.push('_No fields observed._'); + continue; + } + + lines.push('| Field | Presence | Types | String Patterns | Examples |'); + lines.push('| --- | --- | --- | --- | --- |'); + + for (const field of sortedFields) { + const pct = ((field.presentCount / col.docCount) * 100).toFixed(1); + const fieldCell = formatMarkdownCodeCell(field.field); + const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`; + const typesCell = formatTypeCountsCell(field.typeCounts); + const patternsCell = formatStringStatsCell(field.stringStats); + const examplesCell = formatExamplesCell(field.examples); + lines.push( + `| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |` + ); + } + } + + return `${lines.join('\n')}\n`; +} diff --git a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts index 58b7ea6a..528814f2 100644 --- a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts +++ b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts @@ -53,6 +53,9 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', export interface SourceSymbolFindOptions { projection?: Record; batchSize?: number; + limit?: number; + promoteValues?: boolean; + promoteLongs?: boolean; } /** diff --git a/apps/stock/data-pipeline/test/sample-closes-edge.test.ts b/apps/stock/data-pipeline/test/sample-closes-edge.test.ts new file mode 100644 index 00000000..9de5c1e5 --- /dev/null +++ b/apps/stock/data-pipeline/test/sample-closes-edge.test.ts @@ -0,0 +1,330 @@ +import { describe, expect, test } from 'bun:test'; +import { + buildSampleCloseFilter, + createReadOnlyMongoSourceSymbolReader, + EOD_SAMPLE_CLOSES_PROJECTION, + FX_USD_CAD_SOURCE_ID, + MAX_SAMPLE_DATES, + QM_SAMPLE_CLOSES_PROJECTION, + readSampleCloses, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SampleCloseSource, + type SampleCloseSourceReadStats, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +// QA edge cases for the Pass 4a sample-close reader that complement sample-closes.test.ts. +// All readers are in-memory; no MongoDB / PostgreSQL / network. + +interface RecordedCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +function unfilteredReader(docsByCollection: Record): { + reader: ReadOnlySourceSymbolReader; + calls: RecordedCall[]; +} { + const calls: RecordedCall[] = []; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + calls.push({ collectionName, filter, options }); + const docs = docsByCollection[collectionName] ?? []; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (const doc of docs) { + yield doc as T; + } + }, + }; + }, + }; + return { reader, calls }; +} + +function expectReconciled(stats: SampleCloseSourceReadStats): void { + const s = stats.skipped; + expect(stats.skippedTotal).toBe( + s.missingId + s.unrequestedId + s.invalidDate + s.unrequestedDate + s.invalidClose + ); + expect(stats.docsRead).toBe(stats.emitted + stats.skippedTotal); +} + +function makeDistinctDates(count: number): string[] { + const out: string[] = []; + const start = Date.UTC(2020, 0, 1); + for (let i = 0; i < count; i++) { + out.push(new Date(start + i * 86_400_000).toISOString().slice(0, 10)); + } + return out; +} + +describe('Pass 4a sample-closes reader — QA edge cases', () => { + test('streams end to end through createReadOnlyMongoSourceSymbolReader, forwarding filter/projection/batchSize and closing driver cursors', async () => { + const collectionCalls: Array<{ + name: string; + filter: Record; + options: SourceSymbolFindOptions | undefined; + }> = []; + let driverCursorsClosed = 0; + const store: Record[]> = { + eodPrices: [ + { eodSearchCode: 'RY.TO', date: '2024-03-01', close: 130.5 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-03-01', close: 1.355 }, + ], + qmPrices: [{ qmSearchCode: 'RY', date: '2024-03-01', unadjustedclose: 96.3 }], + }; + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find(filter: Record, options?: SourceSymbolFindOptions) { + collectionCalls.push({ name, filter, options }); + const idField = name === 'eodPrices' ? 'eodSearchCode' : 'qmSearchCode'; + const ids = (filter[idField] as { $in: string[] }).$in; + const dates = (filter.date as { $in: string[] }).$in; + const docs = (store[name] ?? []).filter( + d => ids.includes(d[idField] as string) && dates.includes(d.date as string) + ); + return { + async *[Symbol.asyncIterator]() { + yield* docs; + }, + async close() { + driverCursorsClosed += 1; + }, + }; + }, + }; + }, + }; + + const result = await readSampleCloses(createReadOnlyMongoSourceSymbolReader(client), { + sampleDates: ['2024-03-01'], + sourceIdsBySource: { eod: ['RY.TO'], qm: ['RY'] }, + batchSize: 1000, + }); + + expect(collectionCalls.map(c => c.name)).toEqual(['eodPrices', 'qmPrices', 'eodPrices']); + expect(collectionCalls[0]?.options).toEqual({ + projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, + batchSize: 1000, + }); + expect(collectionCalls[1]?.options).toEqual({ + projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, + batchSize: 1000, + }); + for (const call of collectionCalls) { + expect(Object.keys(call.filter)[0]).toBe('date'); + } + expect(driverCursorsClosed).toBe(3); + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'RY.TO', date: '2024-03-01', close: 130.5 }, + { source: 'qm', sourceId: 'RY', date: '2024-03-01', close: 96.3 }, + ]); + expect(result.fxRates).toEqual([{ date: '2024-03-01', usdCad: 1.355 }]); + }); + + test('accepts exactly MAX_SAMPLE_DATES dates and applies the cap after de-duplication', async () => { + const exact = makeDistinctDates(MAX_SAMPLE_DATES); + const { reader } = unfilteredReader({}); + const atCap = await readSampleCloses(reader, { + sampleDates: exact, + sourceIdsBySource: { eod: ['A.US'], qm: [] }, + includeFx: false, + }); + expect(atCap.sampleDates).toHaveLength(MAX_SAMPLE_DATES); + + const withDuplicates = [...exact, ...exact.slice(0, 10)]; + expect(withDuplicates.length).toBeGreaterThan(MAX_SAMPLE_DATES); + const deduped = await readSampleCloses(reader, { + sampleDates: withDuplicates, + sourceIdsBySource: { eod: ['A.US'], qm: [] }, + includeFx: false, + }); + expect(deduped.sampleDates).toEqual(exact); + }); + + test('chunked finds never emit a row twice and count other-chunk ids as unrequested', async () => { + const ids = ['A.US', 'B.US', 'C.US', 'D.US']; + const { reader, calls } = unfilteredReader({ + eodPrices: ids.map((id, i) => ({ eodSearchCode: id, date: '2024-02-01', close: 10 + i })), + }); + + const result = await readSampleCloses(reader, { + sampleDates: ['2024-02-01'], + sourceIdsBySource: { eod: ids, qm: [] }, + idChunkSize: 2, + includeFx: false, + }); + + expect(calls).toHaveLength(2); + expect(result.stats.eod.findsRun).toBe(2); + expect(result.closes.map(c => c.sourceId)).toEqual(ids); + expect(result.stats.eod.docsRead).toBe(8); + expect(result.stats.eod.emitted).toBe(4); + expect(result.stats.eod.skipped.unrequestedId).toBe(4); + expectReconciled(result.stats.eod); + }); + + test('wraps synchronous throws and rejected find() promises with the collection name and cause', async () => { + const syncCause = new Error('auth failed'); + const syncReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => { + throw syncCause; + }, + }; + const syncError = await readSampleCloses(syncReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: ['AAPL'] }, + includeFx: false, + }).catch((e: unknown) => e); + expect(syncError).toBeInstanceOf(Error); + expect((syncError as Error).message).toContain('qmPrices'); + expect((syncError as Error).message).toContain('auth failed'); + expect((syncError as Error).cause).toBe(syncCause); + + const asyncCause = new Error('server selection timed out'); + const asyncReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => Promise.reject(asyncCause), + }; + const asyncError = await readSampleCloses(asyncReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + includeFx: false, + }).catch((e: unknown) => e); + expect((asyncError as Error).message).toContain('eodPrices'); + expect((asyncError as Error).cause).toBe(asyncCause); + }); + + test('requested ids with surrounding spaces do not match trimmed stored ids, and blank-only id lists issue no finds', async () => { + const { reader, calls } = unfilteredReader({ + eodPrices: [{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185 }], + qmPrices: [{ qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185 }], + }); + + const result = await readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US '], qm: [' ', ''] }, + includeFx: false, + }); + + expect(calls).toHaveLength(1); + expect(calls[0]?.filter?.eodSearchCode).toEqual({ $in: ['AAPL.US '] }); + expect(result.closes).toEqual([]); + expect(result.stats.eod.skipped.unrequestedId).toBe(1); + expect(result.stats.qm.findsRun).toBe(0); + }); + + test('stops before the next find when the reader stops reporting read-only mid-run', async () => { + let readOnly = true; + const collections: string[] = []; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => readOnly, + find = Record>( + collectionName: string + ): ReadOnlySourceSymbolCursor { + collections.push(collectionName); + readOnly = false; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty + }, + }; + }, + }; + + await expect( + readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: ['AAPL'] }, + }) + ).rejects.toThrow(/isReadOnly/); + expect(collections).toEqual(['eodPrices']); + }); + + test('qm rows never fall back to close/adjustedclose when unadjustedclose is missing', async () => { + const { reader } = unfilteredReader({ + qmPrices: [ + { qmSearchCode: 'AAPL', date: '2024-01-02', close: 185, adjustedclose: 184 }, + { qmSearchCode: 'AAPL', date: '2024-01-03', unadjustedclose: null, close: 186 }, + ], + }); + + const result = await readSampleCloses(reader, { + sampleDates: ['2024-01-02', '2024-01-03'], + sourceIdsBySource: { eod: [], qm: ['AAPL'] }, + includeFx: false, + }); + + expect(result.closes).toEqual([]); + expect(result.stats.qm.skipped.invalidClose).toBe(2); + expectReconciled(result.stats.qm); + }); + + test('FX rates keep CAD-per-USD orientation and includeFx=false issues no FX find', async () => { + const docs = { eodPrices: [{ eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.35 }] }; + + const withFx = await readSampleCloses(unfilteredReader(docs).reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: [] }, + }); + expect(withFx.fxRates).toEqual([{ date: '2024-01-02', usdCad: 1.35 }]); + + const noFx = unfilteredReader(docs); + const withoutFx = await readSampleCloses(noFx.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: [] }, + includeFx: false, + }); + expect(noFx.calls).toHaveLength(0); + expect(withoutFx.fxRates).toEqual([]); + expect(withoutFx.stats.fx.findsRun).toBe(0); + }); + + test('does not mutate caller inputs', async () => { + const sampleDates = ['2024-01-03', '2024-01-02', '2024-01-03']; + const eod = ['B.US', 'A.US', FX_USD_CAD_SOURCE_ID]; + const qm = ['B', 'A']; + const { reader } = unfilteredReader({}); + + buildSampleCloseFilter('eod', sampleDates, eod); + await readSampleCloses(reader, { sampleDates, sourceIdsBySource: { eod, qm } }); + + expect(sampleDates).toEqual(['2024-01-03', '2024-01-02', '2024-01-03']); + expect(eod).toEqual(['B.US', 'A.US', FX_USD_CAD_SOURCE_ID]); + expect(qm).toEqual(['B', 'A']); + }); + + test('rejects unsupported sources and non-string requested ids before any find', async () => { + expect(() => + buildSampleCloseFilter('ib' as unknown as SampleCloseSource, ['2024-01-02']) + ).toThrow(RangeError); + + const { reader, calls } = unfilteredReader({}); + await expect( + readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['A.US'], qm: [42 as unknown as string] }, + }) + ).rejects.toThrow(TypeError); + await expect( + readSampleCloses(reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['A.US'], qm: [] }, + batchSize: 1.5, + }) + ).rejects.toThrow(RangeError); + expect(calls).toHaveLength(0); + }); +}); diff --git a/apps/stock/data-pipeline/test/sample-closes.test.ts b/apps/stock/data-pipeline/test/sample-closes.test.ts new file mode 100644 index 00000000..2b5950f4 --- /dev/null +++ b/apps/stock/data-pipeline/test/sample-closes.test.ts @@ -0,0 +1,860 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { + buildSampleCloseFilter, + crossCheckPrices, + DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE, + EOD_SAMPLE_CLOSES_PROJECTION, + FX_USD_CAD_SOURCE_ID, + MAX_SAMPLE_DATES, + QM_SAMPLE_CLOSES_PROJECTION, + readSampleCloses, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SampleCloseSourceReadStats, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +interface RecordedFindCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +interface FakeReaderOptions { + readOnly?: boolean; + applyFilter?: boolean; + applyProjection?: boolean; + failOnCallIndex?: number; + failAfterDocs?: number; + failMessage?: string; + failCloseOnCallIndex?: number; +} + +interface FakeReaderHandle { + reader: ReadOnlySourceSymbolReader; + calls: RecordedFindCall[]; + closedCount: () => number; +} + +function matchesSimpleFilter( + doc: unknown, + filter: Record | undefined +): boolean { + if (filter === undefined) { + return true; + } + if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) { + return false; + } + const record = doc as Record; + for (const [key, condition] of Object.entries(filter)) { + if ( + condition !== null && + typeof condition === 'object' && + !Array.isArray(condition) && + '$in' in condition + ) { + const allowed = (condition as { $in: unknown[] }).$in; + if (!allowed.includes(record[key])) { + return false; + } + } else if (record[key] !== condition) { + return false; + } + } + return true; +} + +function projectDoc( + doc: unknown, + projection: Record | undefined +): Record { + if (projection === undefined || doc === null || typeof doc !== 'object' || Array.isArray(doc)) { + return doc as Record; + } + const record = doc as Record; + const projected: Record = {}; + for (const [key, include] of Object.entries(projection)) { + if (include === 1 && key in record) { + projected[key] = record[key]; + } + } + return projected; +} + +function createFakeReader( + docsByCollection: Record, + options: FakeReaderOptions = {} +): FakeReaderHandle { + const calls: RecordedFindCall[] = []; + let closed = 0; + + const reader: ReadOnlySourceSymbolReader = { + isReadOnly(): boolean { + return options.readOnly ?? true; + }, + find = Record>( + collectionName: string, + filter?: Record, + findOptions?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + const callIndex = calls.length; + calls.push({ collectionName, filter, options: findOptions }); + + const rawDocs = docsByCollection[collectionName] ?? []; + const shouldFail = options.failOnCallIndex === callIndex; + const failAfter = options.failAfterDocs ?? 0; + const failMessage = options.failMessage ?? 'simulated cursor read failure'; + const shouldFailClose = options.failCloseOnCallIndex === callIndex; + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + let yielded = 0; + for (let i = 0; i < rawDocs.length; i++) { + const rawDoc = rawDocs[i]; + if (options.applyFilter && !matchesSimpleFilter(rawDoc, filter)) { + continue; + } + if (shouldFail && yielded >= failAfter) { + throw new Error(failMessage); + } + const out = options.applyProjection + ? projectDoc(rawDoc, findOptions?.projection) + : rawDoc; + yielded += 1; + yield out as T; + } + if (shouldFail && yielded >= failAfter) { + throw new Error(failMessage); + } + }, + async close(): Promise { + closed += 1; + if (shouldFailClose) { + throw new Error('simulated cursor close failure'); + } + }, + }; + }, + }; + + return { + reader, + calls, + closedCount: () => closed, + }; +} + +function assertStatsReconcile(stats: SampleCloseSourceReadStats): void { + const skipSum = + stats.skipped.missingId + + stats.skipped.unrequestedId + + stats.skipped.invalidDate + + stats.skipped.unrequestedDate + + stats.skipped.invalidClose; + expect(stats.skippedTotal).toBe(skipSum); + expect(stats.docsRead).toBe(stats.emitted + stats.skippedTotal); +} + +function makeSampleDates(count: number): string[] { + const dates: string[] = []; + let year = 2024; + let month = 1; + let day = 1; + while (dates.length < count) { + dates.push( + `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}` + ); + day += 1; + if (day > 28) { + day = 1; + month += 1; + if (month > 12) { + month = 1; + year += 1; + } + } + } + return dates; +} + +describe('Pass 4a sample-closes reader', () => { + test('sample-closes.ts has zero runtime DB, FS, or network imports', () => { + const srcPath = resolve(import.meta.dir, '../src/security-master/sample-closes.ts'); + const source = readFileSync(srcPath, 'utf8'); + const importLines = source + .split('\n') + .filter(line => /^\s*import\b/.test(line) && !/^\s*import\s+type\b/.test(line)); + + for (const line of importLines) { + expect(line).not.toContain('mongodb'); + expect(line).not.toContain('postgres'); + expect(line).not.toContain('node:fs'); + expect(line).not.toContain('node:net'); + expect(line).not.toContain('node:http'); + expect(line).not.toContain('node:https'); + } + expect(source).toContain('BAR_SPAN_COLLECTIONS'); + expect(source).not.toContain("collection: 'eodPrices'"); + expect(source).not.toContain("collection: 'qmPrices'"); + }); + + test('buildSampleCloseFilter emits date-first filters and preserves explicit empty id lists', () => { + const dates = ['2024-06-14', '2024-01-05', '2024-06-14']; + const eodFilter = buildSampleCloseFilter('eod', dates, ['MSFT.US', 'AAPL.US', 'AAPL.US']); + expect(Object.keys(eodFilter)).toEqual(['date', 'eodSearchCode']); + expect(eodFilter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + eodSearchCode: { $in: ['AAPL.US', 'MSFT.US'] }, + }); + + const qmFilter = buildSampleCloseFilter('qm', dates, ['AAPL']); + expect(Object.keys(qmFilter)).toEqual(['date', 'qmSearchCode']); + expect(qmFilter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + qmSearchCode: { $in: ['AAPL'] }, + }); + + const dateOnlyFilter = buildSampleCloseFilter('eod', dates); + expect(Object.keys(dateOnlyFilter)).toEqual(['date']); + + const explicitEmptyFilter = buildSampleCloseFilter('qm', dates, []); + expect(Object.keys(explicitEmptyFilter)).toEqual(['date', 'qmSearchCode']); + expect(explicitEmptyFilter.qmSearchCode).toEqual({ $in: [] }); + }); + + test('passes date-first filter, strict projections, and batchSize to fake reader', async () => { + const fake = createFakeReader( + { + eodPrices: [ + { + eodSearchCode: 'AAPL.US', + date: '2024-01-05', + close: 181.18, + adjustedClose: 180.5, + volume: 999999, + }, + { + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date: '2024-01-05', + close: 1.3365, + }, + ], + qmPrices: [ + { + qmSearchCode: 'AAPL', + date: '2024-01-05', + close: 999.99, + adjustedclose: 180.5, + unadjustedclose: 181.18, + }, + ], + }, + { applyFilter: true, applyProjection: true } + ); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-06-14', '2024-01-05'], + sourceIdsBySource: { + eod: ['AAPL.US'], + qm: ['AAPL'], + }, + batchSize: 2500, + }); + + expect(fake.calls).toHaveLength(3); + + // 1. eodPrices equity call + expect(fake.calls[0]?.collectionName).toBe('eodPrices'); + expect(Object.keys(fake.calls[0]?.filter ?? {})).toEqual(['date', 'eodSearchCode']); + expect(fake.calls[0]?.filter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + eodSearchCode: { $in: ['AAPL.US'] }, + }); + expect(fake.calls[0]?.options).toEqual({ + projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, + batchSize: 2500, + }); + + // 2. qmPrices equity call + expect(fake.calls[1]?.collectionName).toBe('qmPrices'); + expect(Object.keys(fake.calls[1]?.filter ?? {})).toEqual(['date', 'qmSearchCode']); + expect(fake.calls[1]?.filter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + qmSearchCode: { $in: ['AAPL'] }, + }); + expect(fake.calls[1]?.options).toEqual({ + projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, + batchSize: 2500, + }); + expect(fake.calls[1]?.options?.projection).toEqual({ + _id: 0, + qmSearchCode: 1, + date: 1, + unadjustedclose: 1, + }); + + // 3. FX call on eodPrices for CAD.FOREX + expect(fake.calls[2]?.collectionName).toBe('eodPrices'); + expect(Object.keys(fake.calls[2]?.filter ?? {})).toEqual(['date', 'eodSearchCode']); + expect(fake.calls[2]?.filter).toEqual({ + date: { $in: ['2024-01-05', '2024-06-14'] }, + eodSearchCode: { $in: [FX_USD_CAD_SOURCE_ID] }, + }); + expect(fake.calls[2]?.options).toEqual({ + projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, + batchSize: 2500, + }); + + expect(fake.closedCount()).toBe(3); + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-05', close: 181.18 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-05', close: 181.18 }, + ]); + expect(result.fxRates).toEqual([{ date: '2024-01-05', usdCad: 1.3365 }]); + assertStatsReconcile(result.stats.eod); + assertStatsReconcile(result.stats.qm); + assertStatsReconcile(result.stats.fx); + }); + + test('uses raw close for eod, unadjustedclose for qm, and isolates CAD.FOREX exclusively to fxRates', async () => { + const fake = createFakeReader({ + eodPrices: [ + { eodSearchCode: 'NVDA.US', date: '2024-05-01', close: 830.41, adjustedClose: 83.04 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-05-01', close: 1.3742 }, + ], + qmPrices: [ + { + qmSearchCode: 'NVDA', + date: '2024-05-01', + close: 83.04, + adjustedclose: 83.04, + unadjustedclose: 830.41, + }, + ], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-05-01'], + sourceIdsBySource: { + // Explicitly request CAD.FOREX in eod to prove it is stripped from equity reads. + eod: ['NVDA.US', FX_USD_CAD_SOURCE_ID], + qm: ['NVDA'], + }, + }); + + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'NVDA.US', date: '2024-05-01', close: 830.41 }, + { source: 'qm', sourceId: 'NVDA', date: '2024-05-01', close: 830.41 }, + ]); + expect(result.closes.some(row => row.sourceId === FX_USD_CAD_SOURCE_ID)).toBe(false); + expect(result.fxRates).toEqual([{ date: '2024-05-01', usdCad: 1.3742 }]); + + // During the eod equity scan, the unfiltered fake reader also yielded CAD.FOREX, + // which must be skipped as unrequestedId rather than emitted into closes. + expect(result.stats.eod.docsRead).toBe(2); + expect(result.stats.eod.emitted).toBe(1); + expect(result.stats.eod.skipped.unrequestedId).toBe(1); + assertStatsReconcile(result.stats.eod); + assertStatsReconcile(result.stats.qm); + assertStatsReconcile(result.stats.fx); + }); + + test('normalizes Date and string dates to UTC YYYY-MM-DD and reconciles all skip reasons', async () => { + const fake = createFakeReader({ + eodPrices: [ + // Valid: exact string, Date UTC midnight, Date non-midnight UTC, ISO offset crossing into 2024-01-03 UTC + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }, + { eodSearchCode: 'AAPL.US', date: new Date('2024-01-03T00:00:00Z'), close: 184.25 }, + { eodSearchCode: 'AAPL.US', date: new Date('2024-01-04T21:30:00Z'), close: 181.91 }, + { eodSearchCode: 'MSFT.US', date: '2024-01-02T22:00:00-05:00', close: 370.6 }, + // missingId (null doc, non-string id, blank id) + null, + { eodSearchCode: 123, date: '2024-01-02', close: 10 }, + { eodSearchCode: ' ', date: '2024-01-02', close: 10 }, + // unrequestedId + { eodSearchCode: 'OTHER.US', date: '2024-01-02', close: 50 }, + // invalidDate (bad string, invalid Date, timezone-less timestamp) + { eodSearchCode: 'AAPL.US', date: '2023-02-29', close: 100 }, + { eodSearchCode: 'AAPL.US', date: new Date('invalid'), close: 100 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02T16:00:00', close: 100 }, + // unrequestedDate (valid date outside sampleDates) + { eodSearchCode: 'AAPL.US', date: '2024-01-05', close: 181.18 }, + { eodSearchCode: 'AAPL.US', date: new Date('2024-01-06T00:00:00Z'), close: 181.18 }, + // invalidClose (NaN, Infinity, -Infinity, 0, negative, string) + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.NaN }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.POSITIVE_INFINITY }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: Number.NEGATIVE_INFINITY }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: -12.5 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: '185.64' }, + ], + qmPrices: [], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-01-02', '2024-01-03', '2024-01-04'], + sourceIdsBySource: { eod: ['AAPL.US', 'MSFT.US'], qm: [] }, + includeFx: false, + }); + + expect(result.closes).toEqual([ + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 185.64 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-03', close: 184.25 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-04', close: 181.91 }, + { source: 'eod', sourceId: 'MSFT.US', date: '2024-01-03', close: 370.6 }, + ]); + + expect(result.stats.eod.docsRead).toBe(19); + expect(result.stats.eod.emitted).toBe(4); + expect(result.stats.eod.skipped).toEqual({ + missingId: 3, + unrequestedId: 1, + invalidDate: 3, + unrequestedDate: 2, + invalidClose: 6, + }); + assertStatsReconcile(result.stats.eod); + expect(result.stats.qm.findsRun).toBe(0); + expect(result.stats.fx.findsRun).toBe(0); + }); + + test('does not trim source IDs (T-49): surrounded-space IDs match only identical requested IDs', async () => { + const fake = createFakeReader({ + eodPrices: [ + { eodSearchCode: ' AAPL.US ', date: '2024-01-02', close: 185.64 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }, + ], + qmPrices: [ + { qmSearchCode: ' AAPL ', date: '2024-01-02', unadjustedclose: 185.64 }, + { qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.64 }, + ], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { + eod: [' AAPL.US '], + qm: ['AAPL'], + }, + includeFx: false, + }); + + expect(result.closes).toEqual([ + { source: 'eod', sourceId: ' AAPL.US ', date: '2024-01-02', close: 185.64 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-02', close: 185.64 }, + ]); + expect(result.stats.eod.skipped.unrequestedId).toBe(1); + expect(result.stats.qm.skipped.unrequestedId).toBe(1); + assertStatsReconcile(result.stats.eod); + assertStatsReconcile(result.stats.qm); + }); + + test('produces deterministic deep-equal output regardless of cursor or input order', async () => { + const eodDocs = [ + { eodSearchCode: 'MSFT.US', date: '2024-01-03', close: 371.0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 186.0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.0 }, + { eodSearchCode: 'AAPL.US', date: '2024-01-03', close: 184.0 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-03', close: 1.335 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.331 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.329 }, + ]; + const qmDocs = [ + { qmSearchCode: 'MSFT', date: '2024-01-02', unadjustedclose: 370.0 }, + { qmSearchCode: 'AAPL', date: '2024-01-03', unadjustedclose: 184.0 }, + { qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.0 }, + ]; + + const fakeA = createFakeReader({ eodPrices: eodDocs, qmPrices: qmDocs }); + const fakeB = createFakeReader({ + eodPrices: [...eodDocs].reverse(), + qmPrices: [...qmDocs].reverse(), + }); + + const resultA = await readSampleCloses(fakeA.reader, { + sampleDates: ['2024-01-03', '2024-01-02'], + sourceIdsBySource: { eod: ['MSFT.US', 'AAPL.US'], qm: ['MSFT', 'AAPL'] }, + }); + const resultB = await readSampleCloses(fakeB.reader, { + sampleDates: ['2024-01-02', '2024-01-03'], + sourceIdsBySource: { eod: ['AAPL.US', 'MSFT.US'], qm: ['AAPL', 'MSFT'] }, + }); + + expect(resultA).toEqual(resultB); + expect(resultA.closes).toEqual([ + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 185.0 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-02', close: 186.0 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2024-01-03', close: 184.0 }, + { source: 'eod', sourceId: 'MSFT.US', date: '2024-01-03', close: 371.0 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-02', close: 185.0 }, + { source: 'qm', sourceId: 'AAPL', date: '2024-01-03', close: 184.0 }, + { source: 'qm', sourceId: 'MSFT', date: '2024-01-02', close: 370.0 }, + ]); + expect(resultA.fxRates).toEqual([ + { date: '2024-01-02', usdCad: 1.329 }, + { date: '2024-01-02', usdCad: 1.331 }, + { date: '2024-01-03', usdCad: 1.335 }, + ]); + }); + + test('chunks large id sets by idChunkSize with date-first filters and skips empty sources', async () => { + const eodIds = ['A.US', 'B.US', 'C.US', 'D.US', 'E.US']; + const fake = createFakeReader( + { + eodPrices: eodIds.map((id, i) => ({ + eodSearchCode: id, + date: '2024-02-01', + close: 10 + i, + })), + qmPrices: [], + }, + { applyFilter: true } + ); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-02-01'], + sourceIdsBySource: { eod: eodIds, qm: [] }, + idChunkSize: 2, + includeFx: false, + }); + + expect(DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE).toBe(10_000); + expect(fake.calls).toHaveLength(3); + expect(result.stats.eod.findsRun).toBe(3); + expect(result.stats.qm.findsRun).toBe(0); + expect(result.stats.fx.findsRun).toBe(0); + expect(result.closes).toHaveLength(5); + + for (const call of fake.calls) { + expect(call.collectionName).toBe('eodPrices'); + expect(Object.keys(call.filter ?? {})).toEqual(['date', 'eodSearchCode']); + expect(call.filter?.date).toEqual({ $in: ['2024-02-01'] }); + } + expect(fake.calls[0]?.filter?.eodSearchCode).toEqual({ $in: ['A.US', 'B.US'] }); + expect(fake.calls[1]?.filter?.eodSearchCode).toEqual({ $in: ['C.US', 'D.US'] }); + expect(fake.calls[2]?.filter?.eodSearchCode).toEqual({ $in: ['E.US'] }); + }); + + test('rejects non-read-only reader and invalid options before issuing any find', async () => { + const writableFake = createFakeReader({}, { readOnly: false }); + await expect( + readSampleCloses(writableFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + }) + ).rejects.toThrow(/isReadOnly/); + expect(writableFake.calls).toHaveLength(0); + + const validFake = createFakeReader({}); + const badDateInputs: string[][] = [ + [], + ['2024-1-2'], + ['2023-02-29'], + [' 2024-01-02 '], + ['2024-01-02T00:00:00Z'], + makeSampleDates(MAX_SAMPLE_DATES + 1), + ]; + + for (const badDates of badDateInputs) { + await expect( + readSampleCloses(validFake.reader, { + sampleDates: badDates, + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + }) + ).rejects.toThrow(RangeError); + } + + await expect( + readSampleCloses(validFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + batchSize: 0, + }) + ).rejects.toThrow(RangeError); + + await expect( + readSampleCloses(validFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + idChunkSize: -5, + }) + ).rejects.toThrow(RangeError); + + expect(validFake.calls).toHaveLength(0); + }); + + test('rejects buffered array results with TypeError and closes cursors on errors while preserving collection name', async () => { + const bufferedReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => [] as unknown as AsyncIterable>, + }; + + await expect( + readSampleCloses(bufferedReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + }) + ).rejects.toThrow(TypeError); + + // Cursor error on qmPrices (call index 1) with close() also failing: primary error + collection name preserved. + const failingFake = createFakeReader( + { + eodPrices: [{ eodSearchCode: 'AAPL.US', date: '2024-01-02', close: 185.64 }], + qmPrices: [ + { qmSearchCode: 'AAPL', date: '2024-01-02', unadjustedclose: 185.64 }, + { qmSearchCode: 'MSFT', date: '2024-01-02', unadjustedclose: 370.0 }, + ], + }, + { + failOnCallIndex: 1, + failAfterDocs: 1, + failMessage: 'socket reset', + failCloseOnCallIndex: 1, + } + ); + + await expect( + readSampleCloses(failingFake.reader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: ['AAPL', 'MSFT'] }, + }) + ).rejects.toThrow(/qmPrices.*socket reset/); + + // Both call 0 (eodPrices) and call 1 (qmPrices) must have had close() invoked. + expect(failingFake.closedCount()).toBe(2); + }); + + test('wraps TypeError thrown during iteration or close with collection name and original cause while closing cursor', async () => { + const iterationCause = new TypeError('cannot decode malformed BSON field'); + let iterationCloseCalls = 0; + + const iterationTypeErrorReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find = Record>( + collectionName: string + ): ReadOnlySourceSymbolCursor { + if (collectionName === 'qmPrices') { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + yield { + qmSearchCode: 'AAPL', + date: '2024-01-02', + unadjustedclose: 185.64, + } as unknown as T; + throw iterationCause; + }, + async close(): Promise { + iterationCloseCalls += 1; + }, + }; + } + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty + }, + async close(): Promise { + // noop + }, + }; + }, + }; + + let caughtIterationError: unknown; + try { + await readSampleCloses(iterationTypeErrorReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: [], qm: ['AAPL'] }, + includeFx: false, + }); + } catch (error) { + caughtIterationError = error; + } + + expect(caughtIterationError).toBeInstanceOf(Error); + expect((caughtIterationError as Error).message).toContain('qmPrices'); + expect((caughtIterationError as Error).message).toContain('cannot decode malformed BSON field'); + expect((caughtIterationError as Error).cause).toBe(iterationCause); + expect(iterationCloseCalls).toBe(1); + + const closeCause = new TypeError('cursor close internal TypeError'); + const closeTypeErrorReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find = Record>(): ReadOnlySourceSymbolCursor { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty + }, + async close(): Promise { + throw closeCause; + }, + }; + }, + }; + + let caughtCloseError: unknown; + try { + await readSampleCloses(closeTypeErrorReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + includeFx: false, + }); + } catch (error) { + caughtCloseError = error; + } + + expect(caughtCloseError).toBeInstanceOf(Error); + expect((caughtCloseError as Error).message).toContain('eodPrices'); + expect((caughtCloseError as Error).message).toContain('cursor close internal TypeError'); + expect((caughtCloseError as Error).cause).toBe(closeCause); + }); + + test('rejects an invalid closable handle with TypeError and still releases it via close()', async () => { + let invalidHandleClosed = 0; + const invalidClosableReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: () => + ({ + async close(): Promise { + invalidHandleClosed += 1; + }, + }) as unknown as AsyncIterable>, + }; + + await expect( + readSampleCloses(invalidClosableReader, { + sampleDates: ['2024-01-02'], + sourceIdsBySource: { eod: ['AAPL.US'], qm: [] }, + includeFx: false, + }) + ).rejects.toThrow(TypeError); + + expect(invalidHandleClosed).toBe(1); + }); + + test('integrates end to end with crossCheckPrices for USD/USD and CAD/USD pairs (confirmed and conflict)', async () => { + const dates = [ + '2024-01-02', + '2024-02-01', + '2024-03-01', + '2024-04-01', + '2024-05-01', + '2024-06-03', + ]; + const usdPrices = [100, 108, 102, 115, 121, 118]; + const fxRatesByIdx = [1.33, 1.35, 1.36, 1.37, 1.38, 1.36]; + + const eodDocs: Record[] = []; + const qmDocs: Record[] = []; + + for (let i = 0; i < dates.length; i++) { + const date = dates[i]!; + const p = usdPrices[i]!; + const fx = fxRatesByIdx[i]!; + + // FX series + eodDocs.push({ eodSearchCode: FX_USD_CAD_SOURCE_ID, date, close: fx }); + + // USD/USD consistent pair (AAPL.US vs AAPL) + eodDocs.push({ eodSearchCode: 'AAPL.US', date, close: p }); + qmDocs.push({ qmSearchCode: 'AAPL', date, unadjustedclose: p * 1.002 }); + + // CAD/USD consistent cross-listed pair (SHOP.TO in CAD vs SHOP in USD) + eodDocs.push({ eodSearchCode: 'SHOP.TO', date, close: p * fx }); + qmDocs.push({ qmSearchCode: 'SHOP', date, unadjustedclose: p }); + + // Mismatched USD/USD pair (ratio off by 15%) + eodDocs.push({ eodSearchCode: 'BAD.US', date, close: p * 1.15 }); + qmDocs.push({ qmSearchCode: 'BAD', date, unadjustedclose: p }); + + // Low-correlation USD/USD pair (same scale near 1.0 ratio, opposite daily moves) + const inverted = usdPrices[dates.length - 1 - i]!; + eodDocs.push({ eodSearchCode: 'UNCORR.US', date, close: p }); + qmDocs.push({ qmSearchCode: 'UNCORR', date, unadjustedclose: inverted }); + } + + const fake = createFakeReader({ eodPrices: eodDocs, qmPrices: qmDocs }, { applyFilter: true }); + const sample = await readSampleCloses(fake.reader, { + sampleDates: dates, + sourceIdsBySource: { + eod: ['AAPL.US', 'SHOP.TO', 'BAD.US', 'UNCORR.US'], + qm: ['AAPL', 'SHOP', 'BAD', 'UNCORR'], + }, + }); + + const check = crossCheckPrices({ + pairs: [ + { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'AAPL', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD' }, + right: { source: 'qm', sourceId: 'SHOP', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'BAD.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'BAD', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'UNCORR.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'UNCORR', currency: 'USD' }, + }, + ], + closes: sample.closes, + usdCadByDate: sample.fxRates, + }); + + const byLeftId = new Map(check.results.map(r => [r.left.sourceId, r])); + expect(byLeftId.get('AAPL.US')?.verdict).toBe('confirmed'); + expect(byLeftId.get('SHOP.TO')?.verdict).toBe('confirmed'); + expect(byLeftId.get('BAD.US')?.verdict).toBe('ratio_mismatch'); + expect(byLeftId.get('UNCORR.US')?.verdict).toBe('low_correlation'); + expect(check.conflicts).toHaveLength(2); + expect(check.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([ + ['BAD.US', 'price_ratio_mismatch'], + ['UNCORR.US', 'price_low_correlation'], + ]); + }); + + test('reconciles skip counts on FX scan for malformed, unrequested, and invalid FX docs', async () => { + const fake = createFakeReader({ + eodPrices: [ + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: 1.335 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: new Date('2024-01-03T12:00:00Z'), close: 1.34 }, + null, + { eodSearchCode: '', date: '2024-01-02', close: 1.33 }, + { eodSearchCode: 'EUR.FOREX', date: '2024-01-02', close: 1.09 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: 'bad-date', close: 1.33 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-09', close: 1.33 }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: '2024-01-02', close: -1.33 }, + ], + qmPrices: [], + }); + + const result = await readSampleCloses(fake.reader, { + sampleDates: ['2024-01-02', '2024-01-03'], + sourceIdsBySource: { eod: [], qm: [] }, + }); + + expect(result.fxRates).toEqual([ + { date: '2024-01-02', usdCad: 1.335 }, + { date: '2024-01-03', usdCad: 1.34 }, + ]); + expect(result.stats.eod.findsRun).toBe(0); + expect(result.stats.qm.findsRun).toBe(0); + expect(result.stats.fx.findsRun).toBe(1); + expect(result.stats.fx.docsRead).toBe(8); + expect(result.stats.fx.emitted).toBe(2); + expect(result.stats.fx.skipped).toEqual({ + missingId: 2, + unrequestedId: 1, + invalidDate: 1, + unrequestedDate: 1, + invalidClose: 1, + }); + assertStatsReconcile(result.stats.fx); + }); +}); diff --git a/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts b/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts new file mode 100644 index 00000000..a035b01f --- /dev/null +++ b/apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts @@ -0,0 +1,364 @@ +import { describe, expect, test } from 'bun:test'; +import { BSON } from 'mongodb'; +import { + createReadOnlyMongoSourceSymbolReader, + MAX_EXAMPLES_CAP, + parseProbeSourceFieldShapesArgs, + readFieldShapes, + renderFieldShapesMarkdown, + runSourceFieldShapesProbe, + summarizeFieldShapes, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +// QA coverage for T-108 beyond the programmer's suite: real BSON wire decoding, +// option pass-through via the production read-only adapter, fail-fast safety, +// and CLI/runner failure paths. No MongoDB connection is opened anywhere here. + +const OBJECT_ID_HEX = '507f1f77bcf86cd799439011'; + +function serializeRealBsonDoc(): Uint8Array { + return BSON.serialize({ + _id: new BSON.ObjectId(OBJECT_ID_HEX), + i32: new BSON.Int32(7), + dbl: new BSON.Double(1.0), + lng: BSON.Long.fromString('9007199254740993'), + dec: BSON.Decimal128.fromString('12.34'), + flag: true, + text: '2025-01-02', + when: new Date('2025-01-02T00:00:00.000Z'), + nothing: null, + list: [1, 2], + nested: { px: new BSON.Double(2.5), qty: new BSON.Int32(3) }, + bin: new BSON.Binary(new Uint8Array([1, 2, 3])), + ts: new BSON.Timestamp({ t: 1, i: 1 }), + min: new BSON.MinKey(), + }); +} + +function nonZeroTypes(counts: Record): Record { + return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0)); +} + +function asyncCursor( + docs: readonly T[], + onClose?: () => void +): { [Symbol.asyncIterator](): AsyncIterator; close(): Promise } { + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) { + yield doc; + } + }, + async close() { + onClose?.(); + }, + }; +} + +describe('summarizeFieldShapes with real BSON wire documents', () => { + test('promoteValues:false decoding keeps int/double/long/objectId distinct and maps other BSON types to other', () => { + const doc = BSON.deserialize(serializeRealBsonDoc(), { + promoteValues: false, + promoteLongs: false, + }); + + const summary = summarizeFieldShapes([doc]); + const types = Object.fromEntries(summary.fields.map(f => [f.field, nonZeroTypes(f.typeCounts)])); + + expect(types).toEqual({ + _id: { objectId: 1 }, + bin: { other: 1 }, + dbl: { double: 1 }, + dec: { other: 1 }, + flag: { bool: 1 }, + i32: { int: 1 }, + list: { array: 1 }, + lng: { int: 1 }, + min: { other: 1 }, + nested: { object: 1 }, + 'nested.px': { double: 1 }, + 'nested.qty': { int: 1 }, + nothing: { null: 1 }, + text: { string: 1 }, + ts: { other: 1 }, + when: { date: 1 }, + }); + + const examples = Object.fromEntries(summary.fields.map(f => [f.field, f.examples])); + expect(examples._id).toEqual([]); + expect(examples.dbl).toEqual(['1']); + expect(examples.lng).toEqual(['9007199254740993']); + expect(examples.dec).toEqual(['12.34']); + expect(examples.when).toEqual(['2025-01-02T00:00:00.000Z']); + expect(examples.bin).toEqual([]); + }); + + test('default driver promotion collapses Double(1.0) into int, which is why the probe disables promotion', () => { + const promoted = BSON.deserialize(serializeRealBsonDoc()); + const summary = summarizeFieldShapes([promoted]); + const dbl = summary.fields.find(f => f.field === 'dbl')!; + expect(nonZeroTypes(dbl.typeCounts)).toEqual({ int: 1 }); + }); +}); + +describe('readFieldShapes through the production read-only Mongo adapter', () => { + test('forwards limit/promoteValues/promoteLongs verbatim to collection.find and classifies decoded BSON', async () => { + const findCalls: Array<{ name: string; filter: unknown; options: unknown }> = []; + const closed: string[] = []; + const wireDoc = BSON.deserialize(serializeRealBsonDoc(), { + promoteValues: false, + promoteLongs: false, + }); + + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find(filter?: Record, options?: SourceSymbolFindOptions) { + findCalls.push({ name, filter, options }); + return asyncCursor(name === 'qmDividends' ? [wireDoc] : [], () => closed.push(name)); + }, + }; + }, + }; + + const reader = createReadOnlyMongoSourceSymbolReader(client); + const result = await readFieldShapes(reader, { + collections: ['qmDividends', 'qmSplits'], + limit: 25, + }); + + expect(findCalls).toEqual([ + { + name: 'qmDividends', + filter: {}, + options: { limit: 25, promoteValues: false, promoteLongs: false }, + }, + { + name: 'qmSplits', + filter: {}, + options: { limit: 25, promoteValues: false, promoteLongs: false }, + }, + ]); + expect(closed).toEqual(['qmDividends', 'qmSplits']); + expect(result.totalDocsSampled).toBe(1); + const dbl = result.collections[0]!.fields.find(f => f.field === 'dbl')!; + expect(dbl.typeCounts.double).toBe(1); + }); + + test('re-checks read-only before every collection and stops if the reader stops being read-only', async () => { + let readOnly = true; + const findCalls: string[] = []; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => readOnly, + find>(name: string): ReadOnlySourceSymbolCursor { + findCalls.push(name); + readOnly = false; // simulate a reader that flips after its first query + return asyncCursor([]) as unknown as ReadOnlySourceSymbolCursor; + }, + }; + + await expect( + readFieldShapes(reader, { collections: ['ceoShorts', 'qmSplits'] }) + ).rejects.toThrow(/read-only/i); + expect(findCalls).toEqual(['ceoShorts']); + }); + + test('fails fast: an error on one collection prevents queries on later collections', async () => { + const findCalls: string[] = []; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find>(name: string): ReadOnlySourceSymbolCursor { + findCalls.push(name); + if (name === 'eodPrices') { + throw new Error('not authorized on stock'); + } + return asyncCursor([]) as unknown as ReadOnlySourceSymbolCursor; + }, + }; + + let caught: unknown; + try { + await readFieldShapes(reader, { collections: ['qmSplits', 'eodPrices', 'ceoShorts'] }); + } catch (error) { + caught = error; + } + // Collections are ASCII-sorted: ceoShorts, eodPrices, qmSplits. + expect(findCalls).toEqual(['ceoShorts', 'eodPrices']); + expect((caught as Error).message).toContain('eodPrices'); + expect((caught as Error).message).toContain('not authorized on stock'); + expect(((caught as Error).cause as Error).message).toBe('not authorized on stock'); + }); + + test('rejects non-integer limit and invalid batchSize before any query', async () => { + let findCalls = 0; + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find>(): ReadOnlySourceSymbolCursor { + findCalls += 1; + return asyncCursor([]) as unknown as ReadOnlySourceSymbolCursor; + }, + }; + + await expect(readFieldShapes(reader, { limit: 1.5 })).rejects.toThrow(RangeError); + await expect(readFieldShapes(reader, { limit: Number.NaN })).rejects.toThrow(RangeError); + await expect(readFieldShapes(reader, { batchSize: 0 })).rejects.toThrow(RangeError); + await expect(readFieldShapes(reader, { collections: [] })).rejects.toThrow(RangeError); + expect(findCalls).toBe(0); + }); +}); + +describe('summarizeFieldShapes edge cases', () => { + test('non-object documents count toward docCount and keep presence invariants', () => { + const docs = [{ a: 1 }, null, 'oops', { a: 'x' }] as unknown as Record[]; + const summary = summarizeFieldShapes(docs); + expect(summary.docCount).toBe(4); + const a = summary.fields.find(f => f.field === 'a')!; + expect(a.presentCount).toBe(2); + expect(a.missingCount).toBe(2); + }); + + test('undefined values are treated as missing, not as a present type', () => { + const summary = summarizeFieldShapes([{ a: undefined }, { a: 1 }]); + const a = summary.fields.find(f => f.field === 'a')!; + expect(a.presentCount).toBe(1); + expect(a.missingCount).toBe(1); + }); + + test('rejects near-miss dates and times as ymd/isoDatetime', () => { + const values = [ + '2024-13-01', // month 13 + '2024-04-31', // April has 30 days + '2025-01-01T24:00:00Z', // hour 24 + '2025-01-01T10:60:00Z', // minute 60 + '2025-01-01 10:00:00', // space separator + '20250101', // compact date is numeric, not ymd + ]; + const summary = summarizeFieldShapes(values.map(s => ({ s }))); + const s = summary.fields.find(f => f.field === 's')!; + expect(s.stringStats!.patterns).toEqual({ + ymd: 0, + isoDatetime: 0, + numeric: 1, + emptyOrWhitespace: 0, + other: 5, + }); + }); + + test('examples are distinct, strip control characters, and honour maxExamples 0 and the cap', () => { + const docs = [{ s: 'dup' }, { s: 'dup' }, { s: '\u0000\u001bbell\u0007' }]; + + expect(summarizeFieldShapes(docs).fields[0]!.examples).toEqual(['bell', 'dup']); + expect(summarizeFieldShapes(docs, { maxExamples: 0 }).fields[0]!.examples).toEqual([]); + + const many = Array.from({ length: 50 }, (_, i) => ({ s: `v${String(i).padStart(2, '0')}` })); + const capped = summarizeFieldShapes(many, { maxExamples: MAX_EXAMPLES_CAP }).fields[0]!; + expect(capped.examples.length).toBe(MAX_EXAMPLES_CAP); + expect(capped.examples[0]).toBe('v00'); + }); +}); + +describe('renderFieldShapesMarkdown privacy and header', () => { + test('never renders _id values and states the bounded sample in the header', async () => { + const reader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find>(): ReadOnlySourceSymbolCursor { + return asyncCursor([ + { _id: new BSON.ObjectId(OBJECT_ID_HEX), symbol: 'ABC' }, + { _id: { ticker: 'SECRET-COMPOSITE' }, symbol: 'DEF' }, + ] as unknown as T[]) as unknown as ReadOnlySourceSymbolCursor; + }, + }; + + const result = await readFieldShapes(reader, { collections: ['ceoShorts'], limit: 7 }); + const markdown = renderFieldShapesMarkdown(result); + + expect(markdown).not.toContain(OBJECT_ID_HEX); + expect(markdown).not.toContain('SECRET-COMPOSITE'); + expect(markdown).toContain('bounded sample, not a full scan'); + expect(markdown).toContain('**Sample limit per collection:** 7'); + expect(markdown).toContain('**Total documents sampled:** 2'); + expect(markdown).toContain('| `_id.ticker` | 50.0% (1/2) |'); + expect(markdown).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); // no wall-clock stamp + }); +}); + +describe('probe CLI parsing and runner failure paths', () => { + test('rejects a flag in place of a value and empty inline values', () => { + expect(() => parseProbeSourceFieldShapesArgs(['--out', '--limit', '5'])).toThrow(/--out/); + expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit'])).toThrow(/--limit/); + expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections='])).toThrow( + /--collections/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections', ' , '])).toThrow( + /--collections/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1e3'])).toThrow(/--limit/); + }); + + test('merges repeated --collections, accepts boundary limits, and lets --help win', () => { + expect( + parseProbeSourceFieldShapesArgs([ + '--out=x.md', + '--collections=qmSplits', + '--collections', + 'ceoShorts,qmSplits', + '--limit=10000', + ]) + ).toEqual({ help: false, outPath: 'x.md', limit: 10_000, collections: ['ceoShorts', 'qmSplits'] }); + expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1'])).toMatchObject({ limit: 1 }); + expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--help'])).toEqual({ help: true }); + }); + + test('closes Mongo and surfaces the write error when the report cannot be written', async () => { + let closeCalls = 0; + const stdout: string[] = []; + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection() { + return { find: () => asyncCursor([{ a: 1 }]) }; + }, + }; + + await expect( + runSourceFieldShapesProbe( + { + mongoCollectionClient: client, + closeMongo: () => { + closeCalls += 1; + }, + writeFile: () => { + throw new Error('EACCES: permission denied'); + }, + writeStdout: text => stdout.push(text), + }, + { outPath: './tmp/out.md', collections: ['qmSplits'] } + ) + ).rejects.toThrow('EACCES'); + expect(closeCalls).toBe(1); + expect(stdout).toEqual([]); + }); + + test('blank outPath is rejected before any collection is opened', async () => { + let getCollectionCalls = 0; + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection() { + getCollectionCalls += 1; + return { find: () => asyncCursor([]) }; + }, + }; + + await expect( + runSourceFieldShapesProbe( + { mongoCollectionClient: client, writeFile: () => {}, writeStdout: () => {} }, + { outPath: ' ' } + ) + ).rejects.toThrow(/outPath/); + expect(getCollectionCalls).toBe(0); + }); +}); diff --git a/apps/stock/data-pipeline/test/source-field-shapes.test.ts b/apps/stock/data-pipeline/test/source-field-shapes.test.ts new file mode 100644 index 00000000..47e150e9 --- /dev/null +++ b/apps/stock/data-pipeline/test/source-field-shapes.test.ts @@ -0,0 +1,812 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { ParserOptions } from 'prettier'; +import * as markdownPlugin from 'prettier/plugins/markdown'; +import { + DEFAULT_FIELD_SHAPE_LIMIT, + DEFAULT_MAX_EXAMPLE_LENGTH, + DEFAULT_MAX_EXAMPLES, + FIELD_SHAPE_PROBE_COLLECTIONS, + FIELD_VALUE_TYPES, + MAX_EXAMPLE_LENGTH_CAP, + MAX_EXAMPLES_CAP, + MAX_FIELD_SHAPE_LIMIT, + parseProbeSourceFieldShapesArgs, + readFieldShapes, + renderFieldShapesMarkdown, + runSourceFieldShapesProbe, + STRING_PATTERN_CLASSES, + summarizeFieldShapes, + UnknownProbeCollectionError, + type FieldShapeSummary, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +interface RecordedFindCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +interface FakeBsonWrapper { + _bsontype: string; + valueOf?: () => unknown; + toString: () => string; +} + +function fakeInt32(value: number): FakeBsonWrapper { + return { + _bsontype: 'Int32', + valueOf: () => value, + toString: () => String(value), + }; +} + +function fakeDouble(value: number): FakeBsonWrapper { + return { + _bsontype: 'Double', + valueOf: () => value, + toString: () => String(value), + }; +} + +function fakeLong(value: string): FakeBsonWrapper { + return { + _bsontype: 'Long', + toString: () => value, + }; +} + +function fakeObjectId(hex: string): FakeBsonWrapper { + return { + _bsontype: 'ObjectId', + toString: () => hex, + }; +} + +function fakeDecimal128(value: string): FakeBsonWrapper { + return { + _bsontype: 'Decimal128', + toString: () => value, + }; +} + +function sumTypeCounts(summary: FieldShapeSummary): number { + let total = 0; + for (const typeName of FIELD_VALUE_TYPES) { + total += summary.typeCounts[typeName]; + } + return total; +} + +function sumPatternCounts(summary: FieldShapeSummary): number { + if (summary.stringStats === null) { + return 0; + } + let total = 0; + for (const pattern of STRING_PATTERN_CLASSES) { + total += summary.stringStats.patterns[pattern]; + } + return total; +} + +function createFakeReader( + docsByCollection: Record[]>, + opts?: { + readOnly?: boolean; + failFindOnCollection?: string; + failIterOnCollection?: string; + failIterAtIndex?: number; + failCloseOnCollection?: string; + returnBufferedArrayOnCollection?: string; + ignoreLimit?: boolean; + } +): { + reader: ReadOnlySourceSymbolReader; + calls: RecordedFindCall[]; + closedCollections: string[]; + pullsByCollection: Record; +} { + const calls: RecordedFindCall[] = []; + const closedCollections: string[] = []; + const pullsByCollection: Record = {}; + const readOnly = opts?.readOnly ?? true; + + const reader: ReadOnlySourceSymbolReader = { + isReadOnly(): boolean { + return readOnly; + }, + find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + calls.push({ collectionName, filter, options }); + + if (opts?.failFindOnCollection === collectionName) { + throw new Error('simulated find failure'); + } + if (opts?.returnBufferedArrayOnCollection === collectionName) { + return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor; + } + + const sourceDocs = docsByCollection[collectionName] ?? []; + const maxToYield = + opts?.ignoreLimit === true || options?.limit === undefined + ? sourceDocs.length + : Math.min(sourceDocs.length, options.limit); + const failAt = opts?.failIterAtIndex ?? 1; + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < maxToYield; i++) { + pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1; + if (opts?.failIterOnCollection === collectionName && i === failAt) { + throw new Error('simulated cursor iteration failure'); + } + yield sourceDocs[i] as T; + } + }, + async close(): Promise { + closedCollections.push(collectionName); + if (opts?.failCloseOnCollection === collectionName) { + throw new Error('simulated cursor close failure'); + } + }, + }; + }, + }; + + return { reader, calls, closedCollections, pullsByCollection }; +} + +describe('source-field-shapes static purity', () => { + test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => { + const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts'); + const source = readFileSync(filePath, 'utf8'); + const runtimeImportLines = source + .split('\n') + .filter(line => /^\s*import\s+(?!type\b)/.test(line)); + + for (const line of runtimeImportLines) { + expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i); + } + expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/); + }); +}); + +describe('summarizeFieldShapes', () => { + test('classifies mixed JS and BSON value types on one field and reconciles counts', () => { + const docs: Record[] = [ + { mixed: 'hello' }, + { mixed: 42 }, + { mixed: 3.14 }, + { mixed: fakeInt32(7) }, + { mixed: fakeLong('9007199254740993') }, + { mixed: fakeDouble(1.0) }, + { mixed: true }, + { mixed: new Date('2025-01-15T12:00:00.000Z') }, + { mixed: null }, + { mixed: fakeObjectId('507f1f77bcf86cd799439011') }, + { mixed: [1, 2, 3] }, + { mixed: { nested: 'a' } }, + { mixed: fakeDecimal128('12.34') }, + { mixed: new Uint8Array([1, 2]) }, + {}, // missing + ]; + + const summary = summarizeFieldShapes(docs); + expect(summary.docCount).toBe(docs.length); + + const mixed = summary.fields.find(f => f.field === 'mixed'); + expect(mixed).toBeDefined(); + expect(mixed!.presentCount).toBe(14); + expect(mixed!.missingCount).toBe(1); + expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount); + expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount); + + expect(mixed!.typeCounts).toEqual({ + string: 1, + int: 3, // 42, Int32(7), Long(...) + double: 2, // 3.14, Double(1.0) + bool: 1, + date: 1, + null: 1, + objectId: 1, + array: 1, + object: 1, + other: 2, // Decimal128, Uint8Array + }); + }); + + test('tracks one level of nested parent.child keys and stops at depth 1', () => { + const docs: Record[] = [ + { + meta: { + exchange: 'TSX', + deep: { level2: 'ignored' }, + recordedAt: new Date('2025-02-01T00:00:00Z'), + }, + arr: [{ insideArray: 1 }], + bsonObj: fakeObjectId('507f1f77bcf86cd799439012'), + }, + { + meta: { + exchange: 'NYSE', + }, + }, + ]; + + const summary = summarizeFieldShapes(docs); + const fieldNames = summary.fields.map(f => f.field); + + expect(fieldNames).toEqual([ + 'arr', + 'bsonObj', + 'meta', + 'meta.deep', + 'meta.exchange', + 'meta.recordedAt', + ]); + expect(fieldNames).not.toContain('meta.deep.level2'); + expect(fieldNames).not.toContain('bsonObj._bsontype'); + + const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!; + expect(metaExchange.presentCount).toBe(2); + expect(metaExchange.missingCount).toBe(0); + expect(metaExchange.typeCounts.string).toBe(2); + + const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!; + expect(metaDeep.presentCount).toBe(1); + expect(metaDeep.missingCount).toBe(1); + expect(metaDeep.typeCounts.object).toBe(1); + }); + + test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => { + const docs: Record[] = [ + { + 'meta.exchange': 'LITERAL_EXCHANGE', + meta: { + exchange: 42, + }, + }, + ]; + + const summary = summarizeFieldShapes(docs); + expect(summary.docCount).toBe(1); + + const literalField = summary.fields.find(f => f.field === 'meta\\.exchange'); + const nestedField = summary.fields.find(f => f.field === 'meta.exchange'); + expect(literalField).toBeDefined(); + expect(nestedField).toBeDefined(); + + expect(literalField!.presentCount).toBe(1); + expect(literalField!.missingCount).toBe(0); + expect(literalField!.typeCounts.string).toBe(1); + expect(literalField!.typeCounts.int).toBe(0); + expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']); + + expect(nestedField!.presentCount).toBe(1); + expect(nestedField!.missingCount).toBe(0); + expect(nestedField!.typeCounts.int).toBe(1); + expect(nestedField!.typeCounts.string).toBe(0); + expect(nestedField!.examples).toEqual(['42']); + }); + + test('classifies all five string pattern classes and tracks min/max string length', () => { + const docs: Record[] = [ + { s: '2024-02-29' }, // valid leap-year ymd (len 10) + { s: '2023-02-29' }, // invalid calendar date -> other (len 10) + { s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20) + { s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29) + { s: '-123.45' }, // numeric (len 7) + { s: '1.5e-4' }, // numeric (len 6) + { s: '' }, // emptyOrWhitespace (len 0) + { s: ' \t ' }, // emptyOrWhitespace (len 5) + { s: 'AAPL.US' }, // other (len 7) + ]; + + const summary = summarizeFieldShapes(docs); + const field = summary.fields.find(f => f.field === 's')!; + + expect(field.typeCounts.string).toBe(9); + expect(field.stringStats).toEqual({ + minLength: 0, + maxLength: 29, + patterns: { + ymd: 1, + isoDatetime: 2, + numeric: 2, + emptyOrWhitespace: 2, + other: 2, + }, + }); + expect(sumPatternCounts(field)).toBe(field.typeCounts.string); + }); + + test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => { + const docs: Record[] = [ + { + _id: fakeObjectId('507f1f77bcf86cd799439011'), + symbol: 'ZZZZ', + note: 'line1\nline2\twith a very long description that must be truncated', + }, + { + _id: { key: 'secret-composite-id' }, + symbol: 'AAAA', + note: 'short', + }, + { + _id: 'string-id-should-never-appear', + symbol: 'MMMM', + }, + { + symbol: 'BBBB', + }, + ]; + + const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 }); + const idField = summary.fields.find(f => f.field === '_id')!; + const idChildField = summary.fields.find(f => f.field === '_id.key')!; + const symbolField = summary.fields.find(f => f.field === 'symbol')!; + const noteField = summary.fields.find(f => f.field === 'note')!; + + expect(idField.examples).toEqual([]); + expect(idChildField.examples).toEqual([]); + expect(symbolField.examples).toEqual(['AAAA', 'BBBB']); + expect(noteField.examples.length).toBe(2); + expect(noteField.examples[0]).toBe('line1 line2 w...'); + expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16); + expect(noteField.examples[1]).toBe('short'); + + expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError); + expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow( + RangeError + ); + expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError); + expect(() => + summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 }) + ).toThrow(RangeError); + }); + + test('produces deep-equal output for shuffled input order and handles empty iterable', () => { + expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] }); + + const original: Record[] = [ + { _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } }, + { _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } }, + { _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } }, + { _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } }, + ]; + const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!]; + + const a = summarizeFieldShapes(original, { maxExamples: 2 }); + const b = summarizeFieldShapes(shuffled, { maxExamples: 2 }); + + expect(b).toEqual(a); + expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']); + }); +}); + +describe('readFieldShapes', () => { + test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => { + const docsByCollection: Record[]> = { + qmDividends: [ + { _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' }, + { _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' }, + { _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' }, + ], + ceoShorts: [ + { _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) }, + ], + }; + + const { reader, calls, closedCollections, pullsByCollection } = createFakeReader( + docsByCollection, + { + ignoreLimit: true, + failIterOnCollection: 'qmDividends', + failIterAtIndex: 2, + } + ); + + const result = await readFieldShapes(reader, { + collections: ['qmDividends', 'ceoShorts', 'qmDividends'], + limit: 2, + batchSize: 500, + }); + + expect(calls.length).toBe(2); + expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']); + for (const call of calls) { + expect(call.filter).toEqual({}); + expect(call.options).toEqual({ + limit: 2, + promoteValues: false, + promoteLongs: false, + batchSize: 500, + }); + } + expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']); + // Breaks immediately after recording the limit-th doc without pulling a 3rd item + expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 }); + + // Defensively capped at limit=2 even though fake reader ignored limit + expect(result.limit).toBe(2); + expect(result.totalDocsSampled).toBe(3); + const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!; + expect(qmDiv.docCount).toBe(2); + const amountField = qmDiv.fields.find(f => f.field === 'amount')!; + expect(amountField.typeCounts.double).toBe(2); + }); + + test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { + 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); + for (const call of calls) { + expect(call.options).toEqual({ + limit: DEFAULT_FIELD_SHAPE_LIMIT, + promoteValues: false, + promoteLongs: false, + }); + } + }); + + test('rejects invalid limit, unknown collection, 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); + + const badLimitHigh = createFakeReader({}); + await expect( + readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 }) + ).rejects.toThrow(RangeError); + expect(badLimitHigh.calls.length).toBe(0); + + const badLimitZero = createFakeReader({}); + 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; + } + 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 () => { + const buffered = createFakeReader( + { eodPrices: [{ date: '2025-01-02' }] }, + { returnBufferedArrayOnCollection: 'eodPrices' } + ); + await expect( + readFieldShapes(buffered.reader, { collections: ['eodPrices'] }) + ).rejects.toThrow(TypeError); + + const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' }); + let caughtFind: unknown; + try { + await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] }); + } catch (err) { + caughtFind = err; + } + expect(caughtFind).toBeInstanceOf(Error); + expect((caughtFind as Error).message).toContain('qmFilings'); + expect((caughtFind as Error).cause).toBeInstanceOf(Error); + + const iterErr = createFakeReader( + { qmEarnings: [{ a: 1 }, { a: 2 }] }, + { failIterOnCollection: 'qmEarnings' } + ); + let caughtIter: unknown; + try { + await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] }); + } catch (err) { + caughtIter = err; + } + expect(caughtIter).toBeInstanceOf(Error); + expect((caughtIter as Error).message).toContain('qmEarnings'); + expect((caughtIter as Error).cause).toBeInstanceOf(Error); + expect(iterErr.closedCollections).toEqual(['qmEarnings']); + + const closeErr = createFakeReader( + { teMarketData: [{ country: 'US' }] }, + { failCloseOnCollection: 'teMarketData' } + ); + let caughtClose: unknown; + try { + await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] }); + } catch (err) { + caughtClose = err; + } + expect(caughtClose).toBeInstanceOf(Error); + expect((caughtClose as Error).message).toContain('teMarketData'); + expect((caughtClose as Error).cause).toBeInstanceOf(Error); + }); +}); + +interface MdastNode { + type: string; + value?: string; + children?: MdastNode[]; +} + +function decodeHtmlEntities(text: string): string { + return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => { + if (code !== undefined) { + return String.fromCharCode(Number(code)); + } + switch (entity) { + case 'amp': + return '&'; + case 'lt': + return '<'; + case 'gt': + return '>'; + default: + return `&${entity};`; + } + }); +} + +function parseGfmTables(markdown: string): MdastNode[][] { + const ast = markdownPlugin.parsers.markdown.parse( + markdown, + {} as ParserOptions + ) as unknown as MdastNode; + const rows: MdastNode[][] = []; + for (const node of ast.children ?? []) { + if (node.type !== 'table') { + continue; + } + const tableRows = node.children ?? []; + for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) { + rows.push(tableRows[rowIndex]?.children ?? []); + } + } + return rows; +} + +function extractGfmCodeCellValues(cell: MdastNode): string[] { + const nodes = cell.children ?? []; + if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') { + return []; + } + + const values: string[] = []; + let i = 0; + while (i < nodes.length) { + const node = nodes[i]!; + if (node.type === 'inlineCode') { + values.push(node.value ?? ''); + i += 1; + } else if (node.type === 'html' && node.value === '') { + let inner = ''; + i += 1; + let closed = false; + while (i < nodes.length) { + const innerNode = nodes[i]!; + if (innerNode.type === 'html' && innerNode.value === '') { + closed = true; + i += 1; + break; + } + if (innerNode.type !== 'text') { + throw new Error( + `Unexpected Markdown node "${innerNode.type}" inside element: ${JSON.stringify(innerNode)}` + ); + } + inner += decodeHtmlEntities(innerNode.value ?? ''); + i += 1; + } + if (!closed) { + throw new Error('Unclosed HTML element in GFM table cell'); + } + values.push(inner); + } else if (node.type === 'text' && node.value === ', ') { + i += 1; + } else { + throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`); + } + } + return values; +} + +describe('renderFieldShapesMarkdown', () => { + test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => { + const docsA = [ + { + _id: fakeObjectId('000000000000000000000001'), + 'pipe|col': 'val|with`ticks\\slash', + 'slash\\|field': 'slash\\|pipe*em*_u_&', + 'tick`field\nname': '`leading`', + edge: 'double``ticks', + dt: '2025-01-02', + }, + { + _id: fakeObjectId('000000000000000000000002'), + 'pipe|col': 'slash\\|pipe', + 'slash\\|field': 'slash\\\\|pipe', + 'tick`field\nname': ' spaced ', + edge: '', + dt: '2025-01-03', + }, + ]; + const docsB = [docsA[1]!, docsA[0]!]; + + const run1 = await readFieldShapes( + createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader, + { collections: ['eodPrices', 'qmSplits'], limit: 500 } + ); + const run2 = await readFieldShapes( + createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader, + { collections: ['qmSplits', 'eodPrices'], limit: 500 } + ); + + const md1 = renderFieldShapesMarkdown(run1); + const md2 = renderFieldShapesMarkdown(run2); + + expect(md1).toBe(md2); + expect(md1).toContain('bounded sample'); + expect(md1).toContain('Sample limit per collection:** 500'); + expect(md1).toContain('Total documents sampled:** 2'); + expect(md1).toContain('_No documents sampled._'); + + const tableRows = parseGfmTables(md1); + expect(tableRows.length).toBe(6); + + const visibleByField = new Map(); + for (const cells of tableRows) { + expect(cells.length).toBe(5); + const parsedField = extractGfmCodeCellValues(cells[0]!); + expect(parsedField.length).toBe(1); + const parsedExamples = extractGfmCodeCellValues(cells[4]!); + visibleByField.set(parsedField[0]!, parsedExamples); + } + + expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']); + expect(visibleByField.get('slash\\\\|field')).toEqual([ + 'slash\\\\|pipe', + 'slash\\|pipe*em*_u_&', + ]); + expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']); + expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']); + expect(visibleByField.get('_id')).toEqual([]); + }); +}); + +describe('CLI arg parsing and headless probe runner', () => { + test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => { + expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true }); + expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/); + expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow( + /--limit/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow( + /--limit/ + ); + expect(() => + parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)]) + ).toThrow(/--limit/); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow( + /--limit/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow( + /--limit/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow( + /Unknown argument/ + ); + expect(() => + parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol']) + ).toThrow(UnknownProbeCollectionError); + + const parsed = parseProbeSourceFieldShapesArgs([ + '--out', + './tmp/report.md', + '--limit', + '250', + '--collections', + 'qmDividends,ceoShorts,qmDividends', + ]); + expect(parsed).toEqual({ + help: false, + outPath: './tmp/report.md', + limit: 250, + collections: ['ceoShorts', 'qmDividends'], + }); + }); + + test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => { + let getCollectionCalls = 0; + let closeCalls = 0; + + const writableClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => false, + getCollection() { + getCollectionCalls += 1; + throw new Error('should never be called'); + }, + }; + + await expect( + runSourceFieldShapesProbe( + { + mongoCollectionClient: writableClient, + closeMongo: () => { + closeCalls += 1; + }, + writeFile: () => {}, + writeStdout: () => {}, + }, + { outPath: './tmp/should-not-write.md' } + ) + ).rejects.toThrow(/read-only/i); + expect(getCollectionCalls).toBe(0); + expect(closeCalls).toBe(1); + + const writtenFiles: Array<{ filePath: string; content: string }> = []; + const stdoutChunks: string[] = []; + let roCloseCalls = 0; + + const roClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find() { + const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : []; + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) { + yield doc; + } + }, + async close() {}, + }; + }, + }; + }, + }; + + const output = await runSourceFieldShapesProbe( + { + mongoCollectionClient: roClient, + closeMongo: () => { + roCloseCalls += 1; + }, + writeFile: (filePath, content) => { + writtenFiles.push({ filePath, content }); + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { + outPath: './tmp/field-shapes.md', + limit: 10, + collections: ['ceoShorts'], + } + ); + + expect(roCloseCalls).toBe(1); + expect(writtenFiles.length).toBe(1); + expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md'); + expect(writtenFiles[0]!.content).toBe(output.markdown); + expect(stdoutChunks.join('')).toContain('Documents sampled: 1'); + }); +}); diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts index faba4bee..926377b1 100644 --- a/test/unit/security-master-run-cli.test.ts +++ b/test/unit/security-master-run-cli.test.ts @@ -5,29 +5,39 @@ import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { assertEnvironmentSafety, stockAppSchema } from '@stock-bot/stock-config'; import { + BarSpanIndex, computeBarSpans, type BarSpanAggregateReader, type GroupedBarSpanRow, } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; import { assertSecurityMasterPersistSafety, + buildSampleDateCalendar, classifySourceExchanges, compareAscii, composeSecurityMasterRun, createExchangeSourceLookup, createReadOnlyMongoSourceSymbolReader, + crossCheckPrices, + DEFAULT_SAMPLE_DATE_COUNT, EXCHANGE_SOURCES, + FX_USD_CAD_SOURCE_ID, ISO_EXCHANGE_SEEDS, + MAX_SAMPLE_DATES, normalizeRawExchangeDoc, parseRunSecurityMasterArgs, + readSampleCloses, readSecurityMasterSources, RUN_SECURITY_MASTER_USAGE, runSecurityMaster, SECURITY_MASTER_OUTPUT_FILES, + selectSampleDates, SOURCE_EXCHANGE_COLLECTIONS, + type ComposeSecurityMasterRunInput, type PersistSecurityMasterInput, type PersistSecurityMasterResult, type ReadOnlyMongoCollectionClient, + type ReadSampleClosesOptions, type SecurityMasterPostgresHandle, type SecurityMasterQueryable, type SourceExchangeRecord, @@ -93,6 +103,33 @@ function extractRequestedIdsFromPipeline(pipeline: readonly Record; + readonly options?: Record; +} + +function matchesFakeFindFilter( + doc: Record, + filter: Record +): boolean { + for (const [field, condition] of Object.entries(filter)) { + if ( + condition !== null && + typeof condition === 'object' && + Array.isArray((condition as { $in?: unknown }).$in) + ) { + const allowed = new Set((condition as { $in: unknown[] }).$in); + if (!allowed.has(doc[field])) { + return false; + } + } else if (doc[field] !== condition) { + return false; + } + } + return true; +} + function createStrictReadOnlyFakeMongo( fixture: FakeMongoFixture, options: { @@ -105,10 +142,12 @@ function createStrictReadOnlyFakeMongo( readonly barSpanReader: BarSpanAggregateReader; readonly aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }>; readonly findCalls: string[]; + readonly findCallDetails: FindCallDetail[]; } { const readOnly = options.readOnly ?? true; const aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }> = []; const findCalls: string[] = []; + const findCallDetails: FindCallDetail[] = []; const target = { isReadOnly(): boolean { @@ -116,13 +155,23 @@ function createStrictReadOnlyFakeMongo( }, getCollection(collectionName: string) { const colTarget = { - find(_filter: Record = {}) { + find(filter: Record = {}, findOptions?: Record) { findCalls.push(collectionName); + findCallDetails.push({ + collectionName, + filter, + ...(findOptions !== undefined ? { options: findOptions } : {}), + }); if (options.failCollection === collectionName) { throw new Error(`Simulated Mongo find failure on ${collectionName}`); } const docs = fixture.collections[collectionName] ?? []; - return makeAsyncCursor(docs); + const filtered = + (collectionName === 'eodPrices' || collectionName === 'qmPrices') && + Object.keys(filter).length > 0 + ? docs.filter(doc => matchesFakeFindFilter(doc, filter)) + : docs; + return makeAsyncCursor(filtered); }, }; @@ -174,10 +223,53 @@ function createStrictReadOnlyFakeMongo( barSpanReader: proxy as unknown as BarSpanAggregateReader, aggregateCalls, findCalls, + findCallDetails, }; } -function buildUsCaFixture(): FakeMongoFixture { +function buildUsCaFixture(options: { readonly qmPriceMultiplier?: number } = {}): FakeMongoFixture { + const qmMultiplier = options.qmPriceMultiplier ?? 1; + const spanIndex = new BarSpanIndex(); + spanIndex.merge({ + source: 'eod', + sourceId: 'AAPL.US', + firstBarDate: '2015-01-02', + lastBarDate: '2026-01-14', + barCount: 2770, + }); + spanIndex.merge({ + source: 'qm', + sourceId: 'AAPL:US', + firstBarDate: '2018-01-02', + lastBarDate: '2026-01-14', + barCount: 2015, + }); + const calendar = buildSampleDateCalendar({ index: spanIndex }, '2026-01-15'); + const fixtureDates = Array.from( + new Set([ + ...selectSampleDates(calendar, { count: DEFAULT_SAMPLE_DATE_COUNT }), + ...selectSampleDates(calendar, { count: 10 }), + ]) + ).sort(compareAscii); + + const eodPrices: Record[] = []; + const qmPrices: Record[] = []; + for (let i = 0; i < fixtureDates.length; i++) { + const date = fixtureDates[i]!; + const aaplClose = Number((100 + ((i * 17) % 53) + i * 0.75).toFixed(4)); + const shopClose = Number((60 + ((i * 11) % 31) + i * 0.5).toFixed(4)); + const fxRate = Number((1.32 + (i % 9) * 0.012).toFixed(4)); + eodPrices.push( + { eodSearchCode: 'AAPL.US', date, close: aaplClose }, + { eodSearchCode: 'SHOP.TO', date, close: shopClose }, + { eodSearchCode: FX_USD_CAD_SOURCE_ID, date, close: fxRate } + ); + qmPrices.push( + { qmSearchCode: 'AAPL:US', date, unadjustedclose: Number((aaplClose * qmMultiplier).toFixed(4)) }, + { qmSearchCode: 'MYSTERY:CA', date, unadjustedclose: Number((25 + i * 0.4).toFixed(4)) } + ); + } + return { collections: { eodExchanges: [ @@ -255,6 +347,8 @@ function buildUsCaFixture(): FakeMongoFixture { ], ceoSymbols: [], eodSymbolChange: [], + eodPrices, + qmPrices, }, barSpanRowsByCollection: { eodPrices: [ @@ -333,27 +427,50 @@ function assertObjectKeysSortedAscii(value: unknown, path = '$'): void { } describe('parseRunSecurityMasterArgs', () => { - test('parses required space-separated args with default persist=false', () => { + test('parses required space-separated args with default persist=false and Pass 4 enabled', () => { 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, + skipPriceCrossCheck: false, + sampleDateCount: DEFAULT_SAMPLE_DATE_COUNT, }); }); - test('parses = syntax, leap day, and --persist flag', () => { + test('parses = syntax, leap day, --persist, --skip-price-cross-check, and --sample-dates', () => { const parsed = parseRunSecurityMasterArgs([ '--as-of=2024-02-29', '--out-dir=/tmp/sm-report', '--persist', + '--skip-price-cross-check', + '--sample-dates=10', ]); expect(parsed).toEqual({ help: false, asOfDate: '2024-02-29', outDir: '/tmp/sm-report', persist: true, + skipPriceCrossCheck: true, + sampleDateCount: 10, + }); + + const parsedSpace = parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './tmp/out', + '--sample-dates', + String(MAX_SAMPLE_DATES), + ]); + expect(parsedSpace).toEqual({ + help: false, + asOfDate: '2026-01-15', + outDir: './tmp/out', + persist: false, + skipPriceCrossCheck: false, + sampleDateCount: MAX_SAMPLE_DATES, }); }); @@ -362,6 +479,8 @@ describe('parseRunSecurityMasterArgs', () => { expect(RUN_SECURITY_MASTER_USAGE).toContain('--as-of'); expect(RUN_SECURITY_MASTER_USAGE).toContain('--out-dir'); expect(RUN_SECURITY_MASTER_USAGE).toContain('--persist'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--skip-price-cross-check'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--sample-dates'); }); test('rejects missing --as-of or --out-dir', () => { @@ -377,6 +496,47 @@ describe('parseRunSecurityMasterArgs', () => { } }); + test('rejects invalid --sample-dates values (0, 65, negative, float, non-numeric, missing)', () => { + for (const badValue of ['0', String(MAX_SAMPLE_DATES + 1), '-1', '10.5', 'abc', '10abc']) { + expect(() => + parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './out', + '--sample-dates', + badValue, + ]) + ).toThrow(/Invalid --sample-dates value/); + expect(() => + parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './out', + `--sample-dates=${badValue}`, + ]) + ).toThrow(/Invalid --sample-dates value/); + } + + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--sample-dates']) + ).toThrow(/Missing value for --sample-dates/); + expect(() => + parseRunSecurityMasterArgs([ + '--as-of', + '2026-01-15', + '--out-dir', + './out', + '--sample-dates', + '--persist', + ]) + ).toThrow(/Missing value for --sample-dates/); + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--sample-dates=']) + ).toThrow(/Missing value for --sample-dates/); + }); + test('rejects unknown flags, positional args, and flags missing values', () => { expect(() => parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--unknown']) @@ -447,11 +607,25 @@ describe('runSecurityMaster', () => { qm: ['AAPL:US', 'MYSTERY:CA'], }, }); + const expectedCalendar = buildSampleDateCalendar(expectedBarSpans, '2026-01-15'); + const expectedSampleDates = selectSampleDates(expectedCalendar, { + count: DEFAULT_SAMPLE_DATE_COUNT, + }); + const expectedSampleCloses = await readSampleCloses(refReader, { + sampleDates: expectedSampleDates, + sourceIdsBySource: { + eod: ['AAPL.US'], + qm: ['AAPL:US'], + }, + includeFx: true, + }); const expectedComposed = composeSecurityMasterRun( { sources: expectedSources, barSpans: expectedBarSpans, exchanges: expectedExchanges, + sampleCloses: expectedSampleCloses.closes, + fxRates: expectedSampleCloses.fxRates, }, { asOfDate: '2026-01-15' } ); @@ -481,8 +655,26 @@ describe('runSecurityMaster', () => { 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(parsedStats.pass4Wired).toBe(true); + expect(result.composed.pass4).not.toBeNull(); + expect(result.composed.pass4?.stats.byVerdict.confirmed).toBeGreaterThanOrEqual(1); + const pass4Stats = parsedStats.pass4 as { + sampleDates: string[]; + candidatePairs: number; + eodIdsRequested: number; + qmIdsRequested: number; + skippedReason: string | null; + byVerdict: Record | null; + }; + expect(pass4Stats.sampleDates.length).toBeGreaterThanOrEqual(5); + expect(pass4Stats.sampleDates.length).toBeLessThanOrEqual(DEFAULT_SAMPLE_DATE_COUNT); + // AAPL has 3 sources on XNAS (eod, ib, qm) -> 3 pairwise candidate pairs, + // with 1 eod ID (AAPL.US) and 1 qm ID (AAPL:US) requested for sample closes. + expect(pass4Stats.candidatePairs).toBe(3); + expect(pass4Stats.eodIdsRequested).toBe(1); + expect(pass4Stats.qmIdsRequested).toBe(1); + expect(pass4Stats.skippedReason).toBeNull(); + expect(pass4Stats.byVerdict?.confirmed).toBeGreaterThanOrEqual(1); expect(result.composed.stageA.instruments.length).toBe(2); expect(result.composed.stageB.unresolved.some(u => u.sourceId === 'MYSTERY:CA')).toBe(true); @@ -491,7 +683,13 @@ describe('runSecurityMaster', () => { expect(summaryText).toContain('Instruments: 2'); expect(summaryText).toContain('Persisted: no (dry-run)'); expect(summaryText).toContain('match-report.md'); - expect(summaryText).toContain('skipped'); + expect(summaryText).toContain('executed'); + expect(summaryText).toContain(`dates=${pass4Stats.sampleDates.length}`); + expect(summaryText).toContain('confirmed=1'); + expect(summaryText).toContain('ratio_mismatch=0'); + expect(summaryText).toContain('low_correlation=0'); + expect(summaryText).toContain('insufficient_data=2'); + expect(summaryText).not.toContain('not yet wired'); }); test('produces byte-identical files across repeated runs in different output directories', async () => { @@ -1509,6 +1707,8 @@ describe('run-security-master CLI process', () => { test('usage errors exit non-zero with an Error line on stderr and no success summary', () => { for (const args of [ ['--as-of', '2026-02-30', '--out-dir', 'x'], + ['--as-of', '2026-01-15', '--out-dir', 'x', '--sample-dates', '0'], + ['--as-of', '2026-01-15', '--out-dir', 'x', '--sample-dates', '65'], ['--bogus'], ['--out-dir', 'x'], ]) { @@ -1519,3 +1719,921 @@ describe('run-security-master CLI process', () => { } }); }); + +describe('buildSampleDateCalendar', () => { + test('excludes weekends and clamps end date to min(eod, qm, asOfDate)', () => { + const index = new BarSpanIndex(); + // 2024-01-04 (Thu) .. 2024-01-15 (Mon) + index.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2024-01-01', + lastBarDate: '2024-01-15', + barCount: 10, + }); + index.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2024-01-04', + lastBarDate: '2024-01-12', + barCount: 7, + }); + + // Clamped to asOfDate=2024-01-10 (Wed); excludes Sat 2024-01-06 and Sun 2024-01-07 + const clamped = buildSampleDateCalendar({ index }, '2024-01-10'); + expect(clamped).toEqual([ + '2024-01-04', + '2024-01-05', + '2024-01-08', + '2024-01-09', + '2024-01-10', + ]); + + // When asOfDate is later than qm lastBarDate, end clamps to qm lastBarDate (2024-01-12) + const qmClamped = buildSampleDateCalendar({ index }, '2024-01-20'); + expect(qmClamped).toEqual([ + '2024-01-04', + '2024-01-05', + '2024-01-08', + '2024-01-09', + '2024-01-10', + '2024-01-11', + '2024-01-12', + ]); + }); + + test('returns empty array when a source has no spans, start > end, weekend-only, or invalid asOfDate', () => { + // Missing QM + const onlyEod = new BarSpanIndex(); + onlyEod.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2024-01-01', + lastBarDate: '2024-01-31', + barCount: 20, + }); + expect(buildSampleDateCalendar({ index: onlyEod }, '2024-01-31')).toEqual([]); + + // Missing EOD + const onlyQm = new BarSpanIndex(); + onlyQm.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2024-01-01', + lastBarDate: '2024-01-31', + barCount: 20, + }); + expect(buildSampleDateCalendar({ index: onlyQm }, '2024-01-31')).toEqual([]); + + // Non-overlapping (start > end) + const disjoint = new BarSpanIndex(); + disjoint.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2020-01-02', + lastBarDate: '2021-12-31', + barCount: 500, + }); + disjoint.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2022-01-03', + lastBarDate: '2024-01-15', + barCount: 500, + }); + expect(buildSampleDateCalendar({ index: disjoint }, '2024-01-15')).toEqual([]); + + // Weekend-only window: 2024-01-06 (Sat) .. 2024-01-07 (Sun) + const weekendOnly = new BarSpanIndex(); + weekendOnly.merge({ + source: 'eod', + sourceId: 'A.US', + firstBarDate: '2024-01-06', + lastBarDate: '2024-01-07', + barCount: 1, + }); + weekendOnly.merge({ + source: 'qm', + sourceId: 'A:US', + firstBarDate: '2024-01-06', + lastBarDate: '2024-01-07', + barCount: 1, + }); + expect(buildSampleDateCalendar({ index: weekendOnly }, '2024-01-10')).toEqual([]); + + // Invalid asOfDate + expect(buildSampleDateCalendar({ index: onlyEod }, '2023-02-29')).toEqual([]); + }); + + test('is deterministic across repeated calls regardless of BarSpanIndex insertion order', () => { + const spans = [ + { source: 'eod' as const, sourceId: 'B.US', firstBarDate: '2024-01-05', lastBarDate: '2024-01-19', barCount: 11 }, + { source: 'eod' as const, sourceId: 'A.US', firstBarDate: '2024-01-02', lastBarDate: '2024-01-10', barCount: 7 }, + { source: 'qm' as const, sourceId: 'B:US', firstBarDate: '2024-01-08', lastBarDate: '2024-01-26', barCount: 15 }, + { source: 'qm' as const, sourceId: 'A:US', firstBarDate: '2024-01-03', lastBarDate: '2024-01-12', barCount: 8 }, + ]; + const indexA = new BarSpanIndex(); + for (const s of spans) { + indexA.merge(s); + } + const indexB = new BarSpanIndex(); + for (const s of [...spans].reverse()) { + indexB.merge(s); + } + const calA1 = buildSampleDateCalendar({ index: indexA }, '2024-01-18'); + const calA2 = buildSampleDateCalendar({ index: indexA }, '2024-01-18'); + const calB = buildSampleDateCalendar({ index: indexB }, '2024-01-18'); + expect(calA1).toEqual(calA2); + expect(calA1).toEqual(calB); + }); +}); + +describe('runSecurityMaster Pass 4 wiring', () => { + test('2x non-FX price ratio mismatch produces price_ratio_mismatch in conflicts.csv and match-report.md', async () => { + const fixture = buildUsCaFixture({ qmPriceMultiplier: 2 }); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-conflict-'); + const stdoutChunks: string[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(result.composed.pass4).not.toBeNull(); + expect(result.composed.pass4?.stats.byVerdict.ratio_mismatch).toBeGreaterThanOrEqual(1); + + const conflictsCsv = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), + 'utf8' + ); + const matchReport = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), + 'utf8' + ); + expect(conflictsCsv).toContain('price_ratio_mismatch'); + expect(matchReport).toContain('price_ratio_mismatch'); + expect(stdoutChunks.join('')).toContain('ratio_mismatch=1'); + }); + + test('FX forwarding (Option A Test 1): reads CAD.FOREX with includeFx=true and forwards fxRates to compose', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-fx-'); + + const capturedReadOptions: ReadSampleClosesOptions[] = []; + const capturedComposeInputs: ComposeSecurityMasterRunInput[] = []; + let readFxRatesCount = 0; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + readSampleClosesFn: async (reader, options) => { + expect(reader.isReadOnly()).toBe(true); + capturedReadOptions.push(options); + const readResult = await readSampleCloses(reader, options); + readFxRatesCount = readResult.fxRates.length; + return readResult; + }, + composeFn: (input, options) => { + capturedComposeInputs.push(input); + return composeSecurityMasterRun(input, options); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(capturedReadOptions).toHaveLength(1); + expect(capturedReadOptions[0]?.includeFx).toBe(true); + expect(capturedComposeInputs).toHaveLength(2); + expect(capturedComposeInputs[0]?.fxRates).toBeUndefined(); + expect(result.sampleCloses).not.toBeNull(); + expect(readFxRatesCount).toBe(result.pass4.sampleDates.length); + expect(capturedComposeInputs[1]?.fxRates).toEqual(result.sampleCloses?.fxRates); + + const fxFinds = fakeMongo.findCallDetails.filter( + call => + call.collectionName === 'eodPrices' && + Array.isArray((call.filter.eodSearchCode as { $in?: unknown[] } | undefined)?.$in) && + (call.filter.eodSearchCode as { $in: unknown[] }).$in.includes(FX_USD_CAD_SOURCE_ID) + ); + expect(fxFinds).toHaveLength(1); + expect(fxFinds[0]?.filter).toEqual({ + date: { $in: result.pass4.sampleDates }, + eodSearchCode: { $in: [FX_USD_CAD_SOURCE_ID] }, + }); + + const parsedStats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4: { stats: { fx: { emitted: number } } } }; + expect(parsedStats.pass4.stats.fx.emitted).toBe(readFxRatesCount); + }); + + test('USD/CAD verdict (Option A Test 2): crossCheckPrices confirms USD EOD vs CAD QM pair using extracted fxRates', async () => { + const dates = [ + '2025-01-06', + '2025-02-05', + '2025-03-05', + '2025-04-07', + '2025-05-05', + '2025-06-05', + ]; + const usdCloses = [80.0, 88.5, 84.2, 95.1, 102.4, 98.7]; + const fxRates = [1.34, 1.36, 1.35, 1.38, 1.37, 1.39]; + + const fakeMongo = createStrictReadOnlyFakeMongo({ + collections: { + eodPrices: [ + ...dates.map((date, idx) => ({ + eodSearchCode: 'SHOP.US', + date, + close: usdCloses[idx], + })), + ...dates.map((date, idx) => ({ + eodSearchCode: FX_USD_CAD_SOURCE_ID, + date, + close: fxRates[idx], + })), + ], + qmPrices: dates.map((date, idx) => ({ + qmSearchCode: 'SHOP:CA', + date, + unadjustedclose: Number(((usdCloses[idx] ?? 0) * (fxRates[idx] ?? 0)).toFixed(6)), + })), + }, + }); + const reader = createReadOnlyMongoSourceSymbolReader(fakeMongo.mongoCollectionClient); + const extracted = await readSampleCloses(reader, { + sampleDates: dates, + sourceIdsBySource: { eod: ['SHOP.US'], qm: ['SHOP:CA'] }, + includeFx: true, + }); + + const pair = { + left: { source: 'eod', sourceId: 'SHOP.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'SHOP:CA', currency: 'CAD' }, + }; + + const withFx = crossCheckPrices({ + pairs: [pair], + closes: extracted.closes, + usdCadByDate: extracted.fxRates, + }); + expect(withFx.results).toHaveLength(1); + expect(withFx.results[0]?.verdict).toBe('confirmed'); + expect(withFx.stats.byVerdict.confirmed).toBe(1); + + const withoutFx = crossCheckPrices({ + pairs: [pair], + closes: extracted.closes, + usdCadByDate: [], + }); + expect(withoutFx.results[0]?.verdict).toBe('insufficient_data'); + expect(withoutFx.stats.byVerdict.confirmed).toBe(0); + expect(withoutFx.stats.skippedMissingFxDates).toBeGreaterThanOrEqual(5); + }); + + test('query-shape & read-only guard: sample-close reads use date $in filter and request only Pass 4 endpoint IDs', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-query-'); + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + const priceFinds = fakeMongo.findCallDetails.filter( + call => call.collectionName === 'eodPrices' || call.collectionName === 'qmPrices' + ); + expect(priceFinds).toHaveLength(3); // EOD equity, QM equity, EOD FX + + for (const call of priceFinds) { + expect(call.filter.date).toEqual({ $in: result.pass4.sampleDates }); + } + + const eodEquityFind = priceFinds.find( + call => + call.collectionName === 'eodPrices' && + !(call.filter.eodSearchCode as { $in: string[] }).$in.includes(FX_USD_CAD_SOURCE_ID) + ); + const qmEquityFind = priceFinds.find(call => call.collectionName === 'qmPrices'); + + // Only AAPL.US and AAPL:US are Pass 4 endpoints; SHOP.TO, MYSTERY:CA, and IB 265598 are excluded. + expect(eodEquityFind?.filter.eodSearchCode).toEqual({ $in: ['AAPL.US'] }); + expect(qmEquityFind?.filter.qmSearchCode).toEqual({ $in: ['AAPL:US'] }); + }); + + test('skip paths (disabled, no_sample_dates, no_candidate_pairs) issue zero sample-close reads', async () => { + // (a) pass4.enabled: false + { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir('sm-skip-disabled-'); + const stdoutChunks: string[] = []; + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir, pass4: { enabled: false } } + ); + expect( + fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices') + ).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBe('disabled'); + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4Wired: boolean; pass4: { skippedReason: string | null } }; + expect(stats.pass4Wired).toBe(false); + expect(stats.pass4.skippedReason).toBe('disabled'); + expect(stdoutChunks.join('')).toContain('skipped (disabled)'); + } + + // (b) non-overlapping EOD/QM bar spans -> no_sample_dates + { + const base = buildUsCaFixture(); + const nonOverlapping: FakeMongoFixture = { + ...base, + barSpanRowsByCollection: { + eodPrices: [ + { _id: 'AAPL.US', firstBarDate: '2015-01-02', lastBarDate: '2017-12-29', barCount: 750 }, + ], + qmPrices: [ + { _id: 'AAPL:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 }, + ], + }, + }; + const fakeMongo = createStrictReadOnlyFakeMongo(nonOverlapping); + const outDir = createTempDir('sm-skip-nodates-'); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + expect( + fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices') + ).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBe('no_sample_dates'); + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4Wired: boolean; pass4: { skippedReason: string | null } }; + expect(stats.pass4Wired).toBe(false); + expect(stats.pass4.skippedReason).toBe('no_sample_dates'); + } + + // (c) zero candidate pairs -> no_candidate_pairs + { + const base = buildUsCaFixture(); + const noPairs: FakeMongoFixture = { + ...base, + collections: { + ...base.collections, + // Keep only unpaired SHOP.TO (EOD) and MYSTERY:CA (QM) with overlapping spans + eodSymbols: (base.collections.eodSymbols ?? []).filter(d => d.eodSearchCode === 'SHOP.TO'), + ibSymbols: [], + qmSymbols: (base.collections.qmSymbols ?? []).filter(d => d.qmSearchCode === 'MYSTERY:CA'), + }, + }; + const fakeMongo = createStrictReadOnlyFakeMongo(noPairs); + const outDir = createTempDir('sm-skip-nopairs-'); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + expect( + fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices') + ).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBe('no_candidate_pairs'); + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4Wired: boolean; pass4: { skippedReason: string | null } }; + expect(stats.pass4Wired).toBe(false); + expect(stats.pass4.skippedReason).toBe('no_candidate_pairs'); + } + }); + + test('sample-close read failure wraps step read-sample-closes, writes no artifacts, skips persist, and closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { + failCollection: 'qmPrices', + }); + const writes: string[] = []; + const stdout: string[] = []; + let pgFactoryCalls = 0; + let persistCalls = 0; + let mongoClosed = 0; + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('must not be called'); + }, + persistFn: async () => { + persistCalls += 1; + return makeFakePersistResult(); + }, + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: '/virtual/out', persist: true } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('read-sample-closes'); + expect(writes).toHaveLength(0); + expect(pgFactoryCalls).toBe(0); + expect(persistCalls).toBe(0); + expect(stdout).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('programmatic pass4 option validation rejects invalid counts before Mongo and respects sampleDateCount=10', async () => { + for (const badCount of [0, MAX_SAMPLE_DATES + 1, -1, 10.5, Number.NaN]) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { + asOfDate: '2026-01-15', + outDir: createTempDir(), + pass4: { sampleDateCount: badCount }, + } + ); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('validate-options'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + + // Valid sampleDateCount=10 yields at most 10 sample dates + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { + asOfDate: '2026-01-15', + outDir: createTempDir(), + pass4: { sampleDateCount: 10 }, + } + ); + expect(result.pass4.sampleDates.length).toBeLessThanOrEqual(10); + expect(result.pass4.sampleDates.length).toBe(10); + expect(result.composed.pass4?.stats.byVerdict.confirmed).toBe(1); + }); + + test('determinism: repeated runs with Pass 4 active (confirmed + conflict) write byte-identical artifacts', async () => { + const base = buildUsCaFixture(); + // Add a second paired security (MSFT) with a 2x conflict so both confirmed and conflict paths are active. + const msftEodDates = (base.collections.eodPrices ?? []) + .filter(d => d.eodSearchCode === 'AAPL.US') + .map(d => String(d.date)); + const deterministicFixture: FakeMongoFixture = { + collections: { + ...base.collections, + eodSymbols: [ + ...(base.collections.eodSymbols ?? []), + { + eodSearchCode: 'MSFT.US', + Code: 'MSFT', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US5949181045', + Cusip: '594918104', + Name: 'Microsoft Corp', + Type: 'Common Stock', + delisted: false, + }, + ], + qmSymbols: [ + ...(base.collections.qmSymbols ?? []), + { + qmSearchCode: 'MSFT:US', + symbol: 'MSFT', + exchange: 'NSD', + countryCode: 'US', + currency: 'USD', + name: 'Microsoft Corp', + active: true, + }, + ], + eodPrices: [ + ...(base.collections.eodPrices ?? []), + ...msftEodDates.map((date, idx) => ({ + eodSearchCode: 'MSFT.US', + date, + close: Number((200 + ((idx * 13) % 41) + idx * 0.9).toFixed(4)), + })), + ], + qmPrices: [ + ...(base.collections.qmPrices ?? []), + ...msftEodDates.map((date, idx) => ({ + qmSearchCode: 'MSFT:US', + date, + unadjustedclose: Number(((200 + ((idx * 13) % 41) + idx * 0.9) * 2).toFixed(4)), + })), + ], + }, + barSpanRowsByCollection: { + eodPrices: [ + ...(base.barSpanRowsByCollection?.eodPrices ?? []), + { _id: 'MSFT.US', firstBarDate: '2015-01-02', lastBarDate: '2026-01-14', barCount: 2770 }, + ], + qmPrices: [ + ...(base.barSpanRowsByCollection?.qmPrices ?? []), + { _id: 'MSFT:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 }, + ], + }, + }; + + const outDir1 = createTempDir('sm-pass4-det-1-'); + const outDir2 = createTempDir('sm-pass4-det-2-'); + const mongo1 = createStrictReadOnlyFakeMongo(deterministicFixture); + const mongo2 = createStrictReadOnlyFakeMongo(deterministicFixture); + + const run1 = 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 } + ); + + expect(run1.composed.pass4?.stats.byVerdict.confirmed).toBe(1); + expect(run1.composed.pass4?.stats.byVerdict.ratio_mismatch).toBe(1); + + 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 Pass 4 runs`).toBe(content1); + } + }); +}); + +describe('runSecurityMaster Pass 4 wiring (QA edge cases)', () => { + test('read runs but returns no closes: pass4Wired=true, composed.pass4 null, artifacts still written', async () => { + const base = buildUsCaFixture(); + const fixture: FakeMongoFixture = { + ...base, + collections: { ...base.collections, eodPrices: [], qmPrices: [] }, + }; + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir('sm-pass4-empty-'); + const stdoutChunks: string[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(fakeMongo.findCalls.filter(c => c === 'eodPrices' || c === 'qmPrices')).toHaveLength(3); + expect(result.sampleCloses).not.toBeNull(); + expect(result.sampleCloses?.closes).toHaveLength(0); + expect(result.composed.pass4).toBeNull(); + expect(result.pass4.skippedReason).toBeNull(); + expect(result.pass4.byVerdict).toBeNull(); + expect(result.pass4.sampleDates).toHaveLength(DEFAULT_SAMPLE_DATE_COUNT); + + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { + pass4Wired: boolean; + pass4: { + byVerdict: unknown; + skippedReason: unknown; + stats: { eod: { emitted: number }; qm: { emitted: number }; fx: { emitted: number } }; + }; + }; + expect(stats.pass4Wired).toBe(true); + expect(stats.pass4.byVerdict).toBeNull(); + expect(stats.pass4.skippedReason).toBeNull(); + expect(stats.pass4.stats.eod.emitted).toBe(0); + expect(stats.pass4.stats.qm.emitted).toBe(0); + expect(stats.pass4.stats.fx.emitted).toBe(0); + + const conflictsCsv = readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), 'utf8'); + expect(conflictsCsv).not.toContain('price_ratio_mismatch'); + const summary = stdoutChunks.join(''); + expect(summary).toContain('Pass 4 price cross-check: skipped'); + expect(summary).toContain(`dates=${DEFAULT_SAMPLE_DATE_COUNT}`); + expect(summary).toContain('confirmed=0'); + expect(summary).not.toContain('not yet wired'); + }); + + test('--persist with Pass 4 active persists the second (price-checked) compose result', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture({ qmPriceMultiplier: 2 })); + const composeResults: ReturnType[] = []; + const persistInputs: PersistSecurityMasterInput[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + assertSafety: () => {}, + createPostgresClient: (): SecurityMasterPostgresHandle => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => {}, + }), + persistFn: async (_queryable, input) => { + persistInputs.push(input); + return makeFakePersistResult(); + }, + composeFn: (input, options) => { + const composedResult = composeSecurityMasterRun(input, options); + composeResults.push(composedResult); + return composedResult; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir('sm-pass4-persist-'), persist: true } + ); + + expect(composeResults).toHaveLength(2); + expect(composeResults[0]?.pass4).toBeNull(); + expect(composeResults[1]?.pass4?.stats.byVerdict.ratio_mismatch).toBe(1); + expect(persistInputs).toHaveLength(1); + expect(persistInputs[0] === composeResults[1]?.persistInput).toBe(true); + expect(result.composed === composeResults[1]).toBe(true); + }); + + test('second compose failure rejects at compose after the read, writes nothing, closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const writes: string[] = []; + const stdout: string[] = []; + let composeCalls = 0; + let readCalls = 0; + let mongoClosed = 0; + let caught: unknown = null; + + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + readSampleClosesFn: async (reader, options) => { + readCalls += 1; + return readSampleCloses(reader, options); + }, + composeFn: (input, options) => { + composeCalls += 1; + if (composeCalls === 2) { + throw new Error('simulated second compose failure'); + } + return composeSecurityMasterRun(input, options); + }, + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: '/virtual/out' } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('compose'); + expect((caught as Error).message).not.toContain('read-sample-closes'); + expect(readCalls).toBe(1); + expect(composeCalls).toBe(2); + expect(writes).toHaveLength(0); + expect(stdout).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('batchSize is forwarded to sample-close finds only when provided', async () => { + const withBatch = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const capturedWith: ReadSampleClosesOptions[] = []; + await runSecurityMaster( + { + mongoCollectionClient: withBatch.mongoCollectionClient, + barSpanReader: withBatch.barSpanReader, + readSampleClosesFn: async (reader, options) => { + capturedWith.push(options); + return readSampleCloses(reader, options); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), batchSize: 7 } + ); + expect(capturedWith[0]?.batchSize).toBe(7); + const priceFindsWith = withBatch.findCallDetails.filter( + c => c.collectionName === 'eodPrices' || c.collectionName === 'qmPrices' + ); + expect(priceFindsWith).toHaveLength(3); + for (const call of priceFindsWith) { + expect(call.options?.batchSize).toBe(7); + } + + const withoutBatch = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const capturedWithout: ReadSampleClosesOptions[] = []; + await runSecurityMaster( + { + mongoCollectionClient: withoutBatch.mongoCollectionClient, + barSpanReader: withoutBatch.barSpanReader, + readSampleClosesFn: async (reader, options) => { + capturedWithout.push(options); + return readSampleCloses(reader, options); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + expect(capturedWithout).toHaveLength(1); + expect('batchSize' in (capturedWithout[0] ?? {})).toBe(false); + }); + + test('programmatic pass4 rejects null and non-boolean enabled at validate-options before any Mongo read', async () => { + const badPass4Values: unknown[] = [null, 'on', { enabled: 'yes' }, { enabled: 1 }, { sampleDateCount: '10' }]; + for (const badPass4 of badPass4Values) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { + asOfDate: '2026-01-15', + outDir: createTempDir(), + pass4: badPass4 as { enabled?: boolean }, + } + ); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('validate-options'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(fakeMongo.aggregateCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + }); + + test('selected sample dates are ascending, unique, Mon-Fri, inside the overlap window, and mirrored in run-stats.json', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir('sm-pass4-dates-'); + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + const dates = result.pass4.sampleDates; + expect(dates).toHaveLength(DEFAULT_SAMPLE_DATE_COUNT); + expect([...dates].sort(compareAscii)).toEqual([...dates]); + expect(new Set(dates).size).toBe(dates.length); + for (const date of dates) { + const dow = new Date(`${date}T00:00:00Z`).getUTCDay(); + expect(dow).toBeGreaterThanOrEqual(1); + expect(dow).toBeLessThanOrEqual(5); + // Overlap of fixture spans: QM starts 2018-01-02, both end 2026-01-14. + expect(date >= '2018-01-02').toBe(true); + expect(date <= '2026-01-14').toBe(true); + } + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { pass4: { sampleDates: string[] } }; + expect(stats.pass4.sampleDates).toEqual([...dates]); + }); +}); + +describe('buildSampleDateCalendar (QA edge cases)', () => { + function twoSourceIndex(first: string, last: string): BarSpanIndex { + const index = new BarSpanIndex(); + index.merge({ source: 'eod', sourceId: 'X.US', firstBarDate: first, lastBarDate: last, barCount: 5 }); + index.merge({ source: 'qm', sourceId: 'X:US', firstBarDate: first, lastBarDate: last, barCount: 5 }); + return index; + } + + test('handles year boundaries and leap days (2000 and 2024)', () => { + expect(buildSampleDateCalendar({ index: twoSourceIndex('2023-12-28', '2024-01-02') }, '2024-01-02')).toEqual([ + '2023-12-28', + '2023-12-29', + '2024-01-01', + '2024-01-02', + ]); + expect(buildSampleDateCalendar({ index: twoSourceIndex('2024-02-28', '2024-03-01') }, '2024-03-01')).toEqual([ + '2024-02-28', + '2024-02-29', + '2024-03-01', + ]); + expect(buildSampleDateCalendar({ index: twoSourceIndex('2000-02-28', '2000-03-01') }, '2000-03-01')).toEqual([ + '2000-02-28', + '2000-02-29', + '2000-03-01', + ]); + }); + + test('matches a Date.getUTCDay weekday oracle over 2019-2026', () => { + const calendar = buildSampleDateCalendar({ index: twoSourceIndex('2019-01-01', '2026-12-31') }, '2026-12-31'); + const expected: string[] = []; + for ( + let ms = Date.UTC(2019, 0, 1); + ms <= Date.UTC(2026, 11, 31); + ms += 86_400_000 + ) { + const d = new Date(ms); + const dow = d.getUTCDay(); + if (dow >= 1 && dow <= 5) { + expected.push(d.toISOString().slice(0, 10)); + } + } + expect(calendar).toEqual(expected); + }); + + test('ignores zero-bar, inverted, and invalid-date spans when computing the window', () => { + const index = twoSourceIndex('2024-01-08', '2024-01-12'); + index.merge({ source: 'eod', sourceId: 'Z.US', firstBarDate: '2020-01-01', lastBarDate: '2030-01-01', barCount: 0 }); + index.merge({ source: 'qm', sourceId: 'Y:US', firstBarDate: '2024-02-30', lastBarDate: '2024-03-05', barCount: 3 }); + expect(buildSampleDateCalendar({ index }, '2030-01-01')).toEqual([ + '2024-01-08', + '2024-01-09', + '2024-01-10', + '2024-01-11', + '2024-01-12', + ]); + }); + + test('asOfDate before the overlap start yields an empty calendar', () => { + expect(buildSampleDateCalendar({ index: twoSourceIndex('2024-01-08', '2024-01-12') }, '2024-01-05')).toEqual([]); + }); +}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 66e1bb46..17a618af 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`. +Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, and the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`). ## Scope & Sign Conventions @@ -453,7 +453,29 @@ Rules: - `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`). - `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`. 5. **Deferred out of `M1.2o`:** - - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). + - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). + +## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`) + +`decode_qm_split_doc`, `decode_qm_split_bytes`, `decode_qm_split_buffer`, `decode_qm_dividend_doc`, `decode_qm_dividend_bytes`, and `decode_qm_dividend_buffer` (`src/bson_qm_actions.rs`) decode raw MongoDB `qmSplits` and `qmDividends` BSON documents in a single forward pass over `RawDocument::iter_elements()` into borrowed `RawQmSplit<'a>` and `RawQmDividend<'a>` views without allocating a `String` or `bson::Document` per row, reusing `bson_eod_prices::iter_raw_bson_docs` for concatenated length-prefixed buffers. + +1. **Field contract & cited in-repo sources:** + - `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`. + - `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25). + - `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25). + - `splitratio` (`FIELD_SPLIT_RATIO`): BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `splitratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25). + - `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding. + - `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below. + - `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below. +2. **Zero-allocation key mapping & builder conversions:** + - `RawQmSplit::to_split_event` → `SplitEvent`, `to_split_action_event` → `SplitActionEvent`; `RawQmDividend::to_dividend_event` → `DividendEvent`, `to_dividend_action_event` → `DividendActionEvent`. + - `try_map_key(|code, ex_date| ...)` and `try_into_*` helpers mirror `RawEodDailyBar::try_into_eod_daily_bar` so callers can resolve `("qm", qmSearchCode, ex_date)` through `ProviderMappingTable` before allocating `currency` on dividends. +3. **Typed errors & stream accounting policy:** + - Never panics on untrusted input. `BsonQmActionError` names the offending field on every field-level error (`MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, plus framing variants `TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`). + - Buffer decoders report and skip per-document errors without aborting the stream, always reconciling `decoded + rejected_total() == docs_in`. +4. **Unverified field names:** + - `amount` (`FIELD_DIVIDEND_CASH`) and `currency` (`FIELD_DIVIDEND_CURRENCY`) could not be proven from any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped and `design/DATA-CONTRACTS.md` names only `date`, `declared`, and `usdFxRate` for `qmDividends`). Both are isolated in single `pub const` constants so the live MongoDB cursor task can confirm or adjust them in one place before touching QA data. + - Numeric strings (e.g. `"10.0"`, `"1.42"`) are currently rejected as `WrongType` because no in-repo source proves QuoteMedia sends `splitratio` or dividend cash as strings; live schema inspection should confirm whether string coercion is needed. ## Local Benchmarks @@ -669,6 +691,54 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d27 - Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3` - Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`). +### `bench-bson-qm-actions` + +Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic QuoteMedia corporate-action documents (~4% `qmSplits`, ~96% `qmDividends`, with extra metadata `_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) pre-encoded into two contiguous length-prefixed buffers up front, timing decode-only via `decode_qm_split_buffer` and `decode_qm_dividend_buffer`: + +```bash +cargo run --release -p curate-etl --offline -- bench-bson-qm-actions [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59e46dc9dc`): `cargo run --release -p curate-etl --offline -- bench-bson-qm-actions` + +- Input: `rows=1000000`, `splits=40146`, `dividends=959854`, `bytes=236043886` (~225.1 MiB, ~236.0 bytes/doc) +- Splits: `decoded=39937`, `noop_ratio_one=616`, `rejected=209` (`missing=93`, `empty=0`, `wrong_type=45`, `malformed_date=38`, `invalid_number=33`, `corrupt=0`) +- Dividends: `decoded=954952`, `rejected=4902` (`missing=1952`, `empty=0`, `wrong_type=1009`, `malformed_date=946`, `invalid_number=995`, `corrupt=0`) +- Run 1: `elapsed=275.12 ms`, `throughput=3634828 docs/s`, `scan=818.23 MB/s`, `latency=275.12 ns/doc`, `checksum=0x6d48cd59e46dc9dc` +- Run 2: `elapsed=282.92 ms`, `throughput=3534598 docs/s`, `scan=795.67 MB/s`, `latency=282.92 ns/doc`, `checksum=0x6d48cd59e46dc9dc` + +## Raw BSON Streaming Reader (`bson_stream`, `M1.2y`) + +`RawBsonChunkReader` (`src/bson_stream.rs`) frames arbitrary concatenated length-prefixed raw BSON streams (files, stdin pipes, or future cursor adapters) into whole-document [`RawBsonChunk`] slices using a single reused buffer, feeding the existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, `decode_qm_dividend_buffer`) unchanged without requiring the full dataset to fit in memory. + +1. **Bounded memory & exact growth:** + - Defaults: `DEFAULT_CHUNK_CAPACITY_BYTES = 8 MiB`, `DEFAULT_MAX_DOC_BYTES = 16 MiB + 16 KiB` (MongoDB max document size plus headroom). `BsonStreamOptions::validate` rejects `chunk_capacity_bytes == 0` (`InvalidChunkCapacity`) and `max_doc_bytes < 5` (`InvalidMaxDocBytes`). + - Reuses one internal `Vec` buffer across chunks, compacting any trailing partial document to the front via `copy_within`. Grows only via `reserve_exact` + `resize` when a single document exceeds the current buffer length (or to 4 bytes when `chunk_capacity_bytes < 4`), and never beyond `max_doc_bytes`. `buffer_capacity()` exposes the current allocation ceiling. + - Retries `ErrorKind::Interrupted` transparently and handles arbitrary short reads down to 1 byte at a time. +2. **Error semantics & sticky terminal state:** + - Complete prefix documents already buffered are always yielded before surfacing a trailing framing or I/O error. + - Terminal errors carry the absolute byte `offset: u64` of the offending document: declared length `< 5` or `> max_doc_bytes` → `CorruptDocumentLength`; EOF mid-header or mid-document → `TruncatedDocument`; underlying read error → `Io`. After any terminal error, subsequent `next_chunk()` calls keep returning an error without panicking, looping, or re-reading the underlying source. +3. **Streaming decode helpers (`for<'a>` callbacks):** + - `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result` + - `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result` + - `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result` + - Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream. + +### `bench-bson-stream` + +Fixed-seed (`std`-only SplitMix64) streaming vs in-memory buffer decode benchmark over `2,000,000` synthetic `eodPrices` documents (reusing the exact `bench-bson-eod-prices` generator), decoding once via `decode_eod_price_buffer` and once via `RawBsonChunkReader` + `decode_eod_price_chunks` over an irregular short-read adapter (`257 B`..`128 KiB` prime steps straddling document and 4-byte header boundaries), asserting identical stats and checksum: + +```bash +cargo run --release -p curate-etl --offline -- bench-bson-stream [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-bson-stream` + +- Input: `rows=2000000`, `bytes=571280190` (~544.8 MiB) +- Decode: `decoded=1989987`, `rejected=10013` (`missing=3964`, `empty=0`, `wrong_type=2033`, `malformed_date=2027`, `invalid_number=1989`, `corrupt=0`), `checksum=0x94f87c60c9d3fbc6` +- Buffer baseline: `elapsed=524.54 ms`, `throughput=3812856 rows/s`, `scan=1038.65 MiB/s` +- Streamed short-read: `elapsed=544.59 ms`, `throughput=3672494 rows/s`, `scan=1000.42 MiB/s`, `ratio=0.963x`, `peak_buffer_capacity=8388608 bytes` (8 MiB) + ## Deferred Follow-Ups (`M1.3+` / `M2`) This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add: @@ -842,6 +912,61 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows] - Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s` - Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000` +## `adj_factors` Curation Stage (`M1.2v`) + +`curate_adj_factors`, `curate_adj_factors_as_of`, `curate_and_write_adj_factors`, `curate_and_write_adj_factors_as_of`, `read_adj_factors_dataset`, `read_adj_factors_dataset_as_of`, and `adj_factors_for_bar` (`src/curate_adj.rs`) join `ProviderMappingTable`, `build_adj_factors`, `session_close::et_session_close_utc_micros`, and `write_adj_factors_dataset` into contract `AdjFactorsParquetRow` records sorted and unique by `(listing_id, ex_date)`. + +1. **Map-before-build rule:** + - Resolves every source-keyed `qmSplits` and `qmDividends` event via `(mapping_source, source_key, ex_date) -> listing_id: i32` (using a cached per-key `ProviderMappingCursor`) *before* invoking `build_adj_factors::` unchanged. + - Cumulative factors (`cum_split_factor`, `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker renames (two adjacent source-key ranges mapping to one `listing_id`), while ticker reuse across distinct `listing_id`s (e.g. `FB` 2012–2022 vs `FB` 2025+) produces two independent chains with no cross-listing bleed. + - Unmapped splits and dividends are dropped and counted separately (`splits_dropped_unmapped`, `dividends_dropped_unmapped`). +2. **Collision policy (fail closed on cross-key conflict):** + - Single-source-key groups on `(listing_id, ex_date)` pass through unchanged to `build_adj_factors` (preserving same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and zero-cash dividend drops). + - Multi-source-key groups with bitwise-identical split ratios (or bitwise-identical dividend `cash`/`currency`/`prev_close`/`prev_close_currency`) collapse to one event and are counted in `splits_collision_collapsed`, `dividends_collision_collapsed`, and `listing_collision_collapsed`. + - Multi-source-key groups with conflicting split ratios or differing dividend payloads fail closed with `CurateAdjError::ConflictingCrossKeySplit` / `CurateAdjError::ConflictingCrossKeyDividend` (silently dropping or doubling an event would corrupt every earlier cumulative factor). +3. **Conservative `known_at` & point-in-time / vault-fence policy:** + - Stamps every curated row with `known_at_micros = session_close::et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / `America/Toronto`: `21:00 UTC` in EST, `20:00 UTC` in EDT) because `qmSplits` / `qmDividends` adj builder inputs carry no announcement timestamp. + - Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns `CurateAdjError::ExDateOutOfRange` naming `(listing_id, ex_date)` without panicking (dropping a row would break the cumulative chain). + - **Retrospective vs. Point-in-Time snapshots:** because `cum_split_factor` and `cum_total_factor` are right-to-left suffix products, later splits and dividends are embedded in earlier rows. `curate_adj_factors` / `curate_and_write_adj_factors` explicitly tag their output as `AdjSnapshotKind::RetrospectiveSnapshot` — slicing a retrospective snapshot with a bare `known_at <= as_of` filter would still leak future or held-out vault actions into earlier bars. + - **Point-in-time & Vault fencing:** `curate_adj_factors_as_of` / `curate_and_write_adj_factors_as_of` accept an `AdjPointInTimeFence { as_of_micros, vault_cutoff_micros }` (`known_at <= as_of_micros` inclusive and `known_at < vault_cutoff_micros` strictly exclusive, matching `design/DATA-CONTRACTS.md` §4) and fence mapped source events *before* compaction and compounding, tagging the output as `AdjSnapshotKind::PointInTimeFenced(fence)`. Appending any future or vault-held action leaves earlier rows and `adj_factors_for_bar` reads bitwise identical. + - **Persisted Parquet footer metadata & verified readers:** `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` publish `/adj_factors/part.parquet` in a single atomic file commit (one dataset lock, exclusive staging, live-preserving backup, single `rename`) embedding `stock_bot.adj_factors.{format_version, snapshot_kind, as_of_micros, vault_cutoff_micros, rows_written, snapshot_checksum}` directly in the Parquet footer `key_value_metadata` (where `snapshot_checksum` binds `format_version`, `snapshot_kind` / exact fence, row count, and all 8 columns of every row). When a run produces 0 rows (e.g. a fence excludes every event), an explicit 0-row Zstd Parquet file with the contract schema and embedded footer metadata is atomically published so any previous `part.parquet` is superseded rather than left stale. `read_adj_factors_dataset_as_of` requires a non-retrospective fence, fails closed on missing/corrupt/unsupported footer metadata, rejects retrospective snapshots (`RetrospectiveSnapshotRejected`) or any mismatched fence (`IncompatibleFence`), checks every row's `known_at` against the fence (`RowOutsideFence`), verifies per-listing `cum_split_factor` reverse suffix products, and verifies the bound `snapshot_checksum` (`SnapshotIntegrityMismatch`). +4. **Accounting & error handling:** + - Exact conservation invariants in `CurateAdjFactorsStats`: + - `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in` + - `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in` + - `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed` + - `rows_out == builder.rows_out` and `listings_out == builder.keys_out` + - For `AdjSnapshotKind::RetrospectiveSnapshot`, `splits_dropped_fenced == 0` and `dividends_dropped_fenced == 0`. + - `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` run curation before touching `out_dir`, so any `CurateAdjError` leaves `out_dir` untouched and publishes no `adj_factors/part.parquet` (surfacing via `CurateAdjWriteError::{Curate, Parquet}`). +5. **Deferred items:** + - Live MongoDB cursor streaming and BSON decoders for `qmSplits` / `qmDividends` + - PostgreSQL `provider_mapping` preload + - Sourcing `DividendEvent.prev_close` from `bars_1d` (currently supplied by the caller) + - `rayon` parallel sharding and end-to-end `curate` CLI command + +### `bench-curate-adj` + +Fixed-seed (`std`-only SplitMix64) benchmark over `1,000,000` (default) or `[events]` source-keyed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys spanning `1990..=2025` (single-range keys, ticker-rename pairs, ticker-reuse keys with an H2-2018 gap, unmapped keys, and explicit bitwise-identical alias keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet `write_adj_factors_dataset` into a temp directory with footer row-count verification and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-adj [events] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a1afe7e6b`): `cargo run --release -p curate-etl --offline -- bench-curate-adj` + +- Input: `events=1000000`, `splits=40221`, `dividends=959779`, `keys=20000` +- Builder: `rows_out=946414`, `keys_out=19500`, `split_noops=1938`, `zero_div=9234`, `missing_prev_close=18458`, `currency_mismatch=18461`, `not_below_prev_close=9193` +- Output: `rows_out=946414` (`94.64%` retained), `listings_out=19500`, `files=1`, `row_groups=1`, `bytes=11872037`, `read_back_rows=946414` +- Curation stats: `splits_unmapped=1486`, `divs_unmapped=34220`, `splits_coll_collapsed=213`, `divs_coll_collapsed=4717`, `coll_collapsed=4930` +- Run 1: + - Stage (in-memory): `elapsed=930.92 ms`, `throughput=1074206 events/s`, `latency=930.92 ns/event`, `checksum=0x024ec73a1afe7e6b` + - Parquet write: `elapsed=262.42 ms`, `throughput=3606439 rows/s` + - Combined (stage → Parquet): `elapsed=1193.34 ms`, `throughput=837982 events/s` +- Run 2: + - Stage (in-memory): `elapsed=933.02 ms`, `throughput=1071785 events/s`, `latency=933.02 ns/event`, `checksum=0x024ec73a1afe7e6b` + - Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s` + - Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s` + ## `corporate_actions` Curation Stage (`M1.2u`) `curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`. diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 6e4806de..532b34b6 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; use bson::oid::ObjectId; -use bson::raw::{cstr, RawDocumentBuf}; +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; use bson::DateTime; use parquet::errors::ParquetError; use parquet::file::reader::{FileReader, SerializedFileReader}; @@ -17,6 +17,12 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; +use crate::bson_qm_actions::{ + decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, +}; +use crate::bson_stream::{ + decode_eod_price_chunks, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, +}; use crate::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, @@ -79,6 +85,8 @@ pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000; /// + `known_at` (8) + `known_at_source` (~13) = 72 bytes. pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000; +pub const DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS: usize = 1_000_000; +pub const DEFAULT_BSON_STREAM_BENCH_ROWS: usize = 2_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; @@ -104,6 +112,7 @@ const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4; const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D; const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F; const BSON_EOD_PRICES_BENCH_SEED: u64 = 0x570C_4B07_B504_E0D1; +const BSON_QM_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_B504_AC71; const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; @@ -3615,28 +3624,7 @@ pub struct BsonEodPricesBenchReport { pub stats: BsonEodDecodeStats, } -/// Runs the fixed-seed raw BSON `eodPrices` zero-copy decode benchmark for `rows` synthetic -/// documents. -/// -/// Pre-encodes `rows` realistic `eodPrices` documents (including extra metadata fields `_id`, -/// `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, -/// `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON -/// `DateTime` dates, and ~0.5% deterministic rejected rows) into one contiguous length-prefixed -/// `Vec` buffer up front, then times decode-only via [`decode_eod_price_buffer`]. -pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { - if rows == 0 { - return BsonEodPricesBenchReport { - rows: 0, - bytes: 0, - elapsed_ms: 0.0, - rows_per_sec: 0.0, - mb_per_sec: 0.0, - ns_per_row: 0.0, - checksum: 0, - stats: BsonEodDecodeStats::default(), - }; - } - +fn build_bson_eod_prices_bench_buffer(rows: usize) -> Vec { const SYMBOL_POOL: usize = 2_000; const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; const PROVIDER_EXCHANGES: [&str; 4] = ["US", "US", "TO", "V"]; @@ -3750,6 +3738,33 @@ pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { buffer.extend_from_slice(doc.as_bytes()); } + buffer +} + +/// Runs the fixed-seed raw BSON `eodPrices` zero-copy decode benchmark for `rows` synthetic +/// documents. +/// +/// Pre-encodes `rows` realistic `eodPrices` documents (including extra metadata fields `_id`, +/// `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `created_at`, +/// `updated_at`, mixed `Double`/`Int32`/`Int64` numerics, `YYYY-MM-DD` strings + ~5% BSON +/// `DateTime` dates, and ~0.5% deterministic rejected rows) into one contiguous length-prefixed +/// `Vec` buffer up front, then times decode-only via [`decode_eod_price_buffer`]. +pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { + if rows == 0 { + return BsonEodPricesBenchReport { + rows: 0, + bytes: 0, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + ns_per_row: 0.0, + checksum: 0, + stats: BsonEodDecodeStats::default(), + }; + } + + let buffer = build_bson_eod_prices_bench_buffer(rows); + let bytes = buffer.len(); let mut hash = 0u64; let mut err_hash = 0u64; @@ -3792,6 +3807,456 @@ pub fn run_bson_eod_prices_benchmark(rows: usize) -> BsonEodPricesBenchReport { } } +/// Summary metrics produced by [`run_bson_stream_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BsonStreamBenchReport { + pub rows: usize, + pub bytes: usize, + pub buffer_elapsed_ms: f64, + pub buffer_rows_per_sec: f64, + pub buffer_mib_per_sec: f64, + pub stream_elapsed_ms: f64, + pub stream_rows_per_sec: f64, + pub stream_mib_per_sec: f64, + pub stream_to_buffer_ratio: f64, + pub peak_buffer_capacity: usize, + pub checksum: u64, + pub stats: BsonEodDecodeStats, +} + +/// Deterministic reader returning irregular prime/odd short reads across ~257 B..128 KiB so every +/// read straddles BSON document and 4-byte length-prefix boundaries. +struct IrregularShortReader<'a> { + data: &'a [u8], + pos: usize, + step_idx: usize, +} + +impl<'a> IrregularShortReader<'a> { + const STEPS: [usize; 10] = [ + 257, 1_021, 4_093, 16_381, 65_521, 131_071, 521, 8_191, 32_749, 49_157, + ]; + + fn new(data: &'a [u8]) -> Self { + Self { + data, + pos: 0, + step_idx: 0, + } + } +} + +impl io::Read for IrregularShortReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let step = Self::STEPS[self.step_idx % Self::STEPS.len()]; + self.step_idx = self.step_idx.wrapping_add(1); + let take = remaining.min(step).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +/// Runs the fixed-seed raw BSON streaming vs in-memory buffer decode benchmark for `rows` +/// synthetic `eodPrices` documents. +/// +/// Reuses the identical fixed-seed synthetic buffer from [`run_bson_eod_prices_benchmark`], decodes +/// once via [`decode_eod_price_buffer`] (baseline) and once via [`RawBsonChunkReader`] + +/// [`decode_eod_price_chunks`] over irregular short reads, asserts identical stats and row+error +/// checksum, and reports throughput and peak buffer capacity. +pub fn run_bson_stream_benchmark(rows: usize) -> Result { + if rows == 0 { + return Ok(BsonStreamBenchReport { + rows: 0, + bytes: 0, + buffer_elapsed_ms: 0.0, + buffer_rows_per_sec: 0.0, + buffer_mib_per_sec: 0.0, + stream_elapsed_ms: 0.0, + stream_rows_per_sec: 0.0, + stream_mib_per_sec: 0.0, + stream_to_buffer_ratio: 0.0, + peak_buffer_capacity: 0, + checksum: 0, + stats: BsonEodDecodeStats::default(), + }); + } + + let buffer = build_bson_eod_prices_bench_buffer(rows); + let bytes = buffer.len(); + + // Baseline: in-memory buffer decode. + let mut buf_hash = 0u64; + let mut buf_err_hash = 0u64; + let buf_start = Instant::now(); + let buf_stats = decode_eod_price_buffer( + &buffer, + |bar| { + buf_hash = mix_bytes(buf_hash, bar.eod_search_code.as_bytes()); + buf_hash = mix_u64(buf_hash, bar.session_date as u64); + buf_hash = mix_u64(buf_hash, bar.open.to_bits()); + buf_hash = mix_u64(buf_hash, bar.high.to_bits()); + buf_hash = mix_u64(buf_hash, bar.low.to_bits()); + buf_hash = mix_u64(buf_hash, bar.close.to_bits()); + buf_hash = mix_u64(buf_hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + buf_err_hash = mix_u64(buf_err_hash, offset as u64 ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + ); + let buf_elapsed_secs = buf_start.elapsed().as_secs_f64(); + let buf_checksum = black_box(buf_hash ^ buf_err_hash); + + // Streamed decode over irregular short reads using default bounded chunk capacity. + let mut chunk_reader = RawBsonChunkReader::with_options( + IrregularShortReader::new(&buffer), + BsonStreamOptions::default(), + )?; + let mut stream_hash = 0u64; + let mut stream_err_hash = 0u64; + let stream_start = Instant::now(); + let stream_stats = decode_eod_price_chunks( + &mut chunk_reader, + |bar| { + stream_hash = mix_bytes(stream_hash, bar.eod_search_code.as_bytes()); + stream_hash = mix_u64(stream_hash, bar.session_date as u64); + stream_hash = mix_u64(stream_hash, bar.open.to_bits()); + stream_hash = mix_u64(stream_hash, bar.high.to_bits()); + stream_hash = mix_u64(stream_hash, bar.low.to_bits()); + stream_hash = mix_u64(stream_hash, bar.close.to_bits()); + stream_hash = mix_u64(stream_hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + stream_err_hash = mix_u64(stream_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + )?; + let stream_elapsed_secs = stream_start.elapsed().as_secs_f64(); + let stream_checksum = black_box(stream_hash ^ stream_err_hash); + let peak_buffer_capacity = chunk_reader.buffer_capacity(); + + assert_eq!( + stream_stats, buf_stats, + "stream decode stats must match in-memory buffer decode" + ); + assert_eq!( + stream_checksum, buf_checksum, + "stream decode checksum must match in-memory buffer decode" + ); + + let buffer_elapsed_ms = buf_elapsed_secs * 1_000.0; + let (buffer_rows_per_sec, _) = compute_rates(rows, buf_elapsed_secs); + let buffer_mib_per_sec = if buf_elapsed_secs > 0.0 && buf_elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / buf_elapsed_secs + } else { + 0.0 + }; + + let stream_elapsed_ms = stream_elapsed_secs * 1_000.0; + let (stream_rows_per_sec, _) = compute_rates(rows, stream_elapsed_secs); + let stream_mib_per_sec = if stream_elapsed_secs > 0.0 && stream_elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / stream_elapsed_secs + } else { + 0.0 + }; + + let stream_to_buffer_ratio = if buffer_rows_per_sec > 0.0 { + stream_rows_per_sec / buffer_rows_per_sec + } else { + 0.0 + }; + + Ok(BsonStreamBenchReport { + rows, + bytes, + buffer_elapsed_ms, + buffer_rows_per_sec, + buffer_mib_per_sec, + stream_elapsed_ms, + stream_rows_per_sec, + stream_mib_per_sec, + stream_to_buffer_ratio, + peak_buffer_capacity, + checksum: stream_checksum, + stats: stream_stats, + }) +} + +/// Summary metrics produced by [`run_bson_qm_actions_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BsonQmActionsBenchReport { + pub rows: usize, + pub split_rows: usize, + pub dividend_rows: usize, + pub bytes: usize, + pub elapsed_ms: f64, + pub docs_per_sec: f64, + pub mb_per_sec: f64, + pub ns_per_doc: f64, + pub checksum: u64, + pub split_stats: BsonQmActionDecodeStats, + pub dividend_stats: BsonQmActionDecodeStats, +} + +/// Runs the fixed-seed raw BSON `qmSplits` + `qmDividends` zero-copy decode benchmark for `rows` +/// synthetic documents (~4% splits, ~96% dividends). +/// +/// Pre-encodes realistic QuoteMedia documents (including extra metadata `_id`, `symbol`, +/// `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` +/// present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, +/// ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) into two contiguous +/// length-prefixed buffers, then times decode-only via [`decode_qm_split_buffer`] and +/// [`decode_qm_dividend_buffer`] and asserts exact stats reconciliation. +pub fn run_bson_qm_actions_benchmark(rows: usize) -> BsonQmActionsBenchReport { + if rows == 0 { + return BsonQmActionsBenchReport { + rows: 0, + split_rows: 0, + dividend_rows: 0, + bytes: 0, + elapsed_ms: 0.0, + docs_per_sec: 0.0, + mb_per_sec: 0.0, + ns_per_doc: 0.0, + checksum: 0, + split_stats: BsonQmActionDecodeStats::default(), + dividend_stats: BsonQmActionDecodeStats::default(), + }; + } + + const SYMBOL_POOL: usize = 2_000; + const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; + const CURRENCIES: [&str; 4] = ["USD", "USD", "CAD", "CAD"]; + const MILLIS_PER_DAY: i64 = 86_400_000; + + let min_date = ymd_to_epoch_days(2005, 1, 3).unwrap_or(12_786); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let mut date_days: Vec = Vec::with_capacity(5_600); + let mut date_strings: Vec = Vec::with_capacity(5_600); + for d in min_date..=max_date { + let dow = (d + 4).rem_euclid(7); + if dow == 0 || dow == 6 { + continue; + } + let (y, m, day) = epoch_days_to_ymd(d); + date_days.push(d); + date_strings.push(format!("{y:04}-{m:02}-{day:02}")); + } + + let symbols: Vec<(String, String, &'static str, &'static str)> = (0..SYMBOL_POOL) + .map(|i| { + let ex_idx = i % EXCHANGES.len(); + let sym = format!("QM{i:04}"); + let code = if ex_idx >= 2 { + format!("{sym}:CA") + } else { + sym.clone() + }; + (sym, code, EXCHANGES[ex_idx], CURRENCIES[ex_idx]) + }) + .collect(); + + let mut rng = SplitMix64::new(BSON_QM_ACTIONS_BENCH_SEED); + let mut split_rows = 0usize; + let mut dividend_rows = 0usize; + let mut split_buf: Vec = Vec::with_capacity((rows / 20).saturating_mul(224)); + let mut dividend_buf: Vec = Vec::with_capacity(rows.saturating_mul(256)); + + for i in 0..rows { + let is_split = (rng.next_u64() % 100) < 4; + let sym_idx = (rng.next_u64() as usize) % symbols.len(); + let (ref symbol, ref code, exchange, currency) = symbols[sym_idx]; + let date_idx = (rng.next_u64() as usize) % date_days.len(); + let epoch_day = date_days[date_idx]; + let date_str = &date_strings[date_idx]; + let decl_idx = date_idx.saturating_sub(15); + let decl_day = date_days[decl_idx]; + let decl_str = &date_strings[decl_idx]; + + let mut oid_bytes = [0u8; 12]; + let seq = (i as u64).to_be_bytes(); + oid_bytes[4..12].copy_from_slice(&seq); + + let report_ms = i64::from(epoch_day) * MILLIS_PER_DAY; + let created_ms = report_ms + 79_200_000; + let updated_ms = created_ms + 60_000; + + let bad_roll = rng.next_u64() % 1_000; + let date_as_dt = (rng.next_u64() % 20) == 0; + let decl_roll = rng.next_u64() % 1_000; + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); + doc.append(cstr!("symbol"), symbol.as_str()); + doc.append(cstr!("exchange"), exchange); + doc.append(cstr!("qmSearchCode"), code.as_str()); + doc.append(cstr!("reportDate"), DateTime::from_millis(report_ms)); + + if bad_roll == 0 { + doc.append(cstr!("date"), "2023-02-29"); + } else if date_as_dt { + doc.append(cstr!("date"), DateTime::from_millis(report_ms)); + } else { + doc.append(cstr!("date"), date_str.as_str()); + } + + if is_split { + split_rows += 1; + // ~30% declared present, ~20% Null, ~50% missing. + if decl_roll < 300 { + if date_as_dt { + doc.append( + cstr!("declared"), + DateTime::from_millis(i64::from(decl_day) * MILLIS_PER_DAY), + ); + } else { + doc.append(cstr!("declared"), decl_str.as_str()); + } + } else if decl_roll < 500 { + doc.append(cstr!("declared"), RawBsonRef::Null); + } + + if bad_roll == 1 { + doc.append(cstr!("splitratio"), "2.0"); + } else if bad_roll == 2 { + doc.append(cstr!("splitratio"), 0.0_f64); + } else if bad_roll != 3 && bad_roll != 4 { + if (rng.next_u64() % 1_000) < 15 { + match i % 3 { + 0 => doc.append(cstr!("splitratio"), 1.0_f64), + 1 => doc.append(cstr!("splitratio"), 1_i32), + _ => doc.append(cstr!("splitratio"), 1_i64), + } + } else { + let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]; + if i % 5 == 0 && ratio >= 1.0 { + doc.append(cstr!("splitratio"), ratio as i32); + } else if i % 7 == 0 && ratio >= 1.0 { + doc.append(cstr!("splitratio"), ratio as i64); + } else { + doc.append(cstr!("splitratio"), ratio); + } + } + } + + doc.append(cstr!("usdFxRate"), 1_i32); + doc.append(cstr!("created_at"), DateTime::from_millis(created_ms)); + doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms)); + split_buf.extend_from_slice(doc.as_bytes()); + } else { + dividend_rows += 1; + // ~82% declared present, ~9% Null, ~9% missing. + if decl_roll < 820 { + if date_as_dt { + doc.append( + cstr!("declared"), + DateTime::from_millis(i64::from(decl_day) * MILLIS_PER_DAY), + ); + } else { + doc.append(cstr!("declared"), decl_str.as_str()); + } + } else if decl_roll < 910 { + doc.append(cstr!("declared"), RawBsonRef::Null); + } + + let cents = (rng.next_u64() % 400) as i64; + if bad_roll == 1 { + doc.append(cstr!("amount"), "0.25"); + } else if bad_roll == 2 { + doc.append(cstr!("amount"), -0.25_f64); + } else if bad_roll != 3 { + match i % 10 { + 0 => doc.append(cstr!("amount"), (cents / 100) as i32), + 1 => doc.append(cstr!("amount"), cents / 100), + _ => doc.append(cstr!("amount"), cents as f64 / 100.0), + } + } + + if bad_roll != 4 { + doc.append(cstr!("currency"), currency); + } + doc.append(cstr!("usdFxRate"), 1_i32); + doc.append(cstr!("created_at"), DateTime::from_millis(created_ms)); + doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms)); + dividend_buf.extend_from_slice(doc.as_bytes()); + } + } + + let bytes = split_buf.len() + dividend_buf.len(); + let mut hash = 0u64; + let mut err_hash = 0u64; + + let start = Instant::now(); + let split_stats = decode_qm_split_buffer( + &split_buf, + |s| { + hash = mix_bytes(hash, s.qm_search_code.as_bytes()); + hash = mix_u64(hash, s.ex_date as u64); + hash = mix_u64(hash, s.ratio.to_bits()); + hash = mix_u64(hash, s.declared_date.unwrap_or(i32::MIN) as u64); + }, + |offset, _err| { + err_hash = mix_u64(err_hash, offset as u64 ^ 0x5171_DEAD_BEEF_0001u64); + }, + ); + let dividend_stats = decode_qm_dividend_buffer( + ÷nd_buf, + |d| { + hash = mix_bytes(hash, d.qm_search_code.as_bytes()); + hash = mix_u64(hash, d.ex_date as u64); + hash = mix_u64(hash, d.cash.to_bits()); + hash = mix_bytes(hash, d.currency.as_bytes()); + hash = mix_u64(hash, d.declared_date.unwrap_or(i32::MIN) as u64); + }, + |offset, _err| { + err_hash = mix_u64(err_hash, offset as u64 ^ 0xD171_DEAD_BEEF_0002u64); + }, + ); + let elapsed_secs = start.elapsed().as_secs_f64(); + + assert_eq!( + split_stats.decoded + split_stats.rejected_total(), + split_stats.docs_in, + "qmSplits decode stats must reconcile" + ); + assert_eq!( + dividend_stats.decoded + dividend_stats.rejected_total(), + dividend_stats.docs_in, + "qmDividends decode stats must reconcile" + ); + assert_eq!( + split_stats.docs_in + dividend_stats.docs_in, + rows, + "total decoded+rejected docs must equal input rows" + ); + + let elapsed_ms = elapsed_secs * 1_000.0; + let (docs_per_sec, ns_per_doc) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let checksum = black_box(hash ^ err_hash); + + BsonQmActionsBenchReport { + rows, + split_rows, + dividend_rows, + bytes, + elapsed_ms, + docs_per_sec, + mb_per_sec, + ns_per_doc, + checksum, + split_stats, + dividend_stats, + } +} + pub const DEFAULT_CURATE_BARS_BENCH_ROWS: usize = 2_000_000; pub const EOD_PRICES_FULL_ROW_COUNT: f64 = 846_000_000.0; const CURATE_BARS_BENCH_SEED: u64 = 0x570C_4B07_C04A_BA45; @@ -5385,6 +5850,348 @@ pub fn run_curate_fx_benchmark( Ok(report) } +pub const DEFAULT_CURATE_ADJ_BENCH_EVENTS: usize = 1_000_000; +const CURATE_ADJ_BENCH_SEED: u64 = 0x570C_4B07_C04A_AD7F; +const CURATE_ADJ_BENCH_KEY_COUNT: usize = 20_000; + +/// Summary metrics produced by [`run_curate_adj_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateAdjBenchReport { + pub events: usize, + pub splits_in: usize, + pub dividends_in: usize, + pub key_count: usize, + pub rows_out: usize, + pub listings_out: usize, + pub stage_elapsed_ms: f64, + pub stage_events_per_sec: f64, + pub stage_ns_per_event: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_events_per_sec: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_adj::CurateAdjFactorsStats, +} + +fn run_curate_adj_benchmark_tracked( + events: usize, +) -> Result<(CurateAdjBenchReport, PathBuf), crate::curate_adj::CurateAdjWriteError> { + use crate::curate_adj::{curate_adj_factors, CurateAdjFactorsStats, CurateAdjWriteError}; + + let temp = + BenchTempDir::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-curate-adj") + .map_err(|(path, source)| { + CurateAdjWriteError::Parquet(ParquetAdjError::Io { path, source }) + })?; + let temp_path = temp.path.clone(); + + if events == 0 { + let empty_mapping = ProviderMappingTable::default(); + let curated = curate_adj_factors( + &empty_mapping, + "qm", + std::iter::empty::<(String, SplitEvent)>(), + std::iter::empty::<(String, DividendEvent)>(), + )?; + let write_stats = write_adj_factors_dataset( + &temp.path, + &curated.rows, + AdjFactorsWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_adj_row_count(&temp.path, 0)?; + drop(temp); + return Ok(( + CurateAdjBenchReport { + events: 0, + splits_in: 0, + dividends_in: 0, + key_count: CURATE_ADJ_BENCH_KEY_COUNT, + rows_out: 0, + listings_out: 0, + stage_elapsed_ms: 0.0, + stage_events_per_sec: 0.0, + stage_ns_per_event: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_events_per_sec: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateAdjFactorsStats::default(), + }, + temp_path, + )); + } + + let min_date = ymd_to_epoch_days(1990, 1, 1).expect("valid min_date"); + let max_date = ymd_to_epoch_days(2025, 12, 31).expect("valid max_date"); + let date_span = (max_date - min_date + 1) as u64; // 13,149 days + let rename_cutoff = ymd_to_epoch_days(2014, 12, 31).expect("valid rename_cutoff"); + let reuse_end_old = ymd_to_epoch_days(2018, 6, 30).expect("valid reuse_end_old"); + let reuse_start_new = ymd_to_epoch_days(2019, 1, 1).expect("valid reuse_start_new"); + + const SINGLE_RANGE_END: usize = 18_000; + const RENAME_PAIRS: usize = 300; + const RENAME_END: usize = SINGLE_RANGE_END + RENAME_PAIRS * 2; // 18_600 + const REUSE_COUNT: usize = 600; + const REUSE_END: usize = RENAME_END + REUSE_COUNT; // 19_200 + const UNMAPPED_COUNT: usize = 400; + const ORDINARY_KEY_COUNT: usize = REUSE_END + UNMAPPED_COUNT; // 19_600 + const ALIAS_COUNT: usize = CURATE_ADJ_BENCH_KEY_COUNT - ORDINARY_KEY_COUNT; // 400 + + let keys: Vec = (0..CURATE_ADJ_BENCH_KEY_COUNT) + .map(|i| format!("QM{i:05}")) + .collect(); + + let mut mapping_rows: Vec = + Vec::with_capacity(CURATE_ADJ_BENCH_KEY_COUNT + REUSE_COUNT); + + // 1. Single-range keys [0..18_000) -> listing_id 1..=18_000 + for (i, key) in keys.iter().enumerate().take(SINGLE_RANGE_END) { + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: key.clone(), + valid_from: min_date, + valid_to: None, + listing_id: (i as i32) + 1, + }); + } + + // 2. Ticker-rename pairs [18_000..18_600) -> 300 listings (18_001..=18_300) + let mut next_listing_id = (SINGLE_RANGE_END as i32) + 1; + for p in 0..RENAME_PAIRS { + let old_idx = SINGLE_RANGE_END + p * 2; + let new_idx = old_idx + 1; + let lid = next_listing_id; + next_listing_id += 1; + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: keys[old_idx].clone(), + valid_from: min_date, + valid_to: Some(rename_cutoff), + listing_id: lid, + }); + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: keys[new_idx].clone(), + valid_from: rename_cutoff + 1, + valid_to: None, + listing_id: lid, + }); + } + + // 3. Ticker-reuse keys [18_600..19_200) -> two non-overlapping ranges with H2-2018 gap + for r in 0..REUSE_COUNT { + let key_idx = RENAME_END + r; + let old_lid = next_listing_id; + let new_lid = next_listing_id + 1; + next_listing_id += 2; + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: keys[key_idx].clone(), + valid_from: min_date, + valid_to: Some(reuse_end_old), + listing_id: old_lid, + }); + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: keys[key_idx].clone(), + valid_from: reuse_start_new, + valid_to: None, + listing_id: new_lid, + }); + } + + // 4. Unmapped keys [19_200..19_600) intentionally have no mapping rows. + // 5. Alias keys [19_600..20_000) mirror keys [0..400) -> listing_id 1..=400. + for a in 0..ALIAS_COUNT { + mapping_rows.push(ProviderMappingRow { + source: "qm".to_string(), + source_id: keys[ORDINARY_KEY_COUNT + a].clone(), + valid_from: min_date, + valid_to: None, + listing_id: (a as i32) + 1, + }); + } + + let provider_mapping = + ProviderMappingTable::from_rows(mapping_rows).expect("valid curate_adj bench mapping"); + + let mut rng = SplitMix64::new(CURATE_ADJ_BENCH_SEED); + let mut splits: Vec<(String, SplitEvent)> = Vec::with_capacity(events / 20); + let mut dividends: Vec<(String, DividendEvent)> = Vec::with_capacity(events); + // Per-key unique-date step counter for keys [0..ALIAS_COUNT) so alias clones never collide + // with a second differing event on the same (listing_id, ex_date). + let mut alias_date_steps = [0u64; ALIAS_COUNT]; + let mut emitted = 0usize; + + while emitted < events { + let mut key_idx = (rng.next_u64() as usize) % ORDINARY_KEY_COUNT; + let (ex_date, emit_alias) = if key_idx < ALIAS_COUNT { + let step = alias_date_steps[key_idx]; + if step < date_span { + alias_date_steps[key_idx] = step + 1; + // 197 is prime and coprime to 13,149, so every step yields a unique ex_date. + let offset = (step * 197 + (key_idx as u64) * 31) % date_span; + let dup = emitted + 1 < events && (rng.next_u64() % 4) == 0; + (min_date + offset as i32, dup) + } else { + key_idx = ALIAS_COUNT + (key_idx % (ORDINARY_KEY_COUNT - ALIAS_COUNT)); + (min_date + (rng.next_u64() % date_span) as i32, false) + } + } else { + (min_date + (rng.next_u64() % date_span) as i32, false) + }; + + let kind_roll = rng.next_u64() % 100; + if kind_roll < 4 { + let ratio_roll = rng.next_u64() % 20; + let ratio = if ratio_roll == 0 { + 1.0 + } else { + SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()] + }; + let ev = SplitEvent { ex_date, ratio }; + splits.push((keys[key_idx].clone(), ev)); + emitted += 1; + if emit_alias { + splits.push((keys[ORDINARY_KEY_COUNT + key_idx].clone(), ev)); + emitted += 1; + } + } else { + let (home_curr, alt_curr) = if key_idx % 5 == 0 { + ("CAD", "USD") + } else { + ("USD", "CAD") + }; + let fallback_roll = rng.next_u64() % 100; + let cash = if fallback_roll == 5 { + 0.0 + } else { + ((rng.next_u64() % 150) + 5) as f64 * 0.01 + }; + let (prev_close, prev_close_currency) = match fallback_roll { + 0 | 1 => (None, Some(home_curr.to_string())), + 2 | 3 => ( + Some(20.0 + (rng.next_u64() % 200) as f64), + Some(alt_curr.to_string()), + ), + 4 => (Some(cash * 0.5), Some(home_curr.to_string())), + _ => ( + Some(20.0 + (rng.next_u64() % 200) as f64), + Some(home_curr.to_string()), + ), + }; + let ev = DividendEvent { + ex_date, + cash, + currency: home_curr.to_string(), + prev_close, + prev_close_currency, + }; + if emit_alias { + dividends.push((keys[ORDINARY_KEY_COUNT + key_idx].clone(), ev.clone())); + emitted += 1; + } + dividends.push((keys[key_idx].clone(), ev)); + emitted += 1; + } + } + + let splits_in = splits.len(); + let dividends_in = dividends.len(); + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_adj_factors(&provider_mapping, "qm", splits, dividends)?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_u64(hash, row.listing_id as u64); + hash = mix_u64(hash, row.ex_date as u64); + hash = mix_u64(hash, row.split_factor.to_bits()); + hash = mix_u64(hash, row.div_cash.to_bits()); + match row.div_currency.as_deref() { + Some(curr) => { + hash = mix_u64(hash, 1); + hash = mix_str_u64(hash, curr); + } + None => { + hash = mix_u64(hash, 0); + } + } + hash = mix_u64(hash, row.cum_split_factor.to_bits()); + hash = mix_u64(hash, row.cum_total_factor.to_bits()); + hash = mix_u64(hash, row.known_at_micros as u64); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = write_adj_factors_dataset( + &temp.path, + &curated.rows, + AdjFactorsWriteOptions::default(), + )?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_adj_row_count(&temp.path, curated.rows.len())?; + + let (stage_events_per_sec, stage_ns_per_event) = compute_rates(events, stage_elapsed_secs); + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_events_per_sec, _) = compute_rates(events, total_elapsed_secs); + + let report = CurateAdjBenchReport { + events, + splits_in, + dividends_in, + key_count: CURATE_ADJ_BENCH_KEY_COUNT, + rows_out: curated.stats.rows_out, + listings_out: curated.stats.listings_out, + stage_elapsed_ms, + stage_events_per_sec, + stage_ns_per_event, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_events_per_sec, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `adj_factors` curation stage + Zstd Parquet write benchmark for `events` +/// mixed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys +/// (single-range, ticker-rename, ticker-reuse with gap, unmapped, and bitwise-identical alias +/// keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet +/// `write_adj_factors_dataset` into a temp directory removed on drop. +pub fn run_curate_adj_benchmark( + events: usize, +) -> Result { + let (report, _) = run_curate_adj_benchmark_tracked(events)?; + Ok(report) +} + pub const DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 520_000; const CURATE_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C04A_AC72; const CURATE_CORPORATE_ACTIONS_BENCH_KEY_COUNT: usize = 20_000; @@ -6680,6 +7487,110 @@ mod tests { assert_eq!(report.stats, BsonEodDecodeStats::default()); } + #[test] + fn bson_stream_benchmark_small_run_matches_buffer_and_stream_helper() { + let a = run_bson_stream_benchmark(20_000).expect("stream bench must succeed"); + let b = run_bson_stream_benchmark(20_000).expect("stream bench must be deterministic"); + + assert_eq!(a.rows, 20_000); + assert_eq!(a.bytes, b.bytes); + assert!(a.bytes > 0); + assert_eq!(a.checksum, b.checksum); + assert_eq!(a.stats, b.stats); + assert_eq!(a.stats.docs_in, 20_000); + assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in); + assert_eq!( + a.peak_buffer_capacity, + crate::bson_stream::DEFAULT_CHUNK_CAPACITY_BYTES + ); + assert!(a.buffer_rows_per_sec.is_finite() && a.buffer_rows_per_sec >= 0.0); + assert!(a.stream_rows_per_sec.is_finite() && a.stream_rows_per_sec >= 0.0); + assert!(a.stream_to_buffer_ratio.is_finite() && a.stream_to_buffer_ratio >= 0.0); + + // Verify decode_eod_price_stream produces identical stats and checksum on the same bytes. + let buf = build_bson_eod_prices_bench_buffer(20_000); + let mut h = 0u64; + let mut eh = 0u64; + let s = crate::bson_stream::decode_eod_price_stream( + IrregularShortReader::new(&buf), + BsonStreamOptions::default(), + |bar| { + h = mix_bytes(h, bar.eod_search_code.as_bytes()); + h = mix_u64(h, bar.session_date as u64); + h = mix_u64(h, bar.open.to_bits()); + h = mix_u64(h, bar.high.to_bits()); + h = mix_u64(h, bar.low.to_bits()); + h = mix_u64(h, bar.close.to_bits()); + h = mix_u64(h, bar.adj_volume.to_bits()); + }, + |offset, _err| { + eh = mix_u64(eh, offset ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + ) + .expect("decode_eod_price_stream must succeed"); + assert_eq!(s, a.stats); + assert_eq!(h ^ eh, a.checksum); + } + + #[test] + fn bson_stream_benchmark_zero_rows_handles_cleanly() { + let report = run_bson_stream_benchmark(0).expect("zero-row stream bench must succeed"); + assert_eq!(report.rows, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.buffer_elapsed_ms, 0.0); + assert_eq!(report.stream_elapsed_ms, 0.0); + assert_eq!(report.stream_to_buffer_ratio, 0.0); + assert_eq!(report.peak_buffer_capacity, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stats, BsonEodDecodeStats::default()); + } + + #[test] + fn bson_qm_actions_benchmark_small_run_is_deterministic() { + let a = run_bson_qm_actions_benchmark(20_000); + let b = run_bson_qm_actions_benchmark(20_000); + + assert_eq!(a.rows, 20_000); + assert_eq!(a.split_rows + a.dividend_rows, 20_000); + assert!(a.split_rows > 0 && a.dividend_rows > 0); + assert_eq!(a.bytes, b.bytes); + assert!(a.bytes > 0); + assert_eq!(a.checksum, b.checksum); + assert_eq!(a.split_stats, b.split_stats); + assert_eq!(a.dividend_stats, b.dividend_stats); + assert_eq!(a.split_stats.docs_in, a.split_rows); + assert_eq!(a.dividend_stats.docs_in, a.dividend_rows); + assert_eq!( + a.split_stats.decoded + a.split_stats.rejected_total(), + a.split_stats.docs_in + ); + assert_eq!( + a.dividend_stats.decoded + a.dividend_stats.rejected_total(), + a.dividend_stats.docs_in + ); + assert!(a.split_stats.split_noop_ratio_one > 0); + assert!(a.dividend_stats.rejected_total() > 0); + assert!(a.docs_per_sec.is_finite() && a.docs_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.ns_per_doc.is_finite() && a.ns_per_doc >= 0.0); + } + + #[test] + fn bson_qm_actions_benchmark_zero_rows_handles_cleanly() { + let report = run_bson_qm_actions_benchmark(0); + assert_eq!(report.rows, 0); + assert_eq!(report.split_rows, 0); + assert_eq!(report.dividend_rows, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.docs_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.ns_per_doc, 0.0); + assert_eq!(report.checksum, 0); + assert_eq!(report.split_stats, BsonQmActionDecodeStats::default()); + assert_eq!(report.dividend_stats, BsonQmActionDecodeStats::default()); + } + #[test] fn curate_bars_benchmark_small_run_is_deterministic_and_cleans_up() { let (a, dir_a) = run_curate_bars_benchmark_tracked(20_000).unwrap(); @@ -7191,6 +8102,90 @@ mod tests { assert_eq!(report.stats, crate::curate_fx::CurateFx1dStats::default()); } + #[test] + fn curate_adj_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_curate_adj_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_curate_adj_benchmark_tracked(25_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.events, 25_000); + assert_eq!(a.splits_in + a.dividends_in, 25_000); + assert_eq!(a.stats.splits_in, a.splits_in); + assert_eq!(a.stats.dividends_in, a.dividends_in); + assert_eq!(a.key_count, CURATE_ADJ_BENCH_KEY_COUNT); + assert!(a.rows_out > 0); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.listings_out, b.listings_out); + assert_eq!(a.files_written, 1); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_events_per_sec.is_finite() && a.stage_events_per_sec >= 0.0); + assert!(a.stage_ns_per_event.is_finite() && a.stage_ns_per_event >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_events_per_sec.is_finite() && a.total_events_per_sec >= 0.0); + assert_eq!( + a.stats.splits_in, + a.stats.splits_dropped_unmapped + + a.stats.splits_collision_collapsed + + a.stats.builder.split_events_in + ); + assert_eq!( + a.stats.dividends_in, + a.stats.dividends_dropped_unmapped + + a.stats.dividends_collision_collapsed + + a.stats.builder.dividend_events_in + ); + assert_eq!( + a.stats.listing_collision_collapsed, + a.stats.splits_collision_collapsed + a.stats.dividends_collision_collapsed + ); + assert!(a.stats.splits_dropped_unmapped > 0); + assert!(a.stats.dividends_dropped_unmapped > 0); + assert!(a.stats.listing_collision_collapsed > 0); + } + + #[test] + fn curate_adj_benchmark_zero_events_handles_cleanly() { + let (report, dir) = run_curate_adj_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.events, 0); + assert_eq!(report.splits_in, 0); + assert_eq!(report.dividends_in, 0); + assert_eq!(report.key_count, CURATE_ADJ_BENCH_KEY_COUNT); + assert_eq!(report.rows_out, 0); + assert_eq!(report.listings_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_elapsed_ms, 0.0); + assert_eq!(report.stage_events_per_sec, 0.0); + assert_eq!(report.stage_ns_per_event, 0.0); + assert_eq!(report.parquet_elapsed_ms, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_elapsed_ms, 0.0); + assert_eq!(report.total_events_per_sec, 0.0); + assert_eq!( + report.stats, + crate::curate_adj::CurateAdjFactorsStats::default() + ); + } + #[test] fn curate_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() { let (a, dir_a) = run_curate_corporate_actions_benchmark_tracked(20_000).unwrap(); diff --git a/tools/curate-etl/src/bson_eod_prices.rs b/tools/curate-etl/src/bson_eod_prices.rs index 9547f250..1303f4c9 100644 --- a/tools/curate-etl/src/bson_eod_prices.rs +++ b/tools/curate-etl/src/bson_eod_prices.rs @@ -42,7 +42,7 @@ use bson::spec::ElementType; use crate::bars::EodDailyBar; use crate::split::ymd_to_epoch_days; -const MILLIS_PER_DAY: i64 = 86_400_000; +pub(crate) const MILLIS_PER_DAY: i64 = 86_400_000; const MIN_BSON_DOC_LEN: i32 = 5; /// Borrowed zero-copy view of a single decoded `eodPrices` BSON document. @@ -235,6 +235,26 @@ impl BsonEodDecodeStats { | BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1, } } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_in += other.docs_in; + self.decoded += other.decoded; + self.rejected_missing_field += other.rejected_missing_field; + self.rejected_empty_field += other.rejected_empty_field; + self.rejected_wrong_type += other.rejected_wrong_type; + self.rejected_malformed_date += other.rejected_malformed_date; + self.rejected_invalid_number += other.rejected_invalid_number; + self.rejected_corrupt_document += other.rejected_corrupt_document; + } +} + +impl std::ops::AddAssign for BsonEodDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } } #[inline] @@ -250,22 +270,20 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option { } #[inline] -fn parse_ymd_strict(s: &str) -> Result { +pub(crate) fn parse_ymd_strict_days(s: &str) -> Option { let bytes = s.as_bytes(); if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { - return Err(BsonEodPriceError::MalformedDate { field: "date" }); + return None; } - let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else { - return Err(BsonEodPriceError::MalformedDate { field: "date" }); - }; - let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else { - return Err(BsonEodPriceError::MalformedDate { field: "date" }); - }; - let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else { - return Err(BsonEodPriceError::MalformedDate { field: "date" }); - }; - ymd_to_epoch_days(year_u32 as i32, month, day) - .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" }) + let year_u32 = parse_ascii_digits_u32(&bytes[0..4])?; + let month = parse_ascii_digits_u32(&bytes[5..7])?; + let day = parse_ascii_digits_u32(&bytes[8..10])?; + ymd_to_epoch_days(year_u32 as i32, month, day).ok() +} + +#[inline] +fn parse_ymd_strict(s: &str) -> Result { + parse_ymd_strict_days(s).ok_or(BsonEodPriceError::MalformedDate { field: "date" }) } #[inline] @@ -438,11 +456,7 @@ pub fn decode_eod_price_doc<'a>( decode_eod_price_doc_at(doc, 0) } -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawEodDailyBar`]. -pub fn decode_eod_price_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonEodPriceError> { +pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> { if bytes.len() < 4 { return Err(BsonEodPriceError::TruncatedDocument { offset: 0, @@ -471,10 +485,18 @@ pub fn decode_eod_price_bytes<'a>( declared_len, }); } - let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { + RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { offset: 0, detail: err.to_string(), - })?; + }) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawEodDailyBar`]. +pub fn decode_eod_price_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonEodPriceError> { + let doc = parse_single_raw_doc(bytes)?; decode_eod_price_doc_at(doc, 0) } diff --git a/tools/curate-etl/src/bson_qm_actions.rs b/tools/curate-etl/src/bson_qm_actions.rs new file mode 100644 index 00000000..4efb6aff --- /dev/null +++ b/tools/curate-etl/src/bson_qm_actions.rs @@ -0,0 +1,813 @@ +//! Zero-copy raw BSON decoders for MongoDB `qmSplits` and `qmDividends` documents (`M1.2w`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into +//! borrowed [`RawQmSplit`] and [`RawQmDividend`] views without allocating a `String` or +//! `bson::Document` per row. Callers convert borrowed views into [`SplitEvent`], [`DividendEvent`], +//! [`SplitActionEvent`], or [`DividendActionEvent`], optionally resolving `("qm", qmSearchCode, ex_date)` +//! through a caller-supplied key mapper (such as [`crate::provider_mapping::ProviderMappingTable::resolve`]). +//! +//! # Empirical Field Contract & Cited Sources +//! +//! - `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:92-124`: writes +//! `qmSearchCode`, `symbol`, `exchange`, `reportDate: new Date(x.date)` plus the spread +//! QuoteMedia API payload into `qmDividends` and `qmSplits`. +//! - `design/DATA-CONTRACTS.md` §1 (line 25): documents `date`, `declared`, `splitratio` +//! (`258` rows have `splitratio == 1`), and `usdFxRate` (bogus `usdFxRate: 1` on CAD dividend +//! rows; contract rule: ignore `usdFxRate`). +//! - **Unverified field names:** the raw MongoDB dividend cash and currency field names are not +//! proven by any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped). +//! They are isolated in [`FIELD_DIVIDEND_CASH`] (`"amount"`) and [`FIELD_DIVIDEND_CURRENCY`] +//! (`"currency"`) and explicitly listed under "Unverified field names" in `tools/curate-etl/README.md`. +//! +//! Accepted BSON field representations: +//! - `qmSearchCode`, `currency`: BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only +//! is rejected). +//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via +//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via +//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check). +//! - `declared` (optional): absent, BSON `Null`, or empty/whitespace `String` maps to `None`; +//! otherwise strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`. +//! - `splitratio`: BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `ratio == 1.0` +//! no-ops are **decoded, not dropped** (downstream builders drop them) and counted in +//! [`BsonQmActionDecodeStats::split_noop_ratio_one`]. +//! - `amount` (dividend cash): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` +//! (`-0.0` is normalized to `+0.0`). +//! - `usdFxRate` and all unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, +//! `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without calling +//! `elem.value()`. + +use std::error::Error; +use std::fmt; + +use bson::raw::{RawBsonRef, RawDocument, RawElement}; +use bson::spec::ElementType; + +use crate::adj::DividendEvent; +use crate::bson_eod_prices::{ + iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, + MILLIS_PER_DAY, +}; +use crate::corporate_actions::{DividendActionEvent, SplitActionEvent}; +use crate::split::SplitEvent; + +/// MongoDB field name for the QuoteMedia security key (`events.action.ts:98,118`). +pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; +/// MongoDB field name for the ex-split / ex-dividend date (`events.action.ts:99,119`, `DATA-CONTRACTS.md:25`). +pub const FIELD_DATE: &str = "date"; +/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`). +pub const FIELD_DECLARED: &str = "declared"; +/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`). +pub const FIELD_SPLIT_RATIO: &str = "splitratio"; +/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`). +pub const FIELD_USD_FX_RATE: &str = "usdFxRate"; +/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention). +pub const FIELD_DIVIDEND_CASH: &str = "amount"; +/// MongoDB field name for dividend currency code (**unverified in repo**; QuoteMedia convention). +pub const FIELD_DIVIDEND_CURRENCY: &str = "currency"; + +/// Borrowed zero-copy view of a single decoded `qmSplits` BSON document. +/// +/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. +/// `ratio == 1.0` no-op rows are preserved here so downstream builders (`SplitTable`, +/// `build_adj_factors`, `build_corporate_actions`) apply their own filtering and accounting. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawQmSplit<'a> { + pub qm_search_code: &'a str, + /// Ex-split date as days since `1970-01-01` (UTC Gregorian). + pub ex_date: i32, + /// `new_shares / old_shares` (finite and `> 0.0`). + pub ratio: f64, + /// Optional declaration date as days since `1970-01-01` (UTC Gregorian). + pub declared_date: Option, +} + +impl<'a> RawQmSplit<'a> { + /// Converts this borrowed split into a [`SplitEvent`] for [`crate::split::SplitTable`] or + /// [`crate::adj::build_adj_factors`]. + #[inline] + pub fn to_split_event(self) -> SplitEvent { + SplitEvent { + ex_date: self.ex_date, + ratio: self.ratio, + } + } + + /// Converts this borrowed split into a [`SplitActionEvent`] for + /// [`crate::corporate_actions::build_corporate_actions`]. + #[inline] + pub fn to_split_action_event(self) -> SplitActionEvent { + SplitActionEvent { + ex_date: self.ex_date, + ratio: self.ratio, + declared_date: self.declared_date, + } + } + + /// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper + /// (for example `|code, date| mapping.resolve("qm", code, date)`). + #[inline] + pub fn try_map_key(self, map_key: F) -> Option + where + F: FnOnce(&'a str, i32) -> Option, + { + map_key(self.qm_search_code, self.ex_date) + } + + /// Fallibly resolves the key and pairs it with [`SplitEvent`]. + #[inline] + pub fn try_into_split_event(self, map_key: F) -> Option<(K, SplitEvent)> + where + F: FnOnce(&'a str, i32) -> Option, + { + let key = self.try_map_key(map_key)?; + Some((key, self.to_split_event())) + } + + /// Fallibly resolves the key and pairs it with [`SplitActionEvent`]. + #[inline] + pub fn try_into_split_action_event(self, map_key: F) -> Option<(K, SplitActionEvent)> + where + F: FnOnce(&'a str, i32) -> Option, + { + let key = self.try_map_key(map_key)?; + Some((key, self.to_split_action_event())) + } +} + +/// Borrowed zero-copy view of a single decoded `qmDividends` BSON document. +/// +/// Borrows `qm_search_code` and `currency` directly from the underlying `&RawDocument` byte slice. +/// Deliberately omits `usdFxRate` per `design/DATA-CONTRACTS.md` §1. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawQmDividend<'a> { + pub qm_search_code: &'a str, + /// Ex-dividend date as days since `1970-01-01` (UTC Gregorian). + pub ex_date: i32, + /// Cash dividend amount per share (finite and `>= 0.0`, with `-0.0` normalized to `+0.0`). + pub cash: f64, + /// Local dividend currency code (e.g. `"USD"`, `"CAD"`). + pub currency: &'a str, + /// Optional declaration date as days since `1970-01-01` (UTC Gregorian). + pub declared_date: Option, +} + +impl<'a> RawQmDividend<'a> { + /// Converts this borrowed dividend into a [`DividendEvent`] for + /// [`crate::adj::build_adj_factors`], attaching caller-supplied `prev_close` context. + #[inline] + pub fn to_dividend_event( + self, + prev_close: Option, + prev_close_currency: Option, + ) -> DividendEvent { + DividendEvent { + ex_date: self.ex_date, + cash: self.cash, + currency: self.currency.to_owned(), + prev_close, + prev_close_currency, + } + } + + /// Converts this borrowed dividend into a [`DividendActionEvent`] for + /// [`crate::corporate_actions::build_corporate_actions`]. + #[inline] + pub fn to_dividend_action_event(self) -> DividendActionEvent { + DividendActionEvent { + ex_date: self.ex_date, + cash: self.cash, + currency: self.currency.to_owned(), + declared_date: self.declared_date, + } + } + + /// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper + /// (for example `|code, date| mapping.resolve("qm", code, date)`). + #[inline] + pub fn try_map_key(self, map_key: F) -> Option + where + F: FnOnce(&'a str, i32) -> Option, + { + map_key(self.qm_search_code, self.ex_date) + } + + /// Fallibly resolves the key before allocating `currency` and pairs it with [`DividendEvent`]. + #[inline] + pub fn try_into_dividend_event( + self, + prev_close: Option, + prev_close_currency: Option, + map_key: F, + ) -> Option<(K, DividendEvent)> + where + F: FnOnce(&'a str, i32) -> Option, + { + let key = self.try_map_key(map_key)?; + Some((key, self.to_dividend_event(prev_close, prev_close_currency))) + } + + /// Fallibly resolves the key before allocating `currency` and pairs it with + /// [`DividendActionEvent`]. + #[inline] + pub fn try_into_dividend_action_event( + self, + map_key: F, + ) -> Option<(K, DividendActionEvent)> + where + F: FnOnce(&'a str, i32) -> Option, + { + let key = self.try_map_key(map_key)?; + Some((key, self.to_dividend_action_event())) + } +} + +/// Typed errors returned while decoding raw `qmSplits` or `qmDividends` BSON documents or +/// length-prefixed buffers. +/// +/// Every field-level error names the offending BSON field in both its structure and `Display` +/// output; no input path panics. +#[derive(Debug, Clone, PartialEq)] +pub enum BsonQmActionError { + /// A required field was absent from the document. + MissingField { field: &'static str }, + /// A required string field was empty or contained only whitespace. + EmptyField { field: &'static str }, + /// A decoded field had an unexpected BSON element type. + WrongType { + field: &'static str, + actual: ElementType, + }, + /// A date field was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime` + /// overflowed `i32` epoch days. + MalformedDate { field: &'static str }, + /// A numeric field was non-finite (`NaN`, `±inf`) or violated its domain bound (`> 0` for + /// `splitratio`, `>= 0` for dividend cash). + InvalidNumber { field: &'static str, value: f64 }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: usize, + remaining: usize, + declared_len: Option, + }, + /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single + /// document slice). + CorruptDocumentLength { offset: usize, declared_len: i32 }, + /// Underlying BSON framing or element bytes were malformed. + CorruptBson { offset: usize, detail: String }, +} + +impl fmt::Display for BsonQmActionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingField { field } => { + write!(f, "qm action BSON missing required field '{field}'") + } + Self::EmptyField { field } => { + write!(f, "qm action BSON field '{field}' must not be empty or blank") + } + Self::WrongType { field, actual } => { + write!( + f, + "qm action BSON field '{field}' has unexpected BSON type {actual:?}" + ) + } + Self::MalformedDate { field } => { + write!( + f, + "qm action BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime" + ) + } + Self::InvalidNumber { field, value } => { + write!( + f, + "qm action BSON field '{field}' has invalid numeric value {value}" + ) + } + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => match declared_len { + Some(len) => write!( + f, + "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" + ), + None => write!( + f, + "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" + ), + }, + Self::CorruptDocumentLength { + offset, + declared_len, + } => write!( + f, + "corrupt BSON document length {declared_len} at byte offset {offset}" + ), + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonQmActionError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonQmActionError { + match err { + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonQmActionError::TruncatedDocument { + offset, + remaining, + declared_len, + }, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + } => BsonQmActionError::CorruptDocumentLength { + offset, + declared_len, + }, + BsonEodPriceError::CorruptBson { offset, detail } => { + BsonQmActionError::CorruptBson { offset, detail } + } + BsonEodPriceError::MissingField { field } => BsonQmActionError::MissingField { field }, + BsonEodPriceError::EmptyField { field } => BsonQmActionError::EmptyField { field }, + BsonEodPriceError::WrongType { field, actual } => { + BsonQmActionError::WrongType { field, actual } + } + BsonEodPriceError::MalformedDate { field } => BsonQmActionError::MalformedDate { field }, + BsonEodPriceError::InvalidNumber { field, value } => { + BsonQmActionError::InvalidNumber { field, value } + } + } +} + +/// Per-batch decode and rejection accounting for [`decode_qm_split_buffer`] and +/// [`decode_qm_dividend_buffer`]. +/// +/// Conservation invariant: `decoded + rejected_total() == docs_in`. +/// `split_noop_ratio_one` counts decoded `qmSplits` documents with `ratio == 1.0` (a subset of +/// `decoded`, never added to `rejected_total()`). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonQmActionDecodeStats { + pub docs_in: usize, + pub decoded: usize, + /// Decoded `qmSplits` rows with `splitratio == 1.0` (subset of `decoded`). + pub split_noop_ratio_one: usize, + pub rejected_missing_field: usize, + pub rejected_empty_field: usize, + pub rejected_wrong_type: usize, + pub rejected_malformed_date: usize, + pub rejected_invalid_number: usize, + pub rejected_corrupt_document: usize, +} + +impl BsonQmActionDecodeStats { + /// Total number of rejected documents across all error categories. + #[inline] + pub fn rejected_total(&self) -> usize { + self.rejected_missing_field + + self.rejected_empty_field + + self.rejected_wrong_type + + self.rejected_malformed_date + + self.rejected_invalid_number + + self.rejected_corrupt_document + } + + /// Increments the rejection counter corresponding to `err`. + #[inline] + pub fn record_error(&mut self, err: &BsonQmActionError) { + match err { + BsonQmActionError::MissingField { .. } => self.rejected_missing_field += 1, + BsonQmActionError::EmptyField { .. } => self.rejected_empty_field += 1, + BsonQmActionError::WrongType { .. } => self.rejected_wrong_type += 1, + BsonQmActionError::MalformedDate { .. } => self.rejected_malformed_date += 1, + BsonQmActionError::InvalidNumber { .. } => self.rejected_invalid_number += 1, + BsonQmActionError::TruncatedDocument { .. } + | BsonQmActionError::CorruptDocumentLength { .. } + | BsonQmActionError::CorruptBson { .. } => self.rejected_corrupt_document += 1, + } + } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_in += other.docs_in; + self.decoded += other.decoded; + self.split_noop_ratio_one += other.split_noop_ratio_one; + self.rejected_missing_field += other.rejected_missing_field; + self.rejected_empty_field += other.rejected_empty_field; + self.rejected_wrong_type += other.rejected_wrong_type; + self.rejected_malformed_date += other.rejected_malformed_date; + self.rejected_invalid_number += other.rejected_invalid_number; + self.rejected_corrupt_document += other.rejected_corrupt_document; + } +} + +impl std::ops::AddAssign for BsonQmActionDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +#[inline] +fn decode_element_value<'a>( + field: &'static str, + elem: RawElement<'a>, + offset: usize, +) -> Result, BsonQmActionError> { + elem.value().map_err(|err| BsonQmActionError::CorruptBson { + offset, + detail: format!("field '{field}': {err}"), + }) +} + +#[inline] +fn decode_non_empty_str<'a>( + field: &'static str, + val: RawBsonRef<'a>, +) -> Result<&'a str, BsonQmActionError> { + match val { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + return Err(BsonQmActionError::EmptyField { field }); + } + Ok(s) + } + other => Err(BsonQmActionError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_required_date( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::String(s) => { + parse_ymd_strict_days(s).ok_or(BsonQmActionError::MalformedDate { field }) + } + RawBsonRef::DateTime(dt) => { + let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); + i32::try_from(days).map_err(|_| BsonQmActionError::MalformedDate { field }) + } + other => Err(BsonQmActionError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_optional_date( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result, BsonQmActionError> { + match val { + RawBsonRef::Null => Ok(None), + RawBsonRef::String(s) => { + if s.trim().is_empty() { + return Ok(None); + } + parse_ymd_strict_days(s) + .map(Some) + .ok_or(BsonQmActionError::MalformedDate { field }) + } + RawBsonRef::DateTime(dt) => { + let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); + i32::try_from(days) + .map(Some) + .map_err(|_| BsonQmActionError::MalformedDate { field }) + } + other => Err(BsonQmActionError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_positive_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v <= 0.0 { + return Err(BsonQmActionError::InvalidNumber { field, value: v }); + } + Ok(v) + } + RawBsonRef::Int32(v) => { + if v <= 0 { + return Err(BsonQmActionError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v <= 0 { + return Err(BsonQmActionError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonQmActionError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +#[inline] +fn decode_non_negative_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v < 0.0 { + return Err(BsonQmActionError::InvalidNumber { field, value: v }); + } + if v == 0.0 { + Ok(0.0) + } else { + Ok(v) + } + } + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonQmActionError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonQmActionError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonQmActionError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +fn decode_qm_split_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonQmActionError> { + let mut qm_search_code: Option<&'a str> = None; + let mut ex_date: Option = None; + let mut ratio: Option = None; + let mut declared_date: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key().as_str(); + + if key == FIELD_QM_SEARCH_CODE { + let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?; + qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?); + } else if key == FIELD_DATE { + let val = decode_element_value(FIELD_DATE, elem, offset)?; + ex_date = Some(decode_required_date(FIELD_DATE, val)?); + } else if key == FIELD_SPLIT_RATIO { + let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?; + ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?); + } else if key == FIELD_DECLARED { + let val = decode_element_value(FIELD_DECLARED, elem, offset)?; + declared_date = decode_optional_date(FIELD_DECLARED, val)?; + } + // `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`. + } + + let Some(qm_search_code) = qm_search_code else { + return Err(BsonQmActionError::MissingField { + field: FIELD_QM_SEARCH_CODE, + }); + }; + let Some(ex_date) = ex_date else { + return Err(BsonQmActionError::MissingField { field: FIELD_DATE }); + }; + let Some(ratio) = ratio else { + return Err(BsonQmActionError::MissingField { + field: FIELD_SPLIT_RATIO, + }); + }; + + Ok(RawQmSplit { + qm_search_code, + ex_date, + ratio, + declared_date, + }) +} + +fn decode_qm_dividend_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonQmActionError> { + let mut qm_search_code: Option<&'a str> = None; + let mut ex_date: Option = None; + let mut cash: Option = None; + let mut currency: Option<&'a str> = None; + let mut declared_date: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key().as_str(); + + if key == FIELD_QM_SEARCH_CODE { + let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?; + qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?); + } else if key == FIELD_DATE { + let val = decode_element_value(FIELD_DATE, elem, offset)?; + ex_date = Some(decode_required_date(FIELD_DATE, val)?); + } else if key == FIELD_DIVIDEND_CASH { + let val = decode_element_value(FIELD_DIVIDEND_CASH, elem, offset)?; + cash = Some(decode_non_negative_number(FIELD_DIVIDEND_CASH, val)?); + } else if key == FIELD_DIVIDEND_CURRENCY { + let val = decode_element_value(FIELD_DIVIDEND_CURRENCY, elem, offset)?; + currency = Some(decode_non_empty_str(FIELD_DIVIDEND_CURRENCY, val)?); + } else if key == FIELD_DECLARED { + let val = decode_element_value(FIELD_DECLARED, elem, offset)?; + declared_date = decode_optional_date(FIELD_DECLARED, val)?; + } + // `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`. + } + + let Some(qm_search_code) = qm_search_code else { + return Err(BsonQmActionError::MissingField { + field: FIELD_QM_SEARCH_CODE, + }); + }; + let Some(ex_date) = ex_date else { + return Err(BsonQmActionError::MissingField { field: FIELD_DATE }); + }; + let Some(cash) = cash else { + return Err(BsonQmActionError::MissingField { + field: FIELD_DIVIDEND_CASH, + }); + }; + let Some(currency) = currency else { + return Err(BsonQmActionError::MissingField { + field: FIELD_DIVIDEND_CURRENCY, + }); + }; + + Ok(RawQmDividend { + qm_search_code, + ex_date, + cash, + currency, + declared_date, + }) +} + +/// Decodes a single `&RawDocument` representing a `qmSplits` MongoDB document in one forward pass +/// without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_qm_split_doc<'a>(doc: &'a RawDocument) -> Result, BsonQmActionError> { + decode_qm_split_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmSplit`]. +pub fn decode_qm_split_bytes<'a>(bytes: &'a [u8]) -> Result, BsonQmActionError> { + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_qm_split_doc_at(doc, 0) +} + +/// Decodes a single `&RawDocument` representing a `qmDividends` MongoDB document in one forward +/// pass without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_qm_dividend_doc<'a>( + doc: &'a RawDocument, +) -> Result, BsonQmActionError> { + decode_qm_dividend_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawQmDividend`]. +pub fn decode_qm_dividend_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonQmActionError> { + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_qm_dividend_doc_at(doc, 0) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_split_doc`], invoking +/// `on_split` for every valid document (including `splitratio == 1.0`, counted in +/// `stats.split_noop_ratio_one`) and `on_error(byte_offset, err)` for every rejected document +/// without aborting the stream on per-document errors. +/// +/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. +pub fn decode_qm_split_buffer<'a, F, E>( + buf: &'a [u8], + mut on_split: F, + mut on_error: E, +) -> BsonQmActionDecodeStats +where + F: FnMut(RawQmSplit<'a>), + E: FnMut(usize, BsonQmActionError), +{ + let mut stats = BsonQmActionDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + + while let Some(item) = iter.next_with_offset() { + stats.docs_in += 1; + match item { + Ok((doc_offset, doc)) => match decode_qm_split_doc_at(doc, doc_offset) { + Ok(split) => { + stats.decoded += 1; + if split.ratio == 1.0 { + stats.split_noop_ratio_one += 1; + } + on_split(split); + } + Err(err) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + }, + Err((doc_offset, err)) => { + let mapped = map_framing_error(err); + stats.record_error(&mapped); + on_error(doc_offset, mapped); + } + } + } + + stats +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_dividend_doc`], invoking +/// `on_dividend` for every valid document and `on_error(byte_offset, err)` for every rejected +/// document without aborting the stream on per-document errors. +/// +/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. +pub fn decode_qm_dividend_buffer<'a, F, E>( + buf: &'a [u8], + mut on_dividend: F, + mut on_error: E, +) -> BsonQmActionDecodeStats +where + F: FnMut(RawQmDividend<'a>), + E: FnMut(usize, BsonQmActionError), +{ + let mut stats = BsonQmActionDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + + while let Some(item) = iter.next_with_offset() { + stats.docs_in += 1; + match item { + Ok((doc_offset, doc)) => match decode_qm_dividend_doc_at(doc, doc_offset) { + Ok(dividend) => { + stats.decoded += 1; + on_dividend(dividend); + } + Err(err) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + }, + Err((doc_offset, err)) => { + let mapped = map_framing_error(err); + stats.record_error(&mapped); + on_error(doc_offset, mapped); + } + } + } + + stats +} + +#[cfg(test)] +#[path = "bson_qm_actions_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_qm_actions_tests.rs b/tools/curate-etl/src/bson_qm_actions_tests.rs new file mode 100644 index 00000000..049af9c2 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_actions_tests.rs @@ -0,0 +1,883 @@ +use bson::oid::ObjectId; +use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::DateTime; + +use super::*; +use crate::corporate_actions::{build_corporate_actions, CorporateActionKind, KnownAtSource}; +use crate::curate_adj::curate_adj_factors; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::split::{ymd_to_epoch_days, SplitTable}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("splitratio"), ratio); + if let Some(decl) = declared { + doc.append(cstr!("declared"), decl); + } + doc +} + +fn make_dividend_doc( + code: &str, + date: &str, + cash: f64, + currency: &str, + declared: Option<&str>, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("amount"), cash); + doc.append(cstr!("currency"), currency); + if let Some(decl) = declared { + doc.append(cstr!("declared"), decl); + } + doc +} + +#[test] +fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rate() { + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("provider"), "quotemedia"); + nested.append(cstr!("version"), 1_i32); + + let mut tags = RawArrayBuf::new(); + tags.push("ca"); + tags.push("equity"); + + // Realistic qmSplits document with extra metadata and bogus usdFxRate. + let mut split_doc = RawDocumentBuf::new(); + split_doc.append( + cstr!("_id"), + ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ); + split_doc.append(cstr!("symbol"), "NVDA"); + split_doc.append(cstr!("exchange"), "NASDAQ"); + split_doc.append(cstr!("qmSearchCode"), "NVDA"); + split_doc.append(cstr!("date"), "2024-06-10"); + split_doc.append(cstr!("declared"), "2024-05-22"); + split_doc.append(cstr!("splitratio"), 10.0_f64); + split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type"); + split_doc.append( + cstr!("reportDate"), + DateTime::from_millis(i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY), + ); + split_doc.append(cstr!("created_at"), DateTime::from_millis(1_718_000_000_000)); + split_doc.append(cstr!("updated_at"), DateTime::from_millis(1_718_000_060_000)); + split_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + split_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let split = decode_qm_split_doc(&split_doc).unwrap(); + assert_eq!(split.qm_search_code, "NVDA"); + assert_eq!(split.ex_date, day(2024, 6, 10)); + assert_eq!(split.ratio.to_bits(), 10.0_f64.to_bits()); + assert_eq!(split.declared_date, Some(day(2024, 5, 22))); + assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split); + + // Realistic qmDividends document with bogus usdFxRate: 1 on CAD row. + let mut div_doc = RawDocumentBuf::new(); + div_doc.append( + cstr!("_id"), + ObjectId::from_bytes([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]), + ); + div_doc.append(cstr!("symbol"), "RY"); + div_doc.append(cstr!("exchange"), "TSX"); + div_doc.append(cstr!("qmSearchCode"), "RY:CA"); + div_doc.append(cstr!("date"), "2024-11-15"); + div_doc.append(cstr!("declared"), "2024-10-30"); + div_doc.append(cstr!("amount"), 1.42_f64); + div_doc.append(cstr!("currency"), "CAD"); + div_doc.append(cstr!("usdFxRate"), 1_i32); + div_doc.append( + cstr!("reportDate"), + DateTime::from_millis(i64::from(day(2024, 11, 15)) * MILLIS_PER_DAY), + ); + div_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + div_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let div = decode_qm_dividend_doc(&div_doc).unwrap(); + assert_eq!(div.qm_search_code, "RY:CA"); + assert_eq!(div.ex_date, day(2024, 11, 15)); + assert_eq!(div.cash.to_bits(), 1.42_f64.to_bits()); + assert_eq!(div.currency, "CAD"); + assert_eq!(div.declared_date, Some(day(2024, 10, 30))); + assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div); +} + +#[test] +fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_day() { + // Pre-1970 mid-day: 1969-12-31T12:34:56.789Z must floor to epoch day -1 (not 0). + let pre_1970_ex_ms: i64 = -MILLIS_PER_DAY + (12 * 3600 + 34 * 60 + 56) * 1000 + 789; + let pre_1970_decl_ms: i64 = -10 * MILLIS_PER_DAY + 43_200_000; + + let mut split_dt = RawDocumentBuf::new(); + split_dt.append(cstr!("qmSearchCode"), "IBM"); + split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms)); + split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms)); + split_dt.append(cstr!("splitratio"), 2_i32); + + let split = decode_qm_split_doc(&split_dt).unwrap(); + assert_eq!(split.ex_date, -1); + assert_eq!(split.declared_date, Some(-10)); + assert_eq!(split.ratio, 2.0); + + // Leap day string + DateTime declared. + let mut div_leap = RawDocumentBuf::new(); + div_leap.append(cstr!("qmSearchCode"), "TD:CA"); + div_leap.append(cstr!("date"), "2024-02-29"); + div_leap.append( + cstr!("declared"), + DateTime::from_millis(i64::from(day(2024, 2, 1)) * MILLIS_PER_DAY + 36_000_000), + ); + div_leap.append(cstr!("amount"), 1.02_f64); + div_leap.append(cstr!("currency"), "CAD"); + + let div = decode_qm_dividend_doc(&div_leap).unwrap(); + assert_eq!(div.ex_date, day(2024, 2, 29)); + assert_eq!(div.declared_date, Some(day(2024, 2, 1))); +} + +#[test] +fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() { + // Splits: Double, Int32, Int64. + for (val, expected) in [ + (RawBsonRef::Double(0.05), 0.05_f64), + (RawBsonRef::Int32(4), 4.0_f64), + (RawBsonRef::Int64(10), 10.0_f64), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "TEST"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitratio"), val); + let decoded = decode_qm_split_doc(&doc).unwrap(); + assert_eq!(decoded.ratio.to_bits(), expected.to_bits()); + } + + // Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0. + for (val, expected) in [ + (RawBsonRef::Double(0.25), 0.25_f64), + (RawBsonRef::Double(-0.0), 0.0_f64), + (RawBsonRef::Double(0.0), 0.0_f64), + (RawBsonRef::Int32(0), 0.0_f64), + (RawBsonRef::Int32(2), 2.0_f64), + (RawBsonRef::Int64(0), 0.0_f64), + (RawBsonRef::Int64(5), 5.0_f64), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "TEST"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), val); + doc.append(cstr!("currency"), "USD"); + let decoded = decode_qm_dividend_doc(&doc).unwrap(); + assert_eq!(decoded.cash.to_bits(), expected.to_bits()); + assert!(!decoded.cash.is_sign_negative()); + } +} + +#[test] +fn handles_optional_declared_missing_null_empty_malformed_and_wrong_type() { + // Missing declared -> None. + let s_missing = make_split_doc("AAPL", "2020-08-31", 4.0, None); + assert_eq!(decode_qm_split_doc(&s_missing).unwrap().declared_date, None); + + // Null declared -> None. + let mut s_null = make_split_doc("AAPL", "2020-08-31", 4.0, None); + s_null.append(cstr!("declared"), RawBsonRef::Null); + assert_eq!(decode_qm_split_doc(&s_null).unwrap().declared_date, None); + + // Empty and whitespace-only declared -> None. + for blank in ["", " ", "\t\n"] { + let d_blank = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", Some(blank)); + assert_eq!( + decode_qm_dividend_doc(&d_blank).unwrap().declared_date, + None + ); + } + + // Malformed declared -> MalformedDate naming "declared". + let s_bad = make_split_doc("AAPL", "2020-08-31", 4.0, Some("2023-02-29")); + let err = decode_qm_split_doc(&s_bad).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MalformedDate { + field: FIELD_DECLARED + } + ); + assert!(err.to_string().contains(FIELD_DECLARED)); + + // Wrong type on declared -> WrongType naming "declared". + let mut d_wrong = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None); + d_wrong.append(cstr!("declared"), 20240801_i32); + let err = decode_qm_dividend_doc(&d_wrong).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::WrongType { + field: FIELD_DECLARED, + actual: ElementType::Int32, + } + ); + assert!(err.to_string().contains(FIELD_DECLARED)); +} + +#[test] +fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() { + let mut buf = Vec::new(); + for val in [ + RawBsonRef::Double(1.0), + RawBsonRef::Int32(1), + RawBsonRef::Int64(1), + RawBsonRef::Double(2.0), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NOOP"); + doc.append(cstr!("date"), "2024-03-15"); + doc.append(cstr!("splitratio"), val); + buf.extend_from_slice(doc.as_bytes()); + } + + let mut decoded_ratios = Vec::new(); + let stats = decode_qm_split_buffer( + &buf, + |s| decoded_ratios.push(s.ratio), + |_, err| panic!("unexpected error: {err}"), + ); + + assert_eq!(decoded_ratios, vec![1.0, 1.0, 1.0, 2.0]); + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.decoded, 4); + assert_eq!(stats.split_noop_ratio_one, 3); + assert_eq!(stats.rejected_total(), 0); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); +} + +#[test] +fn rejects_every_error_variant_and_names_offending_field() { + // 1. Missing required fields on splits. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitratio"), 2.0_f64); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MissingField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("splitratio"), 2.0_f64); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE }); + assert!(err.to_string().contains(FIELD_DATE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), "2024-06-10"); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MissingField { + field: FIELD_SPLIT_RATIO + } + ); + assert!(err.to_string().contains(FIELD_SPLIT_RATIO)); + } + + // 2. Missing required fields on dividends. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), 0.5_f64); + doc.append(cstr!("currency"), "USD"); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MissingField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("amount"), 0.5_f64); + doc.append(cstr!("currency"), "CAD"); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE }); + assert!(err.to_string().contains(FIELD_DATE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("currency"), "CAD"); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MissingField { + field: FIELD_DIVIDEND_CASH + } + ); + assert!(err.to_string().contains(FIELD_DIVIDEND_CASH)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), 0.5_f64); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MissingField { + field: FIELD_DIVIDEND_CURRENCY + } + ); + assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY)); + } + + // 3. Empty / whitespace-only string fields. + for blank in ["", " ", "\t\n"] { + let s = make_split_doc(blank, "2024-06-10", 2.0, None); + let err = decode_qm_split_doc(&s).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::EmptyField { + field: FIELD_QM_SEARCH_CODE + } + ); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); + + let d = make_dividend_doc("RY:CA", "2024-06-10", 0.5, blank, None); + let err = decode_qm_dividend_doc(&d).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::EmptyField { + field: FIELD_DIVIDEND_CURRENCY + } + ); + assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY)); + } + + // 4. Wrong BSON types (including string-encoded numerics). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), 123_i32); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitratio"), 2.0_f64); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::WrongType { + field: FIELD_QM_SEARCH_CODE, + actual: ElementType::Int32, + } + ); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), 20240610_i32); + doc.append(cstr!("splitratio"), 2.0_f64); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::WrongType { + field: FIELD_DATE, + actual: ElementType::Int32, + } + ); + assert!(err.to_string().contains(FIELD_DATE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitratio"), "10.0"); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::WrongType { + field: FIELD_SPLIT_RATIO, + actual: ElementType::String, + } + ); + assert!(err.to_string().contains(FIELD_SPLIT_RATIO)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), "1.42"); + doc.append(cstr!("currency"), "CAD"); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::WrongType { + field: FIELD_DIVIDEND_CASH, + actual: ElementType::String, + } + ); + assert!(err.to_string().contains(FIELD_DIVIDEND_CASH)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), 1.42_f64); + doc.append(cstr!("currency"), true); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::WrongType { + field: FIELD_DIVIDEND_CURRENCY, + actual: ElementType::Boolean, + } + ); + assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY)); + } + + // 5. Malformed dates (bad calendar date, bad format, and DateTime overflowing i32 days). + for bad_date in ["2023-02-29", "2024/06/10", "2024-6-10", "not-a-date"] { + let doc = make_split_doc("NVDA", bad_date, 2.0, None); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE }); + assert!(err.to_string().contains(FIELD_DATE)); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), DateTime::from_millis(i64::MAX)); + doc.append(cstr!("splitratio"), 2.0_f64); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE }); + } + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("declared"), DateTime::from_millis(i64::MIN)); + doc.append(cstr!("splitratio"), 2.0_f64); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonQmActionError::MalformedDate { + field: FIELD_DECLARED + } + ); + } + + // 6. Invalid numeric values for splitratio (<= 0 or non-finite). + for bad_ratio in [ + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Double(-2.0), + RawBsonRef::Int32(0), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(0), + RawBsonRef::Int64(-5), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("splitratio"), bad_ratio); + let err = decode_qm_split_doc(&doc).unwrap_err(); + assert!( + matches!( + err, + BsonQmActionError::InvalidNumber { + field: FIELD_SPLIT_RATIO, + .. + } + ), + "expected InvalidNumber for {bad_ratio:?}, got {err:?}" + ); + assert!(err.to_string().contains(FIELD_SPLIT_RATIO)); + } + + // 7. Invalid numeric values for dividend cash (< 0 or non-finite). + for bad_cash in [ + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Double(-0.01), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(-10), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("amount"), bad_cash); + doc.append(cstr!("currency"), "CAD"); + let err = decode_qm_dividend_doc(&doc).unwrap_err(); + assert!( + matches!( + err, + BsonQmActionError::InvalidNumber { + field: FIELD_DIVIDEND_CASH, + .. + } + ), + "expected InvalidNumber for {bad_cash:?}, got {err:?}" + ); + assert!(err.to_string().contains(FIELD_DIVIDEND_CASH)); + } + + // 8. Truncated and corrupt documents (zero panics). + assert!(matches!( + decode_qm_split_bytes(&[]), + Err(BsonQmActionError::TruncatedDocument { + offset: 0, + remaining: 0, + declared_len: None + }) + )); + assert!(matches!( + decode_qm_dividend_bytes(&[1, 2, 3]), + Err(BsonQmActionError::TruncatedDocument { + offset: 0, + remaining: 3, + declared_len: None + }) + )); + assert!(matches!( + decode_qm_split_bytes(&4_i32.to_le_bytes()), + Err(BsonQmActionError::CorruptDocumentLength { + offset: 0, + declared_len: 4 + }) + )); + let valid_bytes = make_split_doc("NVDA", "2024-06-10", 10.0, None) + .as_bytes() + .to_vec(); + assert!(matches!( + decode_qm_split_bytes(&valid_bytes[..valid_bytes.len() - 1]), + Err(BsonQmActionError::TruncatedDocument { + offset: 0, + declared_len: Some(_), + .. + }) + )); + let mut with_trailing = valid_bytes.clone(); + with_trailing.push(0); + assert!(matches!( + decode_qm_split_bytes(&with_trailing), + Err(BsonQmActionError::CorruptDocumentLength { offset: 0, .. }) + )); + let mut bad_terminator = valid_bytes; + *bad_terminator.last_mut().unwrap() = 0xFF; + assert!(matches!( + decode_qm_split_bytes(&bad_terminator), + Err(BsonQmActionError::CorruptBson { offset: 0, .. }) + )); + + // Invalid UTF-8 inside a known string field (`qmSearchCode`). + let mut invalid_utf8_doc: Vec = Vec::new(); + // Placeholder 4-byte length. + invalid_utf8_doc.extend_from_slice(&0_i32.to_le_bytes()); + invalid_utf8_doc.push(0x02); // UTF-8 String element + invalid_utf8_doc.extend_from_slice(b"qmSearchCode\0"); + invalid_utf8_doc.extend_from_slice(&3_i32.to_le_bytes()); // 2 bytes + NUL + invalid_utf8_doc.extend_from_slice(&[0xFF, 0xFE, 0x00]); + invalid_utf8_doc.push(0x00); // doc terminator + let total_len = invalid_utf8_doc.len() as i32; + invalid_utf8_doc[0..4].copy_from_slice(&total_len.to_le_bytes()); + let err = decode_qm_split_bytes(&invalid_utf8_doc).unwrap_err(); + assert!(matches!(err, BsonQmActionError::CorruptBson { offset: 0, .. })); + assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); +} + +#[test] +fn buffer_decoders_survive_per_doc_errors_and_reconcile_stats_for_both_collections() { + // 1. qmSplits mixed valid/invalid buffer. + let s1 = make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")); + let s_noop = make_split_doc("NOOP", "2024-06-11", 1.0, None); + let mut s_missing = RawDocumentBuf::new(); + s_missing.append(cstr!("qmSearchCode"), "MISS"); + s_missing.append(cstr!("date"), "2024-06-12"); + let s_empty = make_split_doc(" ", "2024-06-13", 2.0, None); + let mut s_wrong = RawDocumentBuf::new(); + s_wrong.append(cstr!("qmSearchCode"), "WRNG"); + s_wrong.append(cstr!("date"), "2024-06-14"); + s_wrong.append(cstr!("splitratio"), "2.0"); + let s_bad_date = make_split_doc("DATE", "2023-02-29", 2.0, None); + let s_bad_num = make_split_doc("NUM", "2024-06-15", 0.0, None); + let mut s_corrupt = make_split_doc("CORR", "2024-06-16", 2.0, None) + .as_bytes() + .to_vec(); + *s_corrupt.last_mut().unwrap() = 0xAA; + let s2 = make_split_doc("NEXM:CA", "2025-06-18", 0.05, None); + + let mut split_buf = Vec::new(); + split_buf.extend_from_slice(s1.as_bytes()); + split_buf.extend_from_slice(s_noop.as_bytes()); + split_buf.extend_from_slice(s_missing.as_bytes()); + split_buf.extend_from_slice(s_empty.as_bytes()); + split_buf.extend_from_slice(s_wrong.as_bytes()); + split_buf.extend_from_slice(s_bad_date.as_bytes()); + split_buf.extend_from_slice(s_bad_num.as_bytes()); + split_buf.extend_from_slice(&s_corrupt); + split_buf.extend_from_slice(s2.as_bytes()); + + let mut split_codes = Vec::new(); + let mut split_errors = Vec::new(); + let split_stats = decode_qm_split_buffer( + &split_buf, + |s| split_codes.push(s.qm_search_code.to_owned()), + |off, err| split_errors.push((off, err)), + ); + + assert_eq!(split_codes, vec!["NVDA", "NOOP", "NEXM:CA"]); + assert_eq!(split_errors.len(), 6); + assert_eq!(split_stats.docs_in, 9); + assert_eq!(split_stats.decoded, 3); + assert_eq!(split_stats.split_noop_ratio_one, 1); + assert_eq!(split_stats.rejected_missing_field, 1); + assert_eq!(split_stats.rejected_empty_field, 1); + assert_eq!(split_stats.rejected_wrong_type, 1); + assert_eq!(split_stats.rejected_malformed_date, 1); + assert_eq!(split_stats.rejected_invalid_number, 1); + assert_eq!(split_stats.rejected_corrupt_document, 1); + assert_eq!( + split_stats.decoded + split_stats.rejected_total(), + split_stats.docs_in + ); + + // 2. qmDividends mixed valid/invalid buffer ending with a corrupt length prefix. + let d1 = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30")); + let mut d_missing = RawDocumentBuf::new(); + d_missing.append(cstr!("qmSearchCode"), "MISS"); + d_missing.append(cstr!("date"), "2024-11-15"); + d_missing.append(cstr!("amount"), 0.5_f64); + let d_empty = make_dividend_doc("RY:CA", "2024-11-15", 0.5, " ", None); + let mut d_wrong = RawDocumentBuf::new(); + d_wrong.append(cstr!("qmSearchCode"), "RY:CA"); + d_wrong.append(cstr!("date"), "2024-11-15"); + d_wrong.append(cstr!("amount"), "0.5"); + d_wrong.append(cstr!("currency"), "CAD"); + let d_bad_date = make_dividend_doc("RY:CA", "2024-11-15", 0.5, "CAD", Some("bad")); + let d_bad_num = make_dividend_doc("RY:CA", "2024-11-15", -0.1, "CAD", None); + let d2 = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None); + + let mut div_buf = Vec::new(); + div_buf.extend_from_slice(d1.as_bytes()); + div_buf.extend_from_slice(d_missing.as_bytes()); + div_buf.extend_from_slice(d_empty.as_bytes()); + div_buf.extend_from_slice(d_wrong.as_bytes()); + div_buf.extend_from_slice(d_bad_date.as_bytes()); + div_buf.extend_from_slice(d_bad_num.as_bytes()); + div_buf.extend_from_slice(d2.as_bytes()); + // Trailing corrupt length < 5 stops cleanly. + div_buf.extend_from_slice(&2_i32.to_le_bytes()); + div_buf.extend_from_slice(d2.as_bytes()); + + let mut div_codes = Vec::new(); + let mut div_errors = Vec::new(); + let div_stats = decode_qm_dividend_buffer( + &div_buf, + |d| div_codes.push(d.qm_search_code.to_owned()), + |off, err| div_errors.push((off, err)), + ); + + assert_eq!(div_codes, vec!["RY:CA", "AAPL"]); + assert_eq!(div_errors.len(), 6); + assert_eq!(div_stats.docs_in, 8); + assert_eq!(div_stats.decoded, 2); + assert_eq!(div_stats.split_noop_ratio_one, 0); + assert_eq!(div_stats.rejected_missing_field, 1); + assert_eq!(div_stats.rejected_empty_field, 1); + assert_eq!(div_stats.rejected_wrong_type, 1); + assert_eq!(div_stats.rejected_malformed_date, 1); + assert_eq!(div_stats.rejected_invalid_number, 1); + assert_eq!(div_stats.rejected_corrupt_document, 1); + assert_eq!( + div_stats.decoded + div_stats.rejected_total(), + div_stats.docs_in + ); +} + +#[test] +fn decoded_events_feed_split_table_curate_adj_factors_and_corporate_actions_unchanged() { + // 1. SplitTable interoperability (NVDA 10:1 forward, NEXM:CA 1:20 reverse, 1:1 no-op). + let mut split_buf = Vec::new(); + split_buf.extend_from_slice( + make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")).as_bytes(), + ); + split_buf.extend_from_slice(make_split_doc("NVDA", "2024-07-01", 1.0, None).as_bytes()); + split_buf.extend_from_slice(make_split_doc("NEXM:CA", "2025-06-18", 0.05, None).as_bytes()); + split_buf.extend_from_slice(make_split_doc("UNMAPPED", "2024-06-10", 2.0, None).as_bytes()); + + let mut div_buf = Vec::new(); + let mut ry_div = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30")); + ry_div.append(cstr!("usdFxRate"), 1_i32); // bogus usdFxRate must have zero effect + div_buf.extend_from_slice(ry_div.as_bytes()); + let mut unmapped_div = make_dividend_doc("UNMAPPED", "2024-11-15", 0.50, "USD", None); + unmapped_div.append(cstr!("usdFxRate"), 999.0_f64); + div_buf.extend_from_slice(unmapped_div.as_bytes()); + + let mut source_splits = Vec::new(); + let split_stats = decode_qm_split_buffer( + &split_buf, + |s| source_splits.push((s.qm_search_code.to_owned(), s.to_split_event())), + |_, err| panic!("unexpected split decode error: {err}"), + ); + assert_eq!(split_stats.split_noop_ratio_one, 1); + + let table = SplitTable::from_events(source_splits.iter().cloned()).unwrap(); + assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0); + assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 10)), 1.0); + assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 17)), 0.05); + assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 18)), 1.0); + + // 2. ProviderMappingTable + curate_adj_factors interoperability. + let mapping = ProviderMappingTable::from_rows([ + ProviderMappingRow { + source: "qm".to_string(), + source_id: "NVDA".to_string(), + listing_id: 101, + valid_from: day(2020, 1, 1), + valid_to: None, + }, + ProviderMappingRow { + source: "qm".to_string(), + source_id: "NEXM:CA".to_string(), + listing_id: 202, + valid_from: day(2020, 1, 1), + valid_to: None, + }, + ProviderMappingRow { + source: "qm".to_string(), + source_id: "RY:CA".to_string(), + listing_id: 303, + valid_from: day(2020, 1, 1), + valid_to: None, + }, + ]) + .unwrap(); + + let mut source_divs = Vec::new(); + decode_qm_dividend_buffer( + &div_buf, + |d| { + source_divs.push(( + d.qm_search_code.to_owned(), + d.to_dividend_event(Some(142.0), Some("CAD".to_string())), + )); + }, + |_, err| panic!("unexpected dividend decode error: {err}"), + ); + + let curated = curate_adj_factors(&mapping, "qm", source_splits, source_divs).unwrap(); + // 1:1 NVDA split dropped by builder; UNMAPPED split & dividend dropped by mapping. + assert_eq!(curated.rows.len(), 3); + assert_eq!(curated.stats.builder.split_noops_dropped, 1); + assert_eq!(curated.stats.splits_dropped_unmapped, 1); + assert_eq!(curated.stats.dividends_dropped_unmapped, 1); + + // Row 0: listing 101 (NVDA) 10:1 split + assert_eq!(curated.rows[0].listing_id, 101); + assert_eq!(curated.rows[0].ex_date, day(2024, 6, 10)); + assert_eq!(curated.rows[0].split_factor, 10.0); + assert_eq!(curated.rows[0].cum_split_factor, 10.0); + + // Row 1: listing 202 (NEXM:CA) 1:20 reverse split + assert_eq!(curated.rows[1].listing_id, 202); + assert_eq!(curated.rows[1].ex_date, day(2025, 6, 18)); + assert_eq!(curated.rows[1].split_factor, 0.05); + + // Row 2: listing 303 (RY:CA) CAD dividend with usdFxRate ignored + assert_eq!(curated.rows[2].listing_id, 303); + assert_eq!(curated.rows[2].ex_date, day(2024, 11, 15)); + assert_eq!(curated.rows[2].div_cash, 1.42); + assert_eq!(curated.rows[2].div_currency.as_deref(), Some("CAD")); + let expected_div_factor = 142.0 / (142.0 - 1.42); + assert!((curated.rows[2].cum_total_factor - expected_div_factor).abs() < 1e-12); + + // 3. try_map_key / try_into_*_action_event -> build_corporate_actions. + let mut mapped_split_actions = Vec::new(); + decode_qm_split_buffer( + &split_buf, + |s| { + if let Some(pair) = + s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date)) + { + mapped_split_actions.push(pair); + } + }, + |_, err| panic!("unexpected error: {err}"), + ); + + let mut mapped_div_actions = Vec::new(); + decode_qm_dividend_buffer( + &div_buf, + |d| { + if let Some(pair) = + d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date)) + { + mapped_div_actions.push(pair); + } + }, + |_, err| panic!("unexpected error: {err}"), + ); + + // Also verify try_into_split_event & try_into_dividend_event filter unmapped keys. + let unmapped_split_doc = make_split_doc("UNMAPPED", "2024-06-10", 2.0, None); + let unmapped_split = decode_qm_split_doc(&unmapped_split_doc).unwrap(); + assert_eq!( + unmapped_split.try_into_split_event(|code, date| mapping.resolve("qm", code, date)), + None + ); + let mapped_div = decode_qm_dividend_doc(&ry_div).unwrap(); + let (lid, div_ev) = mapped_div + .try_into_dividend_event(Some(142.0), Some("CAD".to_string()), |code, date| { + mapping.resolve("qm", code, date) + }) + .unwrap(); + assert_eq!(lid, 303); + assert_eq!(div_ev.currency, "CAD"); + + let ca = build_corporate_actions( + mapped_split_actions, + mapped_div_actions, + std::iter::empty(), + ) + .unwrap(); + assert_eq!(ca.rows.len(), 3); + assert_eq!(ca.stats.split_noops_dropped, 1); + + // NVDA split has declared_date -> DeclaredDate. + assert_eq!(ca.rows[0].key, 101); + assert_eq!(ca.rows[0].kind, CorporateActionKind::Split); + assert_eq!(ca.rows[0].declared_date, Some(day(2024, 5, 22))); + assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate); + + // NEXM split has no declared_date -> ExDateFallback. + assert_eq!(ca.rows[1].key, 202); + assert_eq!(ca.rows[1].kind, CorporateActionKind::Split); + assert_eq!(ca.rows[1].declared_date, None); + assert_eq!(ca.rows[1].known_at_source, KnownAtSource::ExDateFallback); + + // RY:CA dividend has declared_date -> DeclaredDate. + assert_eq!(ca.rows[2].key, 303); + assert_eq!(ca.rows[2].kind, CorporateActionKind::Dividend); + assert_eq!(ca.rows[2].cash_amount, Some(1.42)); + assert_eq!(ca.rows[2].currency.as_deref(), Some("CAD")); + assert_eq!(ca.rows[2].declared_date, Some(day(2024, 10, 30))); + assert_eq!(ca.rows[2].known_at_source, KnownAtSource::DeclaredDate); +} diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs new file mode 100644 index 00000000..40bcacdf --- /dev/null +++ b/tools/curate-etl/src/bson_stream.rs @@ -0,0 +1,661 @@ +//! Bounded-memory streaming reader for concatenated raw BSON (`M1.2y`). +//! +//! Reads length-prefixed raw BSON documents from any [`std::io::Read`] source (files, stdin pipes, +//! or future cursor adapters) into a single reused byte buffer with a fixed memory ceiling, +//! framing only complete documents into [`RawBsonChunk`] slices that can be passed directly to the +//! existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, +//! `decode_qm_dividend_buffer`). +//! +//! # Callback Lifetime Bound (`for<'a>`) +//! +//! Because [`RawBsonChunkReader`] reuses one internal byte buffer across chunks, borrowed zero-copy +//! document views ([`RawEodDailyBar<'a>`], [`RawQmSplit<'a>`], [`RawQmDividend<'a>`]) only remain +//! valid for the duration of the chunk in which they were decoded. The streaming decode helpers +//! ([`decode_eod_price_stream`], [`decode_qm_split_stream`], [`decode_qm_dividend_stream`], and +//! their `*_chunks` counterparts) therefore require higher-ranked callbacks +//! (`F: for<'a> FnMut(RawEodDailyBar<'a>)`, etc.) so closures cannot escape borrowed slices past a +//! chunk boundary. Callers should map or intern borrowed keys (e.g. via +//! `ProviderMappingTable::resolve`) or copy only the retained fields inside the callback. + +use std::error::Error; +use std::fmt; +use std::io; + +use crate::bson_eod_prices::{ + decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar, +}; +use crate::bson_qm_actions::{ + decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError, + RawQmDividend, RawQmSplit, +}; + +/// Default chunk buffer capacity: 8 MiB. +pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024; +/// Default maximum allowed BSON document size: 16 MiB (MongoDB limit) + 16 KiB headroom. +pub const DEFAULT_MAX_DOC_BYTES: usize = 16 * 1024 * 1024 + 16 * 1024; +/// Minimum valid length-prefixed BSON document size (4-byte length prefix + trailing `0x00`). +pub const MIN_BSON_DOC_BYTES: usize = 5; + +/// Configuration options for [`RawBsonChunkReader`] and the `decode_*_stream` helpers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BsonStreamOptions { + /// Initial reusable buffer size in bytes (capped at `max_doc_bytes`). Must be `> 0`. + pub chunk_capacity_bytes: usize, + /// Hard upper bound on any single BSON document's declared byte length. Must be `>= 5`. + pub max_doc_bytes: usize, +} + +impl Default for BsonStreamOptions { + #[inline] + fn default() -> Self { + Self { + chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + } + } +} + +impl BsonStreamOptions { + /// Validates option invariants, rejecting `chunk_capacity_bytes == 0` and `max_doc_bytes < 5`. + #[inline] + pub fn validate(&self) -> Result<(), BsonStreamError> { + if self.chunk_capacity_bytes == 0 { + return Err(BsonStreamError::InvalidChunkCapacity); + } + if self.max_doc_bytes < MIN_BSON_DOC_BYTES { + return Err(BsonStreamError::InvalidMaxDocBytes); + } + Ok(()) + } +} + +/// Terminal errors returned by [`RawBsonChunkReader`] and the `decode_*_stream` helpers. +/// +/// Every stream-level framing or I/O error carries the absolute byte `offset` of the offending +/// document in the underlying stream. +#[derive(Debug)] +pub enum BsonStreamError { + /// `BsonStreamOptions::chunk_capacity_bytes` was `0`. + InvalidChunkCapacity, + /// `BsonStreamOptions::max_doc_bytes` was `< 5`. + InvalidMaxDocBytes, + /// Declared 4-byte little-endian BSON document length was `< 5` or `> max_doc_bytes`. + CorruptDocumentLength { + offset: u64, + declared_len: i32, + max_doc_bytes: usize, + }, + /// Stream reached EOF mid-header (`declared_len == None`) or mid-document (`Some(len)`). + TruncatedDocument { + offset: u64, + remaining: usize, + declared_len: Option, + }, + /// Underlying [`std::io::Read`] failed with a non-`Interrupted` error. + Io { offset: u64, source: io::Error }, +} + +impl fmt::Display for BsonStreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidChunkCapacity => { + write!(f, "invalid BSON stream chunk_capacity_bytes: must be > 0") + } + Self::InvalidMaxDocBytes => { + write!( + f, + "invalid BSON stream max_doc_bytes: must be >= {MIN_BSON_DOC_BYTES}" + ) + } + Self::CorruptDocumentLength { + offset, + declared_len, + max_doc_bytes, + } => write!( + f, + "corrupt BSON document length {declared_len} at stream offset {offset} (valid range: {MIN_BSON_DOC_BYTES}..={max_doc_bytes})" + ), + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => match declared_len { + Some(len) => write!( + f, + "truncated BSON document at stream offset {offset}: declared length {len} exceeds remaining {remaining} bytes" + ), + None => write!( + f, + "truncated BSON document header at stream offset {offset}: only {remaining} bytes remaining" + ), + }, + Self::Io { offset, source } => { + write!( + f, + "I/O error reading BSON stream at offset {offset}: {source}" + ) + } + } + } +} + +impl Error for BsonStreamError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Io { source, .. } => Some(source), + _ => None, + } + } +} + +/// A borrowed chunk of complete, length-prefixed raw BSON documents from [`RawBsonChunkReader`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RawBsonChunk<'a> { + /// Contiguous bytes containing one or more complete length-prefixed BSON documents. + pub bytes: &'a [u8], + /// Absolute byte offset of `bytes[0]` from the start of the underlying stream. + pub start_offset: u64, +} + +#[derive(Debug, Clone)] +enum StickyError { + CorruptDocumentLength { + offset: u64, + declared_len: i32, + max_doc_bytes: usize, + }, + TruncatedDocument { + offset: u64, + remaining: usize, + declared_len: Option, + }, + Io { + offset: u64, + kind: io::ErrorKind, + message: String, + }, +} + +impl StickyError { + fn to_error(&self) -> BsonStreamError { + match self { + Self::CorruptDocumentLength { + offset, + declared_len, + max_doc_bytes, + } => BsonStreamError::CorruptDocumentLength { + offset: *offset, + declared_len: *declared_len, + max_doc_bytes: *max_doc_bytes, + }, + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonStreamError::TruncatedDocument { + offset: *offset, + remaining: *remaining, + declared_len: *declared_len, + }, + Self::Io { + offset, + kind, + message, + } => BsonStreamError::Io { + offset: *offset, + source: io::Error::new(*kind, message.clone()), + }, + } + } +} + +#[derive(Debug)] +enum TerminalState { + Active, + Eof, + Failed(StickyError), +} + +#[inline] +fn read_i32_le(bytes: &[u8]) -> i32 { + i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) +} + +/// Bounded-memory chunked reader for concatenated length-prefixed raw BSON documents. +/// +/// Reuses a single internal byte buffer across all calls to [`Self::next_chunk`], carrying any +/// trailing partial document to the front of the buffer before the next fill. The initial +/// allocation is capped at `min(options.chunk_capacity_bytes, options.max_doc_bytes)`; the buffer +/// grows only when a single document exceeds the current buffer length (or to 4 bytes when +/// `chunk_capacity_bytes < 4`), and never beyond `options.max_doc_bytes`. +pub struct RawBsonChunkReader { + reader: R, + options: BsonStreamOptions, + buf: Vec, + filled: usize, + consumed: usize, + buf_start_offset: u64, + bytes_read: u64, + docs_framed: u64, + eof_reached: bool, + pending_io_err: Option, + terminal: TerminalState, +} + +impl RawBsonChunkReader { + /// Creates a new chunk reader with [`BsonStreamOptions::default`]. + pub fn new(reader: R) -> Self { + let options = BsonStreamOptions::default(); + let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes); + Self { + reader, + options, + buf: vec![0u8; initial_cap], + filled: 0, + consumed: 0, + buf_start_offset: 0, + bytes_read: 0, + docs_framed: 0, + eof_reached: false, + pending_io_err: None, + terminal: TerminalState::Active, + } + } + + /// Creates a new chunk reader with explicit [`BsonStreamOptions`], validating them up front. + pub fn with_options(reader: R, options: BsonStreamOptions) -> Result { + options.validate()?; + let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes); + Ok(Self { + reader, + options, + buf: vec![0u8; initial_cap], + filled: 0, + consumed: 0, + buf_start_offset: 0, + bytes_read: 0, + docs_framed: 0, + eof_reached: false, + pending_io_err: None, + terminal: TerminalState::Active, + }) + } + + /// Returns the configured stream options. + #[inline] + pub fn options(&self) -> BsonStreamOptions { + self.options + } + + /// Returns the current allocated capacity of the reusable internal buffer in bytes. + #[inline] + pub fn buffer_capacity(&self) -> usize { + self.buf.capacity() + } + + /// Returns the total number of bytes read from the underlying reader so far. + #[inline] + pub fn bytes_read(&self) -> u64 { + self.bytes_read + } + + /// Returns the total number of complete length-prefixed documents framed and yielded so far. + #[inline] + pub fn docs_framed(&self) -> u64 { + self.docs_framed + } + + /// Consumes the chunk reader, returning the underlying [`std::io::Read`] source. + #[inline] + pub fn into_inner(self) -> R { + self.reader + } + + /// Grows `self.buf` to exactly `target_len` without doubling past `max_doc_bytes`. + fn grow_buf_exact(&mut self, target_len: usize) { + debug_assert!(target_len <= self.options.max_doc_bytes); + if target_len > self.buf.len() { + if target_len > self.buf.capacity() { + self.buf.reserve_exact(target_len - self.buf.len()); + } + self.buf.resize(target_len, 0); + } + } + + /// Reads and frames the next chunk of complete length-prefixed BSON documents. + /// + /// Returns `Ok(None)` at clean EOF. Any terminal framing or I/O error locks the reader into a + /// failed state so subsequent calls continue returning an error without panicking or looping. + pub fn next_chunk(&mut self) -> Result>, BsonStreamError> { + match &self.terminal { + TerminalState::Active => {} + TerminalState::Eof => return Ok(None), + TerminalState::Failed(err) => return Err(err.to_error()), + } + + // Compact bytes already yielded by the previous chunk. + if self.consumed > 0 { + if self.consumed < self.filled { + self.buf.copy_within(self.consumed..self.filled, 0); + } + self.filled -= self.consumed; + self.buf_start_offset += self.consumed as u64; + self.consumed = 0; + } + + let mut chunk_end = 0usize; + let mut chunk_docs = 0u64; + loop { + // Incrementally frame complete documents as bytes arrive so a corrupt length prefix + // stops the fill loop immediately without issuing further reads. + let mut saw_corrupt_len = false; + while self.filled - chunk_end >= 4 { + let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]); + if declared_len < MIN_BSON_DOC_BYTES as i32 + || (declared_len as usize) > self.options.max_doc_bytes + { + if chunk_end == 0 { + let err = StickyError::CorruptDocumentLength { + offset: self.buf_start_offset, + declared_len, + max_doc_bytes: self.options.max_doc_bytes, + }; + self.terminal = TerminalState::Failed(err.clone()); + return Err(err.to_error()); + } + // Yield any complete preceding documents first; the next call will compact + // this corrupt header to index 0 and surface `CorruptDocumentLength`. + saw_corrupt_len = true; + break; + } + let doc_len = declared_len as usize; + if chunk_end == 0 + && doc_len > self.buf.len() + && !self.eof_reached + && self.pending_io_err.is_none() + { + self.grow_buf_exact(doc_len); + } + if doc_len > self.filled - chunk_end { + break; + } + chunk_end += doc_len; + chunk_docs += 1; + } + + if saw_corrupt_len || self.eof_reached || self.pending_io_err.is_some() { + break; + } + + if self.filled == self.buf.len() { + if self.filled < 4 { + // `chunk_capacity_bytes` was in `1..=3`; grow to 4 bytes (always <= max_doc_bytes). + self.grow_buf_exact(4); + } else { + // Buffer is full and the leading document fit in `self.buf.len()`, so at least + // one complete document is ready to yield. + break; + } + } + + match self.reader.read(&mut self.buf[self.filled..]) { + Ok(0) => { + self.eof_reached = true; + break; + } + Ok(n) => { + self.filled += n; + self.bytes_read += n as u64; + } + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => { + self.pending_io_err = Some(err); + break; + } + } + } + + if chunk_end > 0 { + self.consumed = chunk_end; + self.docs_framed += chunk_docs; + return Ok(Some(RawBsonChunk { + bytes: &self.buf[..chunk_end], + start_offset: self.buf_start_offset, + })); + } + + // No complete document could be framed; surface pending I/O error, clean EOF, or truncation. + if let Some(source) = self.pending_io_err.take() { + let offset = self.buf_start_offset; + self.terminal = TerminalState::Failed(StickyError::Io { + offset, + kind: source.kind(), + message: source.to_string(), + }); + return Err(BsonStreamError::Io { offset, source }); + } + + if self.filled == 0 { + self.terminal = TerminalState::Eof; + return Ok(None); + } + + let declared_len = if self.filled >= 4 { + Some(read_i32_le(&self.buf[0..4])) + } else { + None + }; + let err = StickyError::TruncatedDocument { + offset: self.buf_start_offset, + remaining: self.filled, + declared_len, + }; + self.terminal = TerminalState::Failed(err.clone()); + Err(err.to_error()) + } +} + +#[inline] +fn rebase_offset(base: u64, local: usize) -> usize { + let abs = base.saturating_add(local as u64); + usize::try_from(abs).unwrap_or(usize::MAX) +} + +#[inline] +fn rebase_eod_error(base: u64, err: BsonEodPriceError) -> BsonEodPriceError { + match err { + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonEodPriceError::TruncatedDocument { + offset: rebase_offset(base, offset), + remaining, + declared_len, + }, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + } => BsonEodPriceError::CorruptDocumentLength { + offset: rebase_offset(base, offset), + declared_len, + }, + BsonEodPriceError::CorruptBson { offset, detail } => BsonEodPriceError::CorruptBson { + offset: rebase_offset(base, offset), + detail, + }, + other => other, + } +} + +#[inline] +fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError { + match err { + BsonQmActionError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonQmActionError::TruncatedDocument { + offset: rebase_offset(base, offset), + remaining, + declared_len, + }, + BsonQmActionError::CorruptDocumentLength { + offset, + declared_len, + } => BsonQmActionError::CorruptDocumentLength { + offset: rebase_offset(base, offset), + declared_len, + }, + BsonQmActionError::CorruptBson { offset, detail } => BsonQmActionError::CorruptBson { + offset: rebase_offset(base, offset), + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`], +/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream +/// byte offsets. +pub fn decode_eod_price_chunks( + reader: &mut RawBsonChunkReader, + mut on_bar: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawEodDailyBar<'a>), + E: FnMut(u64, BsonEodPriceError), +{ + let mut total = BsonEodDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_eod_price_buffer( + chunk.bytes, + &mut on_bar, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_eod_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `eodPrices` [`std::io::Read`] source through +/// [`decode_eod_price_buffer`] with bounded memory. +/// +/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset +/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. +pub fn decode_eod_price_stream( + reader: R, + options: BsonStreamOptions, + on_bar: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawEodDailyBar<'a>), + E: FnMut(u64, BsonEodPriceError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_eod_price_chunks(&mut chunk_reader, on_bar, on_error) +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_split_buffer`], +/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute +/// stream byte offsets. +pub fn decode_qm_split_chunks( + reader: &mut RawBsonChunkReader, + mut on_split: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmSplit<'a>), + E: FnMut(u64, BsonQmActionError), +{ + let mut total = BsonQmActionDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_qm_split_buffer( + chunk.bytes, + &mut on_split, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_qm_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmSplits` [`std::io::Read`] source through +/// [`decode_qm_split_buffer`] with bounded memory. +pub fn decode_qm_split_stream( + reader: R, + options: BsonStreamOptions, + on_split: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmSplit<'a>), + E: FnMut(u64, BsonQmActionError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_split_chunks(&mut chunk_reader, on_split, on_error) +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_dividend_buffer`], +/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute +/// stream byte offsets. +pub fn decode_qm_dividend_chunks( + reader: &mut RawBsonChunkReader, + mut on_dividend: F, + mut on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmDividend<'a>), + E: FnMut(u64, BsonQmActionError), +{ + let mut total = BsonQmActionDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_qm_dividend_buffer( + chunk.bytes, + &mut on_dividend, + |local_offset, err| { + let abs_offset = base + local_offset as u64; + on_error(abs_offset, rebase_qm_error(base, err)); + }, + ); + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmDividends` [`std::io::Read`] source through +/// [`decode_qm_dividend_buffer`] with bounded memory. +pub fn decode_qm_dividend_stream( + reader: R, + options: BsonStreamOptions, + on_dividend: F, + on_error: E, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmDividend<'a>), + E: FnMut(u64, BsonQmActionError), +{ + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error) +} + +#[cfg(test)] +#[path = "bson_stream_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs new file mode 100644 index 00000000..4edeca31 --- /dev/null +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -0,0 +1,1724 @@ +use std::error::Error as _; +use std::io::{self, Cursor, Read}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime; + +use crate::bson_eod_prices::{ + decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats, +}; +use crate::bson_qm_actions::{ + decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, +}; +use crate::bson_stream::{ + decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_split_stream, BsonStreamError, + BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, + MIN_BSON_DOC_BYTES, +}; + +#[derive(Debug, Clone, Copy)] +struct SplitMix64(u64); + +impl SplitMix64 { + fn new(seed: u64) -> Self { + Self(seed) + } + + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +/// Reader returning at most `max_step` bytes per `read()` call. +struct FixedStepReader<'a> { + data: &'a [u8], + pos: usize, + max_step: usize, +} + +impl<'a> FixedStepReader<'a> { + fn new(data: &'a [u8], max_step: usize) -> Self { + Self { + data, + pos: 0, + max_step: max_step.max(1), + } + } +} + +impl Read for FixedStepReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let take = remaining.min(self.max_step).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +/// Reader returning deterministic pseudo-random read sizes and optional `Interrupted` errors. +struct RandomInterruptReader<'a> { + data: &'a [u8], + pos: usize, + rng: SplitMix64, + inject_interrupts: bool, + calls: usize, +} + +impl<'a> RandomInterruptReader<'a> { + fn new(data: &'a [u8], seed: u64, inject_interrupts: bool) -> Self { + Self { + data, + pos: 0, + rng: SplitMix64::new(seed), + inject_interrupts, + calls: 0, + } + } +} + +impl Read for RandomInterruptReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.calls += 1; + if self.inject_interrupts && self.calls % 3 == 0 { + return Err(io::Error::new( + io::ErrorKind::Interrupted, + "simulated EINTR", + )); + } + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let max_chunk = (self.rng.next_u64() as usize % 511) + 1; + let take = remaining.min(max_chunk).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +/// Reader that delivers scripted chunks and then returns a terminal `io::Error`. +struct FailingReader { + data: Vec, + pos: usize, + fail_kind: io::ErrorKind, + fail_msg: &'static str, + failed: bool, + reads_after_fail: usize, +} + +impl FailingReader { + fn new(data: Vec, fail_kind: io::ErrorKind, fail_msg: &'static str) -> Self { + Self { + data, + pos: 0, + fail_kind, + fail_msg, + failed: false, + reads_after_fail: 0, + } + } +} + +impl Read for FailingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.failed { + self.reads_after_fail += 1; + return Err(io::Error::new(self.fail_kind, "read after terminal fail")); + } + let remaining = self.data.len() - self.pos; + if remaining == 0 { + self.failed = true; + return Err(io::Error::new(self.fail_kind, self.fail_msg)); + } + let take = remaining.min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +fn make_eod_doc(code: &str, date: &str, open: f64, high: f64, low: f64, close: f64, vol: i64) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), vol); + doc.into_bytes() +} + +/// Builds a validly length-prefixed BSON document whose trailing null terminator is corrupted +/// (`0xFF` instead of `0x00`), triggering `CorruptBson` inside `iter_raw_bson_docs` while still +/// cleanly advancing past the document. +fn make_corrupt_bson_doc(len: usize) -> Vec { + assert!(len >= MIN_BSON_DOC_BYTES); + let mut bytes = vec![0u8; len]; + bytes[0..4].copy_from_slice(&(len as i32).to_le_bytes()); + bytes[len - 1] = 0xFF; + bytes +} + +fn build_mixed_eod_fixture() -> Vec { + let mut out = Vec::new(); + // 1. Valid with extra metadata fields. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), "AAPL"); + doc.append(cstr!("exchange"), "NASDAQ"); + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("open"), 195.5_f64); + doc.append(cstr!("high"), 198.0_f64); + doc.append(cstr!("low"), 194.25_f64); + doc.append(cstr!("close"), 197.1_f64); + doc.append(cstr!("volume"), 42_000_000_i64); + doc.append(cstr!("adjustedClose"), 197.1_f64); + out.extend_from_slice(doc.as_bytes()); + } + // 2. Missing required field (`volume`). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "MSFT.US"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("open"), 420.0_f64); + doc.append(cstr!("high"), 425.0_f64); + doc.append(cstr!("low"), 419.0_f64); + doc.append(cstr!("close"), 424.0_f64); + out.extend_from_slice(doc.as_bytes()); + } + // 3. Empty string field (`eodSearchCode`). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), " "); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.5_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + out.extend_from_slice(doc.as_bytes()); + } + // 4. Valid with BSON DateTime and Int32 numerics. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "RY.TO"); + doc.append(cstr!("date"), DateTime::from_millis(19_884_i64 * 86_400_000)); + doc.append(cstr!("open"), 140_i32); + doc.append(cstr!("high"), 142_i32); + doc.append(cstr!("low"), 139_i32); + doc.append(cstr!("close"), 141_i32); + doc.append(cstr!("volume"), 0_i32); + out.extend_from_slice(doc.as_bytes()); + } + // 5. Length-framed CorruptBson (exercises offset rebasing across chunk boundaries). + out.extend_from_slice(&make_corrupt_bson_doc(37)); + // 6. WrongType on `open`. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("date"), "2024-06-11"); + doc.append(cstr!("open"), "not-a-number"); + doc.append(cstr!("high"), 122.0_f64); + doc.append(cstr!("low"), 118.0_f64); + doc.append(cstr!("close"), 121.0_f64); + doc.append(cstr!("volume"), 1_000_i64); + out.extend_from_slice(doc.as_bytes()); + } + // 7. MalformedDate. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "TD.TO"); + doc.append(cstr!("date"), "2023-02-29"); + doc.append(cstr!("open"), 80.0_f64); + doc.append(cstr!("high"), 81.0_f64); + doc.append(cstr!("low"), 79.0_f64); + doc.append(cstr!("close"), 80.5_f64); + doc.append(cstr!("volume"), 500_i64); + out.extend_from_slice(doc.as_bytes()); + } + // 8. InvalidNumber (negative high). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "BCE.TO"); + doc.append(cstr!("date"), "2024-06-12"); + doc.append(cstr!("open"), 45.0_f64); + doc.append(cstr!("high"), -46.0_f64); + doc.append(cstr!("low"), 44.0_f64); + doc.append(cstr!("close"), 45.5_f64); + doc.append(cstr!("volume"), 500_i64); + out.extend_from_slice(doc.as_bytes()); + } + // 9..24. More valid docs + another CorruptBson so multi-chunk streams span many boundaries. + for i in 0..16 { + out.extend_from_slice(&make_eod_doc( + &format!("SYM{i:03}.US"), + "2024-06-14", + 10.0 + i as f64, + 11.0 + i as f64, + 9.5 + i as f64, + 10.5 + i as f64, + 10_000 + i as i64 * 100, + )); + } + out.extend_from_slice(&make_corrupt_bson_doc(23)); + out.extend_from_slice(&make_eod_doc( + "FINAL.TO", + "2024-06-15", + 50.0, + 52.0, + 49.5, + 51.25, + 99_999, + )); + out +} + +fn build_mixed_qm_split_fixture() -> Vec { + let mut out = Vec::new(); + // 1. Valid forward split with declared date and extra fields. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), "NVDA"); + doc.append(cstr!("usdFxRate"), 1_i32); + doc.append(cstr!("qmSearchCode"), "NVDA"); + doc.append(cstr!("date"), "2024-06-10"); + doc.append(cstr!("declared"), "2024-05-22"); + doc.append(cstr!("splitratio"), 10.0_f64); + out.extend_from_slice(doc.as_bytes()); + } + // 2. Valid ratio == 1.0 no-op (preserved and counted in split_noop_ratio_one). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NOOP"); + doc.append(cstr!("date"), "2024-06-11"); + doc.append(cstr!("splitratio"), 1_i32); + out.extend_from_slice(doc.as_bytes()); + } + // 3. InvalidNumber (ratio <= 0). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "BAD"); + doc.append(cstr!("date"), "2024-06-12"); + doc.append(cstr!("splitratio"), 0.0_f64); + out.extend_from_slice(doc.as_bytes()); + } + // 4. Length-framed CorruptBson. + out.extend_from_slice(&make_corrupt_bson_doc(29)); + // 5. MissingField (`splitratio`). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "MISS"); + doc.append(cstr!("date"), "2024-06-13"); + out.extend_from_slice(doc.as_bytes()); + } + // 6. Reverse split with DateTime date. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "NEXM:CA"); + doc.append(cstr!("date"), DateTime::from_millis(20_257_i64 * 86_400_000)); + doc.append(cstr!("splitratio"), 0.05_f64); + out.extend_from_slice(doc.as_bytes()); + } + // 7..16. Additional valid splits. + for i in 0..10 { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), format!("SPL{i:02}")); + doc.append(cstr!("date"), "2024-06-14"); + doc.append(cstr!("splitratio"), if i % 4 == 0 { 1.0 } else { 2.0 + i as f64 }); + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn build_mixed_qm_dividend_fixture() -> Vec { + let mut out = Vec::new(); + // 1. Valid CAD dividend with bogus usdFxRate (ignored) and declared date. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "RY:CA"); + doc.append(cstr!("date"), "2024-07-25"); + doc.append(cstr!("declared"), "2024-05-30"); + doc.append(cstr!("amount"), 1.42_f64); + doc.append(cstr!("currency"), "CAD"); + doc.append(cstr!("usdFxRate"), 1_i32); + out.extend_from_slice(doc.as_bytes()); + } + // 2. EmptyField (`currency`). + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "TD:CA"); + doc.append(cstr!("date"), "2024-07-25"); + doc.append(cstr!("amount"), 1.02_f64); + doc.append(cstr!("currency"), " "); + out.extend_from_slice(doc.as_bytes()); + } + // 3. Length-framed CorruptBson. + out.extend_from_slice(&make_corrupt_bson_doc(31)); + // 4. MalformedDate. + { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), "AAPL"); + doc.append(cstr!("date"), "not-a-date"); + doc.append(cstr!("amount"), 0.25_f64); + doc.append(cstr!("currency"), "USD"); + out.extend_from_slice(doc.as_bytes()); + } + // 5..16. Additional valid USD/CAD dividends. + for i in 0..12 { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), format!("DIV{i:02}")); + doc.append(cstr!("date"), "2024-07-26"); + doc.append(cstr!("amount"), 0.10 * (i as f64)); + doc.append(cstr!("currency"), if i % 2 == 0 { "USD" } else { "CAD" }); + out.extend_from_slice(doc.as_bytes()); + } + out +} + +#[derive(Debug, PartialEq)] +struct OwnedEodBar { + code: String, + session_date: i32, + open: u64, + high: u64, + low: u64, + close: u64, + adj_volume: u64, +} + +#[derive(Debug, PartialEq)] +struct OwnedQmSplit { + code: String, + ex_date: i32, + ratio: u64, + declared_date: Option, +} + +#[derive(Debug, PartialEq)] +struct OwnedQmDividend { + code: String, + ex_date: i32, + cash: u64, + currency: String, + declared_date: Option, +} + +#[test] +fn rejects_invalid_options_and_accepts_valid_boundaries() { + assert!(matches!( + RawBsonChunkReader::with_options( + Cursor::new(&[][..]), + BsonStreamOptions { + chunk_capacity_bytes: 0, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + } + ), + Err(BsonStreamError::InvalidChunkCapacity) + )); + assert!(matches!( + RawBsonChunkReader::with_options( + Cursor::new(&[][..]), + BsonStreamOptions { + chunk_capacity_bytes: 1024, + max_doc_bytes: 4, + } + ), + Err(BsonStreamError::InvalidMaxDocBytes) + )); + assert!(matches!( + RawBsonChunkReader::with_options( + Cursor::new(&[][..]), + BsonStreamOptions { + chunk_capacity_bytes: 1024, + max_doc_bytes: 0, + } + ), + Err(BsonStreamError::InvalidMaxDocBytes) + )); + + let min_reader = RawBsonChunkReader::with_options( + Cursor::new(&[][..]), + BsonStreamOptions { + chunk_capacity_bytes: 1, + max_doc_bytes: MIN_BSON_DOC_BYTES, + }, + ) + .expect("minimum valid options must succeed"); + assert_eq!(min_reader.buffer_capacity(), 1); + assert_eq!(min_reader.options().chunk_capacity_bytes, 1); + assert_eq!(min_reader.options().max_doc_bytes, MIN_BSON_DOC_BYTES); + + let default_reader = RawBsonChunkReader::new(Cursor::new(&[][..])); + assert_eq!( + default_reader.options(), + BsonStreamOptions { + chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + } + ); + let _inner: Cursor<&[u8]> = default_reader.into_inner(); +} + +#[test] +fn empty_input_returns_none_and_zero_stats() { + let mut reader = RawBsonChunkReader::with_options( + Cursor::new(&[][..]), + BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 1024, + }, + ) + .unwrap(); + assert!(reader.next_chunk().unwrap().is_none()); + assert!(reader.next_chunk().unwrap().is_none()); + assert_eq!(reader.bytes_read(), 0); + assert_eq!(reader.docs_framed(), 0); + + let opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 1024, + }; + let eod_stats = decode_eod_price_stream( + Cursor::new(&[][..]), + opts, + |_| panic!("unexpected bar on empty input"), + |_, _| panic!("unexpected error on empty input"), + ) + .unwrap(); + assert_eq!(eod_stats, BsonEodDecodeStats::default()); + + let split_stats = decode_qm_split_stream( + Cursor::new(&[][..]), + opts, + |_| panic!("unexpected split on empty input"), + |_, _| panic!("unexpected error on empty input"), + ) + .unwrap(); + assert_eq!(split_stats, BsonQmActionDecodeStats::default()); + + let div_stats = decode_qm_dividend_stream( + Cursor::new(&[][..]), + opts, + |_| panic!("unexpected dividend on empty input"), + |_, _| panic!("unexpected error on empty input"), + ) + .unwrap(); + assert_eq!(div_stats, BsonQmActionDecodeStats::default()); +} + +#[test] +fn chunk_invariants_hold_across_capacities_including_tiny_headers() { + let mut input = Vec::new(); + let doc_count = 30usize; + for i in 0..doc_count { + input.extend_from_slice(&make_eod_doc( + &format!("CHK{i:03}.US"), + "2024-06-10", + 10.0 + i as f64, + 11.0 + i as f64, + 9.0 + i as f64, + 10.5 + i as f64, + 1_000 + i as i64, + )); + } + + for cap in [1, 2, 3, 4, 5, 64, 256, input.len(), input.len() + 512] { + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&input, 7), + BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let mut reconstructed = Vec::new(); + let mut expected_offset = 0u64; + let mut total_reframed_docs = 0u64; + + while let Some(chunk) = reader.next_chunk().unwrap() { + assert!(!chunk.bytes.is_empty(), "yielded chunk must be non-empty"); + assert_eq!(chunk.start_offset, expected_offset); + expected_offset += chunk.bytes.len() as u64; + reconstructed.extend_from_slice(chunk.bytes); + + let mut consumed_in_chunk = 0usize; + for item in iter_raw_bson_docs(chunk.bytes) { + let doc = item.expect("chunk must contain only cleanly framed whole docs"); + consumed_in_chunk += doc.as_bytes().len(); + total_reframed_docs += 1; + } + assert_eq!(consumed_in_chunk, chunk.bytes.len()); + } + + assert!(reader.next_chunk().unwrap().is_none()); + assert_eq!(reconstructed, input); + assert_eq!(expected_offset, input.len() as u64); + assert_eq!(reader.bytes_read(), input.len() as u64); + assert_eq!(reader.docs_framed(), doc_count as u64); + assert_eq!(total_reframed_docs, doc_count as u64); + } +} + +#[test] +fn decode_eod_price_stream_matches_buffer_across_readers_and_capacities() { + let fixture = build_mixed_eod_fixture(); + + let mut expected_bars = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_eod_price_buffer( + &fixture, + |bar| { + expected_bars.push(OwnedEodBar { + code: bar.eod_search_code.to_owned(), + session_date: bar.session_date, + open: bar.open.to_bits(), + high: bar.high.to_bits(), + low: bar.low.to_bits(), + close: bar.close.to_bits(), + adj_volume: bar.adj_volume.to_bits(), + }); + }, + |offset, err| expected_errs.push((offset as u64, err)), + ); + assert!(expected_stats.decoded > 0); + assert!(expected_stats.rejected_total() >= 7); + assert_eq!( + expected_stats.decoded + expected_stats.rejected_total(), + expected_stats.docs_in + ); + + let capacities = [64, 256, 512, fixture.len(), fixture.len() + 4096]; + + for &cap in &capacities { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; + + let modes: [(&str, Box); 5] = [ + ("1-byte", Box::new(FixedStepReader::new(&fixture, 1))), + ("7-byte", Box::new(FixedStepReader::new(&fixture, 7))), + ("4093-byte", Box::new(FixedStepReader::new(&fixture, 4093))), + ( + "random", + Box::new(RandomInterruptReader::new(&fixture, 0xA11C_E0D1, false)), + ), + ( + "random+EINTR", + Box::new(RandomInterruptReader::new(&fixture, 0xB22D_E0D2, true)), + ), + ]; + + for (label, reader) in modes { + let mut got_bars = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_eod_price_stream( + reader, + opts, + |bar| { + got_bars.push(OwnedEodBar { + code: bar.eod_search_code.to_owned(), + session_date: bar.session_date, + open: bar.open.to_bits(), + high: bar.high.to_bits(), + low: bar.low.to_bits(), + close: bar.close.to_bits(), + adj_volume: bar.adj_volume.to_bits(), + }); + }, + |offset, err| got_errs.push((offset, err)), + ) + .unwrap_or_else(|e| panic!("cap={cap} mode={label} failed: {e}")); + + assert_eq!(got_stats, expected_stats, "stats mismatch cap={cap} mode={label}"); + assert_eq!(got_bars, expected_bars, "bars mismatch cap={cap} mode={label}"); + assert_eq!(got_errs, expected_errs, "errors mismatch cap={cap} mode={label}"); + } + } +} + +#[test] +fn decode_qm_split_stream_matches_buffer_across_readers_and_capacities() { + let fixture = build_mixed_qm_split_fixture(); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_split_buffer( + &fixture, + |s| { + expected_rows.push(OwnedQmSplit { + code: s.qm_search_code.to_owned(), + ex_date: s.ex_date, + ratio: s.ratio.to_bits(), + declared_date: s.declared_date, + }); + }, + |offset, err| expected_errs.push((offset as u64, err)), + ); + assert!(expected_stats.decoded > 0); + assert!(expected_stats.split_noop_ratio_one > 0); + assert!(expected_stats.rejected_total() >= 3); + + for &cap in &[48, 192, fixture.len(), fixture.len() + 1024] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; + let modes: [(&str, Box); 5] = [ + ("1-byte", Box::new(FixedStepReader::new(&fixture, 1))), + ("7-byte", Box::new(FixedStepReader::new(&fixture, 7))), + ("4093-byte", Box::new(FixedStepReader::new(&fixture, 4093))), + ( + "random", + Box::new(RandomInterruptReader::new(&fixture, 0xC33E_5917, false)), + ), + ( + "random+EINTR", + Box::new(RandomInterruptReader::new(&fixture, 0xD44F_5918, true)), + ), + ]; + + for (label, reader) in modes { + let mut got_rows = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_qm_split_stream( + reader, + opts, + |s| { + got_rows.push(OwnedQmSplit { + code: s.qm_search_code.to_owned(), + ex_date: s.ex_date, + ratio: s.ratio.to_bits(), + declared_date: s.declared_date, + }); + }, + |offset, err| got_errs.push((offset, err)), + ) + .unwrap_or_else(|e| panic!("split cap={cap} mode={label} failed: {e}")); + + assert_eq!(got_stats, expected_stats, "split stats cap={cap} mode={label}"); + assert_eq!(got_rows, expected_rows, "split rows cap={cap} mode={label}"); + assert_eq!(got_errs, expected_errs, "split errs cap={cap} mode={label}"); + } + } +} + +#[test] +fn decode_qm_dividend_stream_matches_buffer_across_readers_and_capacities() { + let fixture = build_mixed_qm_dividend_fixture(); + + let mut expected_rows = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_qm_dividend_buffer( + &fixture, + |d| { + expected_rows.push(OwnedQmDividend { + code: d.qm_search_code.to_owned(), + ex_date: d.ex_date, + cash: d.cash.to_bits(), + currency: d.currency.to_owned(), + declared_date: d.declared_date, + }); + }, + |offset, err| expected_errs.push((offset as u64, err)), + ); + assert!(expected_stats.decoded > 0); + assert!(expected_stats.rejected_total() >= 3); + + for &cap in &[48, 192, fixture.len(), fixture.len() + 1024] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; + let modes: [(&str, Box); 5] = [ + ("1-byte", Box::new(FixedStepReader::new(&fixture, 1))), + ("7-byte", Box::new(FixedStepReader::new(&fixture, 7))), + ("4093-byte", Box::new(FixedStepReader::new(&fixture, 4093))), + ( + "random", + Box::new(RandomInterruptReader::new(&fixture, 0xE550_D171, false)), + ), + ( + "random+EINTR", + Box::new(RandomInterruptReader::new(&fixture, 0xF661_D172, true)), + ), + ]; + + for (label, reader) in modes { + let mut got_rows = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_qm_dividend_stream( + reader, + opts, + |d| { + got_rows.push(OwnedQmDividend { + code: d.qm_search_code.to_owned(), + ex_date: d.ex_date, + cash: d.cash.to_bits(), + currency: d.currency.to_owned(), + declared_date: d.declared_date, + }); + }, + |offset, err| got_errs.push((offset, err)), + ) + .unwrap_or_else(|e| panic!("dividend cap={cap} mode={label} failed: {e}")); + + assert_eq!(got_stats, expected_stats, "div stats cap={cap} mode={label}"); + assert_eq!(got_rows, expected_rows, "div rows cap={cap} mode={label}"); + assert_eq!(got_errs, expected_errs, "div errs cap={cap} mode={label}"); + } + } +} + +#[test] +fn memory_ceiling_holds_over_one_megabyte_and_oversized_single_doc() { + // 1) >= 1,000,000 bytes of small docs with chunk_capacity_bytes = 4096. + let single_doc = make_eod_doc("MEM.US", "2024-06-10", 10.0, 11.0, 9.5, 10.5, 50_000); + let repeats = (1_050_000 / single_doc.len()) + 1; + let mut big_input = Vec::with_capacity(repeats * single_doc.len()); + for _ in 0..repeats { + big_input.extend_from_slice(&single_doc); + } + assert!(big_input.len() >= 1_000_000); + + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&big_input, 1009), + BsonStreamOptions { + chunk_capacity_bytes: 4096, + max_doc_bytes: 6000, + }, + ) + .unwrap(); + let mut total_bytes = 0usize; + while let Some(chunk) = reader.next_chunk().unwrap() { + total_bytes += chunk.bytes.len(); + assert!( + reader.buffer_capacity() <= 4096, + "capacity {} exceeded 4096 on small docs", + reader.buffer_capacity() + ); + } + assert_eq!(total_bytes, big_input.len()); + assert_eq!(reader.docs_framed(), repeats as u64); + + // 2) Single doc larger than chunk_capacity_bytes (4096) and equal to exact max_doc_bytes (6000). + let mut oversized = RawDocumentBuf::new(); + oversized.append(cstr!("eodSearchCode"), "BIG.US"); + oversized.append(cstr!("date"), "2024-06-10"); + oversized.append(cstr!("open"), 10.0_f64); + oversized.append(cstr!("high"), 11.0_f64); + oversized.append(cstr!("low"), 9.5_f64); + oversized.append(cstr!("close"), 10.5_f64); + oversized.append(cstr!("volume"), 1_000_i64); + // Pad with an extra string field so the total BSON length equals 6000 bytes exactly. + let base_len = oversized.as_bytes().len(); + // Adding string element "pad" costs: 1 (type) + 4 ("pad\0") + 4 (i32 len) + pad_len + 1 (null). + let pad_len = 6000 - base_len - 10; + oversized.append(cstr!("pad"), "x".repeat(pad_len)); + let oversized_bytes = oversized.into_bytes(); + assert_eq!(oversized_bytes.len(), 6000); + + let mut stream_bytes = Vec::new(); + stream_bytes.extend_from_slice(&single_doc); + stream_bytes.extend_from_slice(&oversized_bytes); + stream_bytes.extend_from_slice(&single_doc); + + let mut oversized_reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&stream_bytes, 331), + BsonStreamOptions { + chunk_capacity_bytes: 4096, + max_doc_bytes: 6000, + }, + ) + .unwrap(); + let mut reconstructed = Vec::new(); + while let Some(chunk) = oversized_reader.next_chunk().unwrap() { + reconstructed.extend_from_slice(chunk.bytes); + assert!( + oversized_reader.buffer_capacity() <= 6000, + "capacity {} exceeded max_doc_bytes 6000", + oversized_reader.buffer_capacity() + ); + } + assert_eq!(reconstructed, stream_bytes); + assert_eq!(oversized_reader.docs_framed(), 3); + assert_eq!(oversized_reader.buffer_capacity(), 6000); +} + +#[test] +fn corrupt_document_length_delivers_valid_prefix_and_is_sticky() { + let valid_doc = make_eod_doc("OK.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let prefix_len = valid_doc.len() as u64; + let max_doc = 512usize; + + for bad_len in [0_i32, 4, -1, i32::MIN, (max_doc as i32) + 1] { + let mut bytes = valid_doc.clone(); + bytes.extend_from_slice(&bad_len.to_le_bytes()); + bytes.extend_from_slice(&[0u8; 16]); + + let mut reader = RawBsonChunkReader::with_options( + Cursor::new(bytes), + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: max_doc, + }, + ) + .unwrap(); + + // First chunk delivers the valid prefix document intact. + let chunk = reader + .next_chunk() + .expect("valid prefix must succeed") + .expect("expected valid prefix chunk"); + assert_eq!(chunk.start_offset, 0); + assert_eq!(chunk.bytes, valid_doc.as_slice()); + + // Second call surfaces CorruptDocumentLength at exact offset of the bad header. + let err = reader.next_chunk().unwrap_err(); + assert!( + matches!( + err, + BsonStreamError::CorruptDocumentLength { + offset, + declared_len, + max_doc_bytes, + } if offset == prefix_len && declared_len == bad_len && max_doc_bytes == max_doc + ), + "unexpected error for bad_len={bad_len}: {err:?}" + ); + assert!(err.source().is_none()); + assert!(err.to_string().contains(&prefix_len.to_string())); + + // Sticky on repeated calls. + for _ in 0..3 { + assert!(matches!( + reader.next_chunk(), + Err(BsonStreamError::CorruptDocumentLength { offset, declared_len, .. }) + if offset == prefix_len && declared_len == bad_len + )); + } + } +} + +#[test] +fn truncated_header_and_truncated_body_deliver_prefix_and_are_sticky() { + let valid_doc = make_eod_doc("PRE.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let prefix_len = valid_doc.len() as u64; + + // 1) EOF inside the 4-byte length prefix (1, 2, 3 trailing bytes). + for tail_len in [1usize, 2, 3] { + let mut bytes = valid_doc.clone(); + bytes.extend_from_slice(&vec![0x20u8; tail_len]); + + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&bytes, 13), + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = reader.next_chunk().unwrap().unwrap(); + assert_eq!(chunk.bytes, valid_doc.as_slice()); + + let err = reader.next_chunk().unwrap_err(); + assert!( + matches!( + err, + BsonStreamError::TruncatedDocument { + offset, + remaining, + declared_len: None, + } if offset == prefix_len && remaining == tail_len + ), + "unexpected error for tail_len={tail_len}: {err:?}" + ); + assert!(err.to_string().contains(&prefix_len.to_string())); + + // Sticky. + assert!(matches!( + reader.next_chunk(), + Err(BsonStreamError::TruncatedDocument { + offset, + remaining, + declared_len: None, + }) if offset == prefix_len && remaining == tail_len + )); + } + + // 2) EOF mid-document body. + let mut mid_bytes = valid_doc.clone(); + mid_bytes.extend_from_slice(&valid_doc[..valid_doc.len() - 5]); + let expected_remaining = valid_doc.len() - 5; + let expected_declared = valid_doc.len() as i32; + + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&mid_bytes, 11), + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = reader.next_chunk().unwrap().unwrap(); + assert_eq!(chunk.bytes, valid_doc.as_slice()); + + let err = reader.next_chunk().unwrap_err(); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { + offset, + remaining, + declared_len: Some(declared), + } if offset == prefix_len && remaining == expected_remaining && declared == expected_declared + )); + assert!(err.to_string().contains(&prefix_len.to_string())); + + // Sticky. + assert!(matches!( + reader.next_chunk(), + Err(BsonStreamError::TruncatedDocument { offset, .. }) if offset == prefix_len + )); +} + +#[test] +fn io_error_delivers_valid_prefix_and_is_sticky_without_rereading() { + let valid_doc = make_eod_doc("IO.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let prefix_len = valid_doc.len() as u64; + + // 1) Valid doc followed by partial doc bytes, then BrokenPipe. + let mut partial = valid_doc.clone(); + partial.extend_from_slice(&valid_doc[..10]); + let mut reader = RawBsonChunkReader::with_options( + FailingReader::new(partial, io::ErrorKind::BrokenPipe, "pipe closed"), + BsonStreamOptions { + chunk_capacity_bytes: 512, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = reader.next_chunk().unwrap().unwrap(); + assert_eq!(chunk.bytes, valid_doc.as_slice()); + + let err = reader.next_chunk().unwrap_err(); + assert!(matches!( + err, + BsonStreamError::Io { offset, ref source } + if offset == prefix_len && source.kind() == io::ErrorKind::BrokenPipe + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("pipe closed")); + + // Sticky: subsequent calls return Io without touching underlying reader again. + for _ in 0..3 { + assert!(matches!( + reader.next_chunk(), + Err(BsonStreamError::Io { offset, ref source }) + if offset == prefix_len && source.kind() == io::ErrorKind::BrokenPipe + )); + } + assert_eq!(reader.into_inner().reads_after_fail, 0); + + // 2) Immediate Io error on first read -> offset 0. + let mut immediate = RawBsonChunkReader::with_options( + FailingReader::new(Vec::new(), io::ErrorKind::PermissionDenied, "denied"), + BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + assert!(matches!( + immediate.next_chunk(), + Err(BsonStreamError::Io { offset: 0, ref source }) + if source.kind() == io::ErrorKind::PermissionDenied + )); + assert!(matches!( + immediate.next_chunk(), + Err(BsonStreamError::Io { offset: 0, .. }) + )); + assert_eq!(immediate.into_inner().reads_after_fail, 0); +} + +#[test] +fn stats_merge_and_add_assign_sum_all_fields() { + let a = BsonEodDecodeStats { + docs_in: 10, + decoded: 4, + rejected_missing_field: 1, + rejected_empty_field: 1, + rejected_wrong_type: 1, + rejected_malformed_date: 1, + rejected_invalid_number: 1, + rejected_corrupt_document: 1, + }; + let b = BsonEodDecodeStats { + docs_in: 20, + decoded: 8, + rejected_missing_field: 2, + rejected_empty_field: 2, + rejected_wrong_type: 2, + rejected_malformed_date: 2, + rejected_invalid_number: 2, + rejected_corrupt_document: 2, + }; + let mut acc = a; + acc += b; + assert_eq!(acc.docs_in, 30); + assert_eq!(acc.decoded, 12); + assert_eq!(acc.rejected_total(), 18); + assert_eq!(acc.decoded + acc.rejected_total(), acc.docs_in); + + let q1 = BsonQmActionDecodeStats { + docs_in: 12, + decoded: 6, + split_noop_ratio_one: 2, + rejected_missing_field: 1, + rejected_empty_field: 1, + rejected_wrong_type: 1, + rejected_malformed_date: 1, + rejected_invalid_number: 1, + rejected_corrupt_document: 1, + }; + let mut q_acc = q1; + q_acc.merge(&q1); + assert_eq!(q_acc.docs_in, 24); + assert_eq!(q_acc.decoded, 12); + assert_eq!(q_acc.split_noop_ratio_one, 4); + assert_eq!(q_acc.rejected_total(), 12); + assert_eq!(q_acc.decoded + q_acc.rejected_total(), q_acc.docs_in); +} + +#[test] +fn initial_allocation_is_capped_at_max_doc_bytes() { + let max_doc = 1024 * 1024; + let empty_reader = RawBsonChunkReader::with_options( + Cursor::new(&[][..]), + BsonStreamOptions { + chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES, + max_doc_bytes: max_doc, + }, + ) + .expect("chunk_capacity_bytes > max_doc_bytes must succeed with capped buffer"); + assert!( + empty_reader.buffer_capacity() <= max_doc, + "initial capacity {} exceeded max_doc_bytes {max_doc}", + empty_reader.buffer_capacity() + ); + assert_eq!(empty_reader.buffer_capacity(), max_doc); + + // Also verify streaming valid docs when chunk_capacity_bytes > max_doc_bytes. + let doc = make_eod_doc("CAP.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let mut input = Vec::new(); + for _ in 0..8 { + input.extend_from_slice(&doc); + } + let small_max = 256usize; + assert!(doc.len() < small_max); + + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&input, 37), + BsonStreamOptions { + chunk_capacity_bytes: 4096, + max_doc_bytes: small_max, + }, + ) + .unwrap(); + assert_eq!(reader.buffer_capacity(), small_max); + + let mut reconstructed = Vec::new(); + while let Some(chunk) = reader.next_chunk().unwrap() { + reconstructed.extend_from_slice(chunk.bytes); + assert!(reader.buffer_capacity() <= small_max); + } + assert_eq!(reconstructed, input); + assert_eq!(reader.docs_framed(), 8); + assert!(reader.buffer_capacity() <= small_max); +} + +#[test] +fn corrupt_header_after_valid_doc_stops_fill_without_extra_read() { + struct ScriptedReader { + chunks: Vec>, + idx: usize, + read_calls: usize, + } + + impl Read for ScriptedReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.read_calls += 1; + if self.idx >= self.chunks.len() { + panic!( + "unexpected extra read #{} after supplying scripted chunks", + self.read_calls + ); + } + let src = &self.chunks[self.idx]; + assert!( + src.len() <= buf.len(), + "scripted chunk ({}) exceeds caller buffer ({})", + src.len(), + buf.len() + ); + buf[..src.len()].copy_from_slice(src); + self.idx += 1; + Ok(src.len()) + } + } + + let valid_doc = make_eod_doc("PIPE.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let prefix_len = valid_doc.len() as u64; + let bad_len = 0_i32; + + // Case 1: single short read supplies both the valid doc and the corrupt 4-byte header. + let mut single_packet = valid_doc.clone(); + single_packet.extend_from_slice(&bad_len.to_le_bytes()); + + let mut reader = RawBsonChunkReader::with_options( + ScriptedReader { + chunks: vec![single_packet], + idx: 0, + read_calls: 0, + }, + BsonStreamOptions { + chunk_capacity_bytes: 4096, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = reader + .next_chunk() + .expect("valid prefix must be yielded immediately") + .expect("expected valid prefix chunk"); + assert_eq!(chunk.start_offset, 0); + assert_eq!(chunk.bytes, valid_doc.as_slice()); + + let err = reader.next_chunk().unwrap_err(); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { + offset, + declared_len, + max_doc_bytes: 4096, + } if offset == prefix_len && declared_len == bad_len + )); + assert_eq!(reader.into_inner().read_calls, 1); + + // Case 2: corrupt header split across two short reads; stops immediately once 4 bytes arrive. + let mut part1 = valid_doc.clone(); + let bad_bytes = (-42_i32).to_le_bytes(); + part1.extend_from_slice(&bad_bytes[..2]); + let part2 = bad_bytes[2..].to_vec(); + + let mut split_reader = RawBsonChunkReader::with_options( + ScriptedReader { + chunks: vec![part1, part2], + idx: 0, + read_calls: 0, + }, + BsonStreamOptions { + chunk_capacity_bytes: 4096, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = split_reader.next_chunk().unwrap().unwrap(); + assert_eq!(chunk.bytes, valid_doc.as_slice()); + let err = split_reader.next_chunk().unwrap_err(); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { + offset, + declared_len: -42, + max_doc_bytes: 4096, + } if offset == prefix_len + )); + assert_eq!(split_reader.into_inner().read_calls, 2); +} + +#[test] +fn eof_is_sticky_and_does_not_reread_source() { + struct CountingEofReader { + data: Vec, + pos: usize, + eof_returned: bool, + reads_after_eof: usize, + } + + impl Read for CountingEofReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.eof_returned { + self.reads_after_eof += 1; + return Ok(0); + } + let remaining = self.data.len() - self.pos; + if remaining == 0 { + self.eof_returned = true; + return Ok(0); + } + let take = remaining.min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } + } + + let doc = make_eod_doc("EOF.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let mut reader = RawBsonChunkReader::with_options( + CountingEofReader { + data: doc.clone(), + pos: 0, + eof_returned: false, + reads_after_eof: 0, + }, + BsonStreamOptions { + chunk_capacity_bytes: 512, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = reader.next_chunk().unwrap().unwrap(); + assert_eq!(chunk.bytes, doc.as_slice()); + assert!(reader.next_chunk().unwrap().is_none()); + for _ in 0..5 { + assert!(reader.next_chunk().unwrap().is_none()); + } + assert_eq!(reader.into_inner().reads_after_eof, 0); +} + +#[test] +fn retries_many_consecutive_interrupted_reads() { + struct BurstInterruptReader<'a> { + data: &'a [u8], + pos: usize, + remaining_interrupts: usize, + } + + impl Read for BurstInterruptReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.remaining_interrupts > 0 { + self.remaining_interrupts -= 1; + return Err(io::Error::new( + io::ErrorKind::Interrupted, + "burst EINTR", + )); + } + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let take = remaining.min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } + } + + let doc = make_eod_doc("INTR.US", "2024-06-10", 20.0, 21.0, 19.0, 20.5, 500); + let mut reader = RawBsonChunkReader::with_options( + BurstInterruptReader { + data: &doc, + pos: 0, + remaining_interrupts: 100, + }, + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + + let chunk = reader.next_chunk().unwrap().unwrap(); + assert_eq!(chunk.bytes, doc.as_slice()); + assert!(reader.next_chunk().unwrap().is_none()); + assert_eq!(reader.docs_framed(), 1); + assert_eq!(reader.bytes_read(), doc.len() as u64); +} + +#[test] +fn exact_single_doc_buffer_yields_one_doc_per_chunk_without_growing() { + let doc = make_eod_doc("EXACT.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let doc_len = doc.len(); + let count = 12usize; + let mut input = Vec::with_capacity(doc_len * count); + for _ in 0..count { + input.extend_from_slice(&doc); + } + + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&input, 19), + BsonStreamOptions { + chunk_capacity_bytes: doc_len, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + assert_eq!(reader.buffer_capacity(), doc_len); + + let mut chunks = 0usize; + while let Some(chunk) = reader.next_chunk().unwrap() { + assert_eq!(chunk.bytes, doc.as_slice()); + assert_eq!(chunk.start_offset, (chunks * doc_len) as u64); + assert_eq!(reader.buffer_capacity(), doc_len); + chunks += 1; + } + assert_eq!(chunks, count); + assert_eq!(reader.docs_framed(), count as u64); +} + +#[test] +fn declared_length_one_over_max_rejects_without_growing_or_extra_read() { + struct HeaderOnlyReader { + header: [u8; 4], + sent: bool, + reads: usize, + } + + impl Read for HeaderOnlyReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reads += 1; + if self.sent { + panic!("unexpected read #{} after sending oversized header", self.reads); + } + self.sent = true; + let take = 4.min(buf.len()); + buf[..take].copy_from_slice(&self.header[..take]); + Ok(take) + } + } + + let max_doc = 512usize; + let over_len = (max_doc + 1) as i32; + let mut reader = RawBsonChunkReader::with_options( + HeaderOnlyReader { + header: over_len.to_le_bytes(), + sent: false, + reads: 0, + }, + BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: max_doc, + }, + ) + .unwrap(); + assert_eq!(reader.buffer_capacity(), 64); + + let err = reader.next_chunk().unwrap_err(); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { + offset: 0, + declared_len, + max_doc_bytes, + } if declared_len == over_len && max_doc_bytes == max_doc + )); + assert_eq!(reader.buffer_capacity(), 64); + assert_eq!(reader.into_inner().reads, 1); +} + +#[test] +fn oversized_truncated_document_reports_declared_len_within_memory_limit() { + let max_doc = 2048usize; + let declared_len = 1500i32; + let mut truncated = Vec::with_capacity(900); + truncated.extend_from_slice(&declared_len.to_le_bytes()); + truncated.resize(900, 0x11); + + let mut reader = RawBsonChunkReader::with_options( + FixedStepReader::new(&truncated, 127), + BsonStreamOptions { + chunk_capacity_bytes: 256, + max_doc_bytes: max_doc, + }, + ) + .unwrap(); + + let err = reader.next_chunk().unwrap_err(); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { + offset: 0, + remaining: 900, + declared_len: Some(1500), + } + )); + assert!( + reader.buffer_capacity() <= max_doc, + "capacity {} exceeded max_doc_bytes {max_doc}", + reader.buffer_capacity() + ); +} + +#[test] +fn stream_helpers_deliver_prefix_rows_before_terminal_error() { + let eod_doc = make_eod_doc("PRE1.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 100); + let split_doc = { + let mut d = RawDocumentBuf::new(); + d.append(cstr!("qmSearchCode"), "SPL1"); + d.append(cstr!("date"), "2024-06-10"); + d.append(cstr!("splitratio"), 2.0_f64); + d.into_bytes() + }; + let div_doc = { + let mut d = RawDocumentBuf::new(); + d.append(cstr!("qmSearchCode"), "DIV1"); + d.append(cstr!("date"), "2024-06-10"); + d.append(cstr!("amount"), 0.5_f64); + d.append(cstr!("currency"), "USD"); + d.into_bytes() + }; + + let opts = BsonStreamOptions { + chunk_capacity_bytes: 512, + max_doc_bytes: 4096, + }; + + // 1) Truncated tail after valid prefix. + { + let mut bytes = eod_doc.clone(); + bytes.extend_from_slice(&eod_doc[..10]); + let mut seen = 0usize; + let err = decode_eod_price_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { offset, remaining: 10, .. } + if offset == eod_doc.len() as u64 + )); + } + { + let mut bytes = split_doc.clone(); + bytes.extend_from_slice(&split_doc[..6]); + let mut seen = 0usize; + let err = decode_qm_split_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { offset, remaining: 6, .. } + if offset == split_doc.len() as u64 + )); + } + { + let mut bytes = div_doc.clone(); + bytes.extend_from_slice(&[1, 2]); + let mut seen = 0usize; + let err = decode_qm_dividend_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::TruncatedDocument { offset, remaining: 2, declared_len: None } + if offset == div_doc.len() as u64 + )); + } + + // 2) I/O error after valid prefix. + { + let mut seen = 0usize; + let err = decode_eod_price_stream( + FailingReader::new(eod_doc.clone(), io::ErrorKind::ConnectionReset, "reset"), + opts, + |_| seen += 1, + |_, _| {}, + ) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::Io { offset, ref source } + if offset == eod_doc.len() as u64 && source.kind() == io::ErrorKind::ConnectionReset + )); + } + { + let mut seen = 0usize; + let err = decode_qm_split_stream( + FailingReader::new(split_doc.clone(), io::ErrorKind::ConnectionReset, "reset"), + opts, + |_| seen += 1, + |_, _| {}, + ) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::Io { offset, .. } if offset == split_doc.len() as u64 + )); + } + { + let mut seen = 0usize; + let err = decode_qm_dividend_stream( + FailingReader::new(div_doc.clone(), io::ErrorKind::ConnectionReset, "reset"), + opts, + |_| seen += 1, + |_, _| {}, + ) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::Io { offset, .. } if offset == div_doc.len() as u64 + )); + } + + // 3) Corrupt length header after valid prefix. + { + let mut bytes = eod_doc.clone(); + bytes.extend_from_slice(&3_i32.to_le_bytes()); + let mut seen = 0usize; + let err = decode_eod_price_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { offset, declared_len: 3, .. } + if offset == eod_doc.len() as u64 + )); + } + { + let mut bytes = split_doc.clone(); + bytes.extend_from_slice(&(-7_i32).to_le_bytes()); + let mut seen = 0usize; + let err = decode_qm_split_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { offset, declared_len: -7, .. } + if offset == split_doc.len() as u64 + )); + } + { + let mut bytes = div_doc.clone(); + bytes.extend_from_slice(&(5000_i32).to_le_bytes()); + let mut seen = 0usize; + let err = decode_qm_dividend_stream(Cursor::new(bytes), opts, |_| seen += 1, |_, _| {}) + .unwrap_err(); + assert_eq!(seen, 1); + assert!(matches!( + err, + BsonStreamError::CorruptDocumentLength { offset, declared_len: 5000, .. } + if offset == div_doc.len() as u64 + )); + } +} + +#[test] +fn stream_helpers_reject_invalid_options_before_reading() { + struct PanicOnRead; + impl Read for PanicOnRead { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + panic!("reader must not be read when options are invalid"); + } + } + + let bad_cap = BsonStreamOptions { + chunk_capacity_bytes: 0, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; + let bad_max = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4, + }; + + assert!(matches!( + decode_eod_price_stream(PanicOnRead, bad_cap, |_| {}, |_, _| {}), + Err(BsonStreamError::InvalidChunkCapacity) + )); + assert!(matches!( + decode_eod_price_stream(PanicOnRead, bad_max, |_| {}, |_, _| {}), + Err(BsonStreamError::InvalidMaxDocBytes) + )); + assert!(matches!( + decode_qm_split_stream(PanicOnRead, bad_cap, |_| {}, |_, _| {}), + Err(BsonStreamError::InvalidChunkCapacity) + )); + assert!(matches!( + decode_qm_split_stream(PanicOnRead, bad_max, |_| {}, |_, _| {}), + Err(BsonStreamError::InvalidMaxDocBytes) + )); + assert!(matches!( + decode_qm_dividend_stream(PanicOnRead, bad_cap, |_| {}, |_, _| {}), + Err(BsonStreamError::InvalidChunkCapacity) + )); + assert!(matches!( + decode_qm_dividend_stream(PanicOnRead, bad_max, |_| {}, |_, _| {}), + Err(BsonStreamError::InvalidMaxDocBytes) + )); +} + +#[test] +fn randomized_buffer_and_read_size_sweep_matches_buffer_decoder() { + let fixture = build_mixed_eod_fixture(); + + let mut expected_bars = Vec::new(); + let mut expected_errs = Vec::new(); + let expected_stats = decode_eod_price_buffer( + &fixture, + |bar| { + expected_bars.push(OwnedEodBar { + code: bar.eod_search_code.to_owned(), + session_date: bar.session_date, + open: bar.open.to_bits(), + high: bar.high.to_bits(), + low: bar.low.to_bits(), + close: bar.close.to_bits(), + adj_volume: bar.adj_volume.to_bits(), + }); + }, + |offset, err| expected_errs.push((offset as u64, err)), + ); + + let mut rng = SplitMix64::new(0x5EED_6464_B501_2026); + for case in 0..64 { + let cap = (rng.next_u64() as usize % (fixture.len() + 256)) + 1; + let step = (rng.next_u64() as usize % 512) + 1; + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; + + let mut got_bars = Vec::new(); + let mut got_errs = Vec::new(); + let got_stats = decode_eod_price_stream( + FixedStepReader::new(&fixture, step), + opts, + |bar| { + got_bars.push(OwnedEodBar { + code: bar.eod_search_code.to_owned(), + session_date: bar.session_date, + open: bar.open.to_bits(), + high: bar.high.to_bits(), + low: bar.low.to_bits(), + close: bar.close.to_bits(), + adj_volume: bar.adj_volume.to_bits(), + }); + }, + |offset, err| got_errs.push((offset, err)), + ) + .unwrap_or_else(|e| panic!("case {case} (cap={cap}, step={step}) failed: {e}")); + + assert_eq!(got_stats, expected_stats, "case {case} stats mismatch"); + assert_eq!(got_bars, expected_bars, "case {case} bars mismatch"); + assert_eq!(got_errs, expected_errs, "case {case} errs mismatch"); + } +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 08d4ad55..f2a442c1 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -5,10 +5,11 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, - DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, - DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, - DEFAULT_CURATE_EVENTS_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, - DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS, + DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS, + DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, + DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, @@ -35,10 +36,13 @@ pub enum CliAction { BenchParquetAdj(usize), BenchParquetCorporateActions(usize), BenchBsonEodPrices(usize), + BenchBsonQmActions(usize), + BenchBsonStream(usize), BenchCurateBars(usize), BenchCurateShorts(usize), BenchCurateEvents(usize), BenchCurateFx(usize), + BenchCurateAdj(usize), BenchCurateCorporateActions(usize), } @@ -65,10 +69,13 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\ {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\ {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ + {name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\ + {name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\ {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ {name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\ {name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\ + {name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\ {name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})" ) } @@ -94,10 +101,13 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-adj [rows]\n\ {name} bench-parquet-corporate-actions [rows]\n\ {name} bench-bson-eod-prices [rows]\n\ + {name} bench-bson-qm-actions [rows]\n\ + {name} bench-bson-stream [rows]\n\ {name} bench-curate-bars [rows]\n\ {name} bench-curate-shorts [rows]\n\ {name} bench-curate-events [rows]\n\ {name} bench-curate-fx [rows]\n\ + {name} bench-curate-adj [events]\n\ {name} bench-curate-corporate-actions [events]" ) } @@ -263,6 +273,28 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-bson-eod-prices", _, ..] => { Err("too many arguments for bench-bson-eod-prices".to_string()) } + ["bench-bson-qm-actions"] => Ok(CliAction::BenchBsonQmActions( + DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS, + )), + ["bench-bson-qm-actions", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchBsonQmActions(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-bson-qm-actions", _, ..] => { + Err("too many arguments for bench-bson-qm-actions".to_string()) + } + ["bench-bson-stream"] => Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS)), + ["bench-bson-stream", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchBsonStream(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-bson-stream", _, ..] => { + Err("too many arguments for bench-bson-stream".to_string()) + } ["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)), ["bench-curate-bars", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)), @@ -305,6 +337,14 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()), + ["bench-curate-adj"] => Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)), + ["bench-curate-adj", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdj(n)), + _ => Err(format!( + "invalid event count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-adj", _, ..] => Err("too many arguments for bench-curate-adj".to_string()), ["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions( DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, )), @@ -604,6 +644,40 @@ mod tests { assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_bson_qm_actions_args() { + assert_eq!( + parse_args(&to_args(&["bench-bson-qm-actions"])), + Ok(CliAction::BenchBsonQmActions( + DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-bson-qm-actions", "250000"])), + Ok(CliAction::BenchBsonQmActions(250_000)) + ); + assert!(parse_args(&to_args(&["bench-bson-qm-actions", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-qm-actions", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-qm-actions", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-qm-actions", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_bson_stream_args() { + assert_eq!( + parse_args(&to_args(&["bench-bson-stream"])), + Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-bson-stream", "250000"])), + Ok(CliAction::BenchBsonStream(250_000)) + ); + assert!(parse_args(&to_args(&["bench-bson-stream", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-stream", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-stream", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -622,10 +696,13 @@ mod tests { assert!(full.contains("bench-parquet-adj")); assert!(full.contains("bench-parquet-corporate-actions")); assert!(full.contains("bench-bson-eod-prices")); + assert!(full.contains("bench-bson-qm-actions")); + assert!(full.contains("bench-bson-stream")); assert!(full.contains("bench-curate-bars")); assert!(full.contains("bench-curate-shorts")); assert!(full.contains("bench-curate-events")); assert!(full.contains("bench-curate-fx")); + assert!(full.contains("bench-curate-adj")); assert!(full.contains("bench-curate-corporate-actions")); let short = format_usage_stderr("curate-etl"); @@ -644,10 +721,13 @@ mod tests { assert!(short.contains("bench-parquet-adj")); assert!(short.contains("bench-parquet-corporate-actions")); assert!(short.contains("bench-bson-eod-prices")); + assert!(short.contains("bench-bson-qm-actions")); + assert!(short.contains("bench-bson-stream")); assert!(short.contains("bench-curate-bars")); assert!(short.contains("bench-curate-shorts")); assert!(short.contains("bench-curate-events")); assert!(short.contains("bench-curate-fx")); + assert!(short.contains("bench-curate-adj")); assert!(short.contains("bench-curate-corporate-actions")); } @@ -719,6 +799,22 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_curate_adj_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-adj"])), + Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-adj", "100000"])), + Ok(CliAction::BenchCurateAdj(100_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-adj", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-adj", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-adj", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-adj", "10", "20"])).is_err()); + } + #[test] fn parses_and_validates_bench_curate_corporate_actions_args() { assert_eq!( diff --git a/tools/curate-etl/src/curate_adj.rs b/tools/curate-etl/src/curate_adj.rs new file mode 100644 index 00000000..9b6ef7c9 --- /dev/null +++ b/tools/curate-etl/src/curate_adj.rs @@ -0,0 +1,1944 @@ +//! Pure, in-memory `adj_factors` curation stage joining +//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::adj::build_adj_factors`], +//! [`crate::session_close::et_session_close_utc_micros`], and +//! [`crate::parquet_adj::write_adj_factors_dataset`] into contract [`AdjFactorsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - **Map before build:** every source-keyed `qmSplits` and `qmDividends` event is resolved via +//! `(mapping_source, source_key, ex_date) -> listing_id: i32` *before* calling +//! [`build_adj_factors`] on `i32` listing keys. Cumulative factors (`cum_split_factor`, +//! `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker +//! renames, while ticker reuse across distinct `listing_id`s produces independent chains. +//! - **Unmapped events:** splits and dividends with no covering `provider_mapping` range on +//! `ex_date` are dropped and counted separately in `splits_dropped_unmapped` and +//! `dividends_dropped_unmapped`. +//! - **Cross-key collision policy (fail closed on conflict):** after mapping, events on the same +//! `(listing_id, ex_date)` are grouped deterministically: +//! - Single-source-key groups pass through unchanged to [`build_adj_factors`] (preserving +//! same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and +//! zero-cash dividend drops). +//! - Multi-source-key groups whose payloads are bitwise identical collapse to one event and are +//! counted in `splits_collision_collapsed` / `dividends_collision_collapsed` and +//! `listing_collision_collapsed`. +//! - Multi-source-key groups with conflicting split ratios or conflicting dividend fields return +//! [`CurateAdjError::ConflictingCrossKeySplit`] / +//! [`CurateAdjError::ConflictingCrossKeyDividend`] rather than silently dropping or doubling an +//! event that would corrupt every earlier cumulative factor. +//! - **Conservative `known_at` & point-in-time snapshot contract:** +//! - Every row's `known_at_micros` is stamped with +//! `et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / +//! `America/Toronto` on `ex_date`: `21:00 UTC` in EST, `20:00 UTC` in EDT). +//! Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns +//! [`CurateAdjError::ExDateOutOfRange`] naming `(listing_id, ex_date)` without panicking. +//! - Because [`build_adj_factors`] computes right-to-left suffix products +//! (`cum_split_factor`, `cum_total_factor`), later splits and dividends are compounded into +//! earlier rows. Consequently, [`curate_adj_factors`] produces an explicitly tagged +//! [`AdjSnapshotKind::RetrospectiveSnapshot`] (full-history snapshot): slicing it with a bare +//! `known_at <= as_of` filter would still admit earlier rows whose cumulative factors embed +//! future or held-out vault actions. +//! - For point-in-time and vault-fenced reads, callers MUST use [`curate_adj_factors_as_of`] / +//! [`curate_and_write_adj_factors_as_of`] with an [`AdjPointInTimeFence`] (`as_of_micros` +//! inclusive `<=`, `vault_cutoff_micros` exclusive `<`), which fences source events *before* +//! compaction and compounding and tags the output as [`AdjSnapshotKind::PointInTimeFenced`]. + +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::HashMap; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use parquet::basic::{Compression, ZstdLevel}; +use parquet::column::reader::ColumnReader; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::metadata::KeyValue; +use parquet::file::properties::WriterProperties; +use parquet::file::reader::{FileReader, SerializedFileReader}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::ColumnPath; + +use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; +use crate::parquet_adj::{ + adj_factors_parquet_schema, AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats, + ParquetAdjError, RollbackFailure, +}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_f64_col, write_i32_col, write_i64_col, write_optional_interned_str_col, DatasetFileLock, + StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, + STRING_WRITE_BATCH_ROWS, +}; +use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; +use crate::session_close::{et_session_close_utc_micros, SessionCloseError}; +use crate::split::SplitEvent; + +/// Current format version embedded in `adj_factors/part.parquet` footer `key_value_metadata`. +pub const ADJ_SNAPSHOT_FORMAT_VERSION: u32 = 1; + +const KV_PREFIX: &str = "stock_bot.adj_factors."; +const KV_FORMAT_VERSION: &str = "stock_bot.adj_factors.format_version"; +const KV_SNAPSHOT_KIND: &str = "stock_bot.adj_factors.snapshot_kind"; +const KV_AS_OF_MICROS: &str = "stock_bot.adj_factors.as_of_micros"; +const KV_VAULT_CUTOFF_MICROS: &str = "stock_bot.adj_factors.vault_cutoff_micros"; +const KV_ROWS_WRITTEN: &str = "stock_bot.adj_factors.rows_written"; +const KV_SNAPSHOT_CHECKSUM: &str = "stock_bot.adj_factors.snapshot_checksum"; + +/// Point-in-time and Vault holdout fence applied to source events *before* +/// [`build_adj_factors`] computes right-to-left cumulative suffix factors. +/// +/// - `as_of_micros`: inclusive UTC microsecond upper bound (`event_known_at <= as_of_micros`). +/// - `vault_cutoff_micros`: exclusive UTC microsecond Vault holdout boundary +/// (`event_known_at < vault_cutoff_micros`), matching `design/DATA-CONTRACTS.md` §4. +/// +/// When both bounds are set, an event must satisfy both (`known_at <= as_of_micros` AND +/// `known_at < vault_cutoff_micros`), so the vault cutoff always wins even if `as_of_micros` is +/// at or past `vault_cutoff_micros`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AdjPointInTimeFence { + pub as_of_micros: Option, + pub vault_cutoff_micros: Option, +} + +impl AdjPointInTimeFence { + /// Unbounded retrospective full-history snapshot (no `as_of` or vault fence). + #[inline] + pub const fn retrospective() -> Self { + Self { + as_of_micros: None, + vault_cutoff_micros: None, + } + } + + /// Inclusive `known_at <= as_of_micros` fence without a separate vault cutoff. + #[inline] + pub const fn as_of(as_of_micros: i64) -> Self { + Self { + as_of_micros: Some(as_of_micros), + vault_cutoff_micros: None, + } + } + + /// Exclusive `known_at < vault_cutoff_micros` vault holdout fence. + #[inline] + pub const fn vault_fenced(vault_cutoff_micros: i64) -> Self { + Self { + as_of_micros: None, + vault_cutoff_micros: Some(vault_cutoff_micros), + } + } + + /// Combined `known_at <= as_of_micros` and `known_at < vault_cutoff_micros` fence. + #[inline] + pub const fn as_of_with_vault_cutoff(as_of_micros: i64, vault_cutoff_micros: i64) -> Self { + Self { + as_of_micros: Some(as_of_micros), + vault_cutoff_micros: Some(vault_cutoff_micros), + } + } + + /// Returns `true` when neither an `as_of` nor a `vault_cutoff` bound is set. + #[inline] + pub const fn is_retrospective(&self) -> bool { + self.as_of_micros.is_none() && self.vault_cutoff_micros.is_none() + } + + /// Returns `true` iff an event with `known_at_micros` is admitted by this fence. + #[inline] + pub const fn admits(&self, known_at_micros: i64) -> bool { + if let Some(as_of) = self.as_of_micros { + if known_at_micros > as_of { + return false; + } + } + if let Some(vault_cutoff) = self.vault_cutoff_micros { + if known_at_micros >= vault_cutoff { + return false; + } + } + true + } +} + +/// Identifies whether a curated `adj_factors` output is an unfenced retrospective full-history +/// snapshot or a point-in-time / vault-fenced snapshot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdjSnapshotKind { + /// Built from the full input history with no `as_of` or vault fence. Earlier rows embed + /// later actions in `cum_split_factor` / `cum_total_factor`; do not slice with a bare + /// `known_at <= as_of` filter for point-in-time research reads. + RetrospectiveSnapshot, + /// Built after fencing source events by the attached [`AdjPointInTimeFence`] before + /// compaction and compounding, so no action beyond the fence is embedded in any row. + PointInTimeFenced(AdjPointInTimeFence), +} + +/// Accounting summary produced alongside [`CurateAdjFactorsOutput::rows`]. +/// +/// Conservation invariants: +/// - `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in` +/// - `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in` +/// - `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed` +/// - `rows_out == builder.rows_out` +/// - `listings_out == builder.keys_out` +/// - For [`AdjSnapshotKind::RetrospectiveSnapshot`], `splits_dropped_fenced == 0` and +/// `dividends_dropped_fenced == 0`. +/// - `builder` independently satisfies all [`AdjBuildStats`] invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateAdjFactorsStats { + pub builder: AdjBuildStats, + pub splits_in: usize, + pub dividends_in: usize, + pub splits_dropped_unmapped: usize, + pub dividends_dropped_unmapped: usize, + pub splits_dropped_fenced: usize, + pub dividends_dropped_fenced: usize, + pub splits_collision_collapsed: usize, + pub dividends_collision_collapsed: usize, + pub listing_collision_collapsed: usize, + pub rows_out: usize, + pub listings_out: usize, +} + +/// Output of [`curate_adj_factors`] / [`curate_adj_factors_as_of`]: contract Parquet rows sorted +/// and unique by `(listing_id, ex_date)`, explicit snapshot classification, and full stage + +/// builder stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateAdjFactorsOutput { + pub rows: Vec, + pub stats: CurateAdjFactorsStats, + pub snapshot_kind: AdjSnapshotKind, +} + +/// Typed errors returned by [`curate_adj_factors`]. +#[derive(Debug, Clone, PartialEq)] +pub enum CurateAdjError { + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, + /// Validation or compounding error propagated from [`build_adj_factors`]. + Adj(AdjError), + /// Two distinct source keys mapped to the same `(listing_id, ex_date)` with conflicting split + /// ratios. + ConflictingCrossKeySplit { + listing_id: i32, + ex_date: i32, + first_key: String, + first_ratio: f64, + second_key: String, + second_ratio: f64, + }, + /// Two distinct source keys mapped to the same `(listing_id, ex_date)` with differing dividend + /// payloads (`cash`, `currency`, `prev_close`, or `prev_close_currency`). + ConflictingCrossKeyDividend { + listing_id: i32, + ex_date: i32, + first_key: String, + second_key: String, + }, + /// A curated row's `ex_date` fell outside [`et_session_close_utc_micros`]'s supported + /// `1976-01-01..=2030-12-31` window. + ExDateOutOfRange { + listing_id: i32, + ex_date: i32, + source: SessionCloseError, + }, +} + +impl fmt::Display for CurateAdjError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + Self::Adj(err) => write!(f, "{err}"), + Self::ConflictingCrossKeySplit { + listing_id, + ex_date, + first_key, + first_ratio, + second_key, + second_ratio, + } => write!( + f, + "conflicting cross-key splits for listing_id {listing_id} on epoch day {ex_date}: key '{first_key}' ratio {first_ratio} vs key '{second_key}' ratio {second_ratio}" + ), + Self::ConflictingCrossKeyDividend { + listing_id, + ex_date, + first_key, + second_key, + } => write!( + f, + "conflicting cross-key dividends for listing_id {listing_id} on epoch day {ex_date}: key '{first_key}' vs key '{second_key}'" + ), + Self::ExDateOutOfRange { + listing_id, + ex_date, + source, + } => write!( + f, + "adj_factors ex_date {ex_date} for listing_id {listing_id} out of range: {source}" + ), + } + } +} + +impl Error for CurateAdjError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Adj(err) => Some(err), + Self::ExDateOutOfRange { source, .. } => Some(source), + Self::EmptyMappingSource + | Self::ConflictingCrossKeySplit { .. } + | Self::ConflictingCrossKeyDividend { .. } => None, + } + } +} + +impl From for CurateAdjError { + fn from(err: AdjError) -> Self { + Self::Adj(err) + } +} + +/// Combined stats returned by [`curate_and_write_adj_factors`] and +/// [`curate_and_write_adj_factors_as_of`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CurateAdjFactorsWriteReport { + pub curate_stats: CurateAdjFactorsStats, + pub write_stats: AdjFactorsWriteStats, + pub snapshot_kind: AdjSnapshotKind, +} + +/// Typed error returned by [`curate_and_write_adj_factors`] and +/// [`curate_and_write_adj_factors_as_of`]. +#[derive(Debug)] +pub enum CurateAdjWriteError { + Curate(CurateAdjError), + Parquet(ParquetAdjError), +} + +impl fmt::Display for CurateAdjWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "adj_factors curation failed: {err}"), + Self::Parquet(err) => write!(f, "adj_factors Parquet write failed: {err}"), + } + } +} + +impl Error for CurateAdjWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateAdjWriteError { + fn from(err: CurateAdjError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateAdjWriteError { + fn from(err: ParquetAdjError) -> Self { + Self::Parquet(err) + } +} + +struct MappedSplit { + listing_id: i32, + ex_date: i32, + source_key: K, + ratio: f64, +} + +struct MappedDividend { + listing_id: i32, + source_key: K, + event: DividendEvent, +} + +#[inline] +fn resolve_with_cache<'a>( + cache: &mut HashMap>, + mapping: &'a ProviderMappingTable, + mapping_source: &str, + key_str: &str, + ex_date: i32, +) -> Option { + if let Some(cursor) = cache.get_mut(key_str) { + return cursor.resolve(ex_date); + } + let mut cursor = mapping.cursor_for(mapping_source, key_str); + let resolved = cursor.resolve(ex_date); + cache.insert(key_str.to_owned(), cursor); + resolved +} + +#[inline] +fn cmp_opt_f64(a: Option, b: Option) -> Ordering { + match (a, b) { + (None, None) => Ordering::Equal, + (None, Some(_)) => Ordering::Less, + (Some(_), None) => Ordering::Greater, + (Some(x), Some(y)) => x.total_cmp(&y), + } +} + +#[inline] +fn cmp_dividend_event(a: &DividendEvent, b: &DividendEvent) -> Ordering { + a.ex_date + .cmp(&b.ex_date) + .then_with(|| a.cash.total_cmp(&b.cash)) + .then_with(|| a.currency.cmp(&b.currency)) + .then_with(|| cmp_opt_f64(a.prev_close, b.prev_close)) + .then_with(|| a.prev_close_currency.cmp(&b.prev_close_currency)) +} + +#[inline] +fn dividend_event_bit_eq(a: &DividendEvent, b: &DividendEvent) -> bool { + a.ex_date == b.ex_date + && a.cash.to_bits() == b.cash.to_bits() + && a.currency == b.currency + && a.prev_close.map(f64::to_bits) == b.prev_close.map(f64::to_bits) + && a.prev_close_currency == b.prev_close_currency +} + +fn compact_mapped_splits>( + mut mapped: Vec>, +) -> Result<(Vec<(i32, SplitEvent)>, usize), CurateAdjError> { + mapped.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ex_date.cmp(&b.ex_date)) + .then_with(|| a.source_key.as_ref().cmp(b.source_key.as_ref())) + .then_with(|| a.ratio.total_cmp(&b.ratio)) + }); + + let mut out: Vec<(i32, SplitEvent)> = Vec::with_capacity(mapped.len()); + let mut collapsed_total = 0usize; + let mut iter = mapped.into_iter().peekable(); + let mut group: Vec> = Vec::with_capacity(4); + + while let Some(first) = iter.next() { + let listing_id = first.listing_id; + let ex_date = first.ex_date; + group.clear(); + group.push(first); + while let Some(next) = iter.peek() { + if next.listing_id == listing_id && next.ex_date == ex_date { + group.push(iter.next().expect("peeked split")); + } else { + break; + } + } + + let group_len = group.len(); + if group_len == 1 { + let item = group.pop().expect("single split"); + out.push(( + listing_id, + SplitEvent { + ex_date, + ratio: item.ratio, + }, + )); + continue; + } + + let first_key = group[0].source_key.as_ref(); + let last_key = group[group_len - 1].source_key.as_ref(); + if first_key == last_key { + // Single source key: pass every event through unchanged to preserve `build_adj_factors` + // same-day split semantics. + for item in group.drain(..) { + out.push(( + listing_id, + SplitEvent { + ex_date, + ratio: item.ratio, + }, + )); + } + continue; + } + + let first_ratio = group[0].ratio; + let first_ratio_bits = first_ratio.to_bits(); + let all_identical = group[1..] + .iter() + .all(|other| other.ratio.to_bits() == first_ratio_bits); + + if all_identical { + collapsed_total += group_len - 1; + out.push(( + listing_id, + SplitEvent { + ex_date, + ratio: first_ratio, + }, + )); + } else { + // Find a deterministic pair with distinct source keys and differing ratios. + let (lhs, rhs) = if let Some(other) = group[1..] + .iter() + .find(|e| e.source_key.as_ref() != first_key && e.ratio.to_bits() != first_ratio_bits) + { + (&group[0], other) + } else { + let bad = group[1..] + .iter() + .find(|e| e.ratio.to_bits() != first_ratio_bits) + .expect("non-identical split exists"); + let other_key = group[1..] + .iter() + .find(|e| e.source_key.as_ref() != first_key) + .expect("distinct source key exists"); + (bad, other_key) + }; + return Err(CurateAdjError::ConflictingCrossKeySplit { + listing_id, + ex_date, + first_key: lhs.source_key.as_ref().to_owned(), + first_ratio: lhs.ratio, + second_key: rhs.source_key.as_ref().to_owned(), + second_ratio: rhs.ratio, + }); + } + } + + Ok((out, collapsed_total)) +} + +fn compact_mapped_dividends>( + mut mapped: Vec>, +) -> Result<(Vec<(i32, DividendEvent)>, usize), CurateAdjError> { + mapped.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.event.ex_date.cmp(&b.event.ex_date)) + .then_with(|| a.source_key.as_ref().cmp(b.source_key.as_ref())) + .then_with(|| cmp_dividend_event(&a.event, &b.event)) + }); + + let mut out: Vec<(i32, DividendEvent)> = Vec::with_capacity(mapped.len()); + let mut collapsed_total = 0usize; + let mut iter = mapped.into_iter().peekable(); + let mut group: Vec> = Vec::with_capacity(4); + + while let Some(first) = iter.next() { + let listing_id = first.listing_id; + let ex_date = first.event.ex_date; + group.clear(); + group.push(first); + while let Some(next) = iter.peek() { + if next.listing_id == listing_id && next.event.ex_date == ex_date { + group.push(iter.next().expect("peeked dividend")); + } else { + break; + } + } + + let group_len = group.len(); + if group_len == 1 { + let item = group.pop().expect("single dividend"); + out.push((listing_id, item.event)); + continue; + } + + let first_key = group[0].source_key.as_ref(); + let last_key = group[group_len - 1].source_key.as_ref(); + if first_key == last_key { + // Single source key: pass every event through unchanged to preserve `build_adj_factors` + // same-day multi-dividend semantics (e.g. regular + special dividend). + for item in group.drain(..) { + out.push((listing_id, item.event)); + } + continue; + } + + let all_identical = group[1..] + .iter() + .all(|other| dividend_event_bit_eq(&group[0].event, &other.event)); + + if all_identical { + collapsed_total += group_len - 1; + let first = group.swap_remove(0); + out.push((listing_id, first.event)); + } else { + let other_key = group[1..] + .iter() + .find(|e| { + e.source_key.as_ref() != first_key && !dividend_event_bit_eq(&group[0].event, &e.event) + }) + .or_else(|| { + group[1..] + .iter() + .find(|e| e.source_key.as_ref() != first_key) + }) + .expect("distinct source key exists"); + return Err(CurateAdjError::ConflictingCrossKeyDividend { + listing_id, + ex_date, + first_key: first_key.to_owned(), + second_key: other_key.source_key.as_ref().to_owned(), + }); + } + } + + Ok((out, collapsed_total)) +} + +/// Pure `adj_factors` curation stage producing a **retrospective full-history snapshot** +/// ([`AdjSnapshotKind::RetrospectiveSnapshot`]). +/// +/// Resolves source-keyed `qmSplits` and `qmDividends` through `provider_mapping` to permanent +/// `listing_id: i32` keys *before* factor building, compacts cross-key collisions (collapsing +/// bitwise-identical aliases and failing closed on conflicts), computes cumulative factors via +/// [`build_adj_factors`] unchanged, and stamps conservative `16:00 ET` `known_at` timestamps via +/// [`et_session_close_utc_micros`]. +/// +/// **Point-in-time warning:** because `cum_split_factor` and `cum_total_factor` compound all later +/// actions in the input into earlier rows, filtering this retrospective snapshot by +/// `known_at <= as_of` leaks future or held-out vault actions into earlier bars. Use +/// [`curate_adj_factors_as_of`] to fence source events by `as_of` and `vault_cutoff` *before* +/// compounding. +/// +/// Output rows are sorted strictly ascending and unique by `(listing_id, ex_date)`. +pub fn curate_adj_factors( + mapping: &ProviderMappingTable, + mapping_source: &str, + splits: S, + dividends: D, +) -> Result +where + K: AsRef + Ord + Clone, + S: IntoIterator, + D: IntoIterator, +{ + curate_adj_factors_as_of( + mapping, + mapping_source, + splits, + dividends, + AdjPointInTimeFence::retrospective(), + ) +} + +/// Point-in-time and vault-fenced `adj_factors` curation stage. +/// +/// Applies `fence` (`known_at <= as_of_micros` and/or `known_at < vault_cutoff_micros`, where each +/// event's `known_at` is `et_session_close_utc_micros(ex_date)`) to mapped source events *before* +/// cross-key compaction and *before* [`build_adj_factors`] compounds cumulative suffix factors. +/// Appending any future or held-out vault action beyond `fence` therefore leaves the curated rows +/// and adjusted reads bitwise identical. +/// +/// When `fence.is_retrospective()` is `true`, this behaves identically to [`curate_adj_factors`] +/// and tags the output as [`AdjSnapshotKind::RetrospectiveSnapshot`]; otherwise it tags the output +/// as [`AdjSnapshotKind::PointInTimeFenced`]. +pub fn curate_adj_factors_as_of( + mapping: &ProviderMappingTable, + mapping_source: &str, + splits: S, + dividends: D, + fence: AdjPointInTimeFence, +) -> Result +where + K: AsRef + Ord + Clone, + S: IntoIterator, + D: IntoIterator, +{ + if mapping_source.trim().is_empty() { + return Err(CurateAdjError::EmptyMappingSource); + } + + let is_fenced = !fence.is_retrospective(); + let splits_iter = splits.into_iter(); + let divs_iter = dividends.into_iter(); + + let mut stats = CurateAdjFactorsStats::default(); + let mut cursor_cache: HashMap> = HashMap::new(); + + let mut mapped_splits: Vec> = Vec::with_capacity(splits_iter.size_hint().0); + for (key, event) in splits_iter { + stats.splits_in += 1; + let Some(listing_id) = resolve_with_cache( + &mut cursor_cache, + mapping, + mapping_source, + key.as_ref(), + event.ex_date, + ) else { + stats.splits_dropped_unmapped += 1; + continue; + }; + if is_fenced { + let known_at = et_session_close_utc_micros(event.ex_date).map_err(|source| { + CurateAdjError::ExDateOutOfRange { + listing_id, + ex_date: event.ex_date, + source, + } + })?; + if !fence.admits(known_at) { + stats.splits_dropped_fenced += 1; + continue; + } + } + mapped_splits.push(MappedSplit { + listing_id, + ex_date: event.ex_date, + source_key: key, + ratio: event.ratio, + }); + } + + let mut mapped_divs: Vec> = Vec::with_capacity(divs_iter.size_hint().0); + for (key, event) in divs_iter { + stats.dividends_in += 1; + let Some(listing_id) = resolve_with_cache( + &mut cursor_cache, + mapping, + mapping_source, + key.as_ref(), + event.ex_date, + ) else { + stats.dividends_dropped_unmapped += 1; + continue; + }; + if is_fenced { + let known_at = et_session_close_utc_micros(event.ex_date).map_err(|source| { + CurateAdjError::ExDateOutOfRange { + listing_id, + ex_date: event.ex_date, + source, + } + })?; + if !fence.admits(known_at) { + stats.dividends_dropped_fenced += 1; + continue; + } + } + mapped_divs.push(MappedDividend { + listing_id, + source_key: key, + event, + }); + } + + drop(cursor_cache); + + let (compacted_splits, splits_collapsed) = compact_mapped_splits(mapped_splits)?; + let (compacted_divs, divs_collapsed) = compact_mapped_dividends(mapped_divs)?; + stats.splits_collision_collapsed = splits_collapsed; + stats.dividends_collision_collapsed = divs_collapsed; + stats.listing_collision_collapsed = splits_collapsed + divs_collapsed; + + let built = build_adj_factors::(compacted_splits, compacted_divs)?; + + let mut rows: Vec = Vec::with_capacity(built.rows.len()); + for row in &built.rows { + let known_at_micros = et_session_close_utc_micros(row.ex_date).map_err(|source| { + CurateAdjError::ExDateOutOfRange { + listing_id: row.key, + ex_date: row.ex_date, + source, + } + })?; + rows.push(AdjFactorsParquetRow::from_adj_row(row, known_at_micros)); + } + + stats.builder = built.stats; + stats.rows_out = rows.len(); + stats.listings_out = built.stats.keys_out; + + let snapshot_kind = if is_fenced { + AdjSnapshotKind::PointInTimeFenced(fence) + } else { + AdjSnapshotKind::RetrospectiveSnapshot + }; + + Ok(CurateAdjFactorsOutput { + rows, + stats, + snapshot_kind, + }) +} + +/// Zero-allocation binary-search helper returning `(cum_split_factor, cum_total_factor)` of the +/// first curated row for `listing_id` with `ex_date > bar_date`, or `(1.0, 1.0)` if no such row +/// exists. +/// +/// Assumes `rows` is sorted ascending by `(listing_id, ex_date)` (as produced by +/// [`curate_adj_factors`] or [`curate_adj_factors_as_of`]). For point-in-time reads, pass rows +/// produced by [`curate_adj_factors_as_of`] with the desired `as_of` / `vault_cutoff` fence. +#[inline] +pub fn adj_factors_for_bar( + rows: &[AdjFactorsParquetRow], + listing_id: i32, + bar_date: i32, +) -> (f64, f64) { + let idx = rows.partition_point(|row| match row.listing_id.cmp(&listing_id) { + Ordering::Less => true, + Ordering::Equal => row.ex_date <= bar_date, + Ordering::Greater => false, + }); + match rows.get(idx) { + Some(row) if row.listing_id == listing_id => (row.cum_split_factor, row.cum_total_factor), + _ => (1.0, 1.0), + } +} + +/// Thin end-to-end wrapper running [`curate_adj_factors`] (retrospective full-history snapshot) +/// and atomically publishing `/adj_factors/part.parquet` with snapshot metadata embedded +/// in the Parquet footer `key_value_metadata`. +/// +/// Any [`CurateAdjError`] returns before touching `out_dir`, leaving any existing snapshot +/// untouched and publishing no `adj_factors/part.parquet`. +pub fn curate_and_write_adj_factors( + out_dir: P, + mapping: &ProviderMappingTable, + mapping_source: &str, + splits: S, + dividends: D, + options: AdjFactorsWriteOptions, +) -> Result +where + P: AsRef, + K: AsRef + Ord + Clone, + S: IntoIterator, + D: IntoIterator, +{ + curate_and_write_adj_factors_as_of( + out_dir, + mapping, + mapping_source, + splits, + dividends, + AdjPointInTimeFence::retrospective(), + options, + ) +} + +/// Point-in-time / vault-fenced end-to-end wrapper running [`curate_adj_factors_as_of`] and +/// atomically publishing `/adj_factors/part.parquet` in a single file commit with snapshot +/// metadata embedded in the Parquet footer `key_value_metadata`. +/// +/// - Any [`CurateAdjError`] returns before touching `out_dir`, leaving any existing snapshot +/// untouched and publishing no files. +/// - When the curated result has 0 rows (e.g. a fence excludes every event), an explicit 0-row +/// Zstd Parquet file with the contract [`adj_factors_parquet_schema`] and embedded footer +/// metadata is atomically published so any previously published `part.parquet` is superseded +/// rather than left stale on disk. +/// - The Parquet footer `key_value_metadata` binds `format_version`, `snapshot_kind`, exact +/// `as_of_micros` / `vault_cutoff_micros`, `rows_written`, and `snapshot_checksum` into the +/// single atomic file commit, allowing [`read_adj_factors_dataset_as_of`] to verify integrity, +/// per-row fence admission, and cumulative-chain consistency when reopening the artifact. +pub fn curate_and_write_adj_factors_as_of( + out_dir: P, + mapping: &ProviderMappingTable, + mapping_source: &str, + splits: S, + dividends: D, + fence: AdjPointInTimeFence, + options: AdjFactorsWriteOptions, +) -> Result +where + P: AsRef, + K: AsRef + Ord + Clone, + S: IntoIterator, + D: IntoIterator, +{ + let curated = curate_adj_factors_as_of(mapping, mapping_source, splits, dividends, fence)?; + let write_stats = write_adj_factors_snapshot_parquet( + out_dir.as_ref(), + &curated.rows, + curated.snapshot_kind, + options, + )?; + + Ok(CurateAdjFactorsWriteReport { + curate_stats: curated.stats, + write_stats, + snapshot_kind: curated.snapshot_kind, + }) +} + +/// Verified `adj_factors` snapshot reopened from `/adj_factors/part.parquet`. +#[derive(Debug, Clone, PartialEq)] +pub struct AdjFactorsSnapshot { + pub rows: Vec, + pub snapshot_kind: AdjSnapshotKind, +} + +impl AdjFactorsSnapshot { + /// Returns `(cum_split_factor, cum_total_factor)` of the first row for `listing_id` with + /// `ex_date > bar_date`, or `(1.0, 1.0)` if no such row exists. + #[inline] + pub fn factors_for_bar(&self, listing_id: i32, bar_date: i32) -> (f64, f64) { + adj_factors_for_bar(&self.rows, listing_id, bar_date) + } +} + +/// Typed error returned by [`read_adj_factors_dataset`] and [`read_adj_factors_dataset_as_of`]. +#[derive(Debug)] +pub enum CurateAdjReadError { + /// Caller passed an unfenced (`retrospective`) fence to [`read_adj_factors_dataset_as_of`]. + UnfencedReadRequested, + /// `/adj_factors/part.parquet` footer carries no `stock_bot.adj_factors.*` metadata + /// keys; refusing to open an unverified Parquet file. + MissingSnapshotMetadata { path: PathBuf }, + /// `/adj_factors/part.parquet` footer metadata has partial, duplicate, unknown, or + /// malformed `stock_bot.adj_factors.*` keys. + InvalidSnapshotMetadata { path: PathBuf, message: String }, + /// `/adj_factors/part.parquet` footer metadata carries an unsupported `format_version`. + UnsupportedSnapshotVersion { + path: PathBuf, + version: u32, + supported: u32, + }, + /// Point-in-time reader refused to open a retrospective full-history snapshot. + RetrospectiveSnapshotRejected { path: PathBuf }, + /// Point-in-time reader refused a snapshot whose persisted fence does not match the requested + /// fence. + IncompatibleFence { + path: PathBuf, + actual: AdjPointInTimeFence, + required: AdjPointInTimeFence, + }, + /// A decoded row's `known_at_micros` fell outside the snapshot's verified point-in-time / + /// vault fence. + RowOutsideFence { + path: PathBuf, + listing_id: i32, + ex_date: i32, + known_at_micros: i64, + fence: AdjPointInTimeFence, + }, + /// `/adj_factors/part.parquet` schema did not match [`adj_factors_parquet_schema`]. + SchemaMismatch { path: PathBuf }, + /// `/adj_factors/part.parquet` failed row-count, ordering, cumulative-split chain, + /// or bound snapshot checksum verification. + SnapshotIntegrityMismatch { path: PathBuf, detail: String }, + /// I/O error reading `part.parquet`. + Io { path: PathBuf, source: io::Error }, + /// Parquet decoding error reading `part.parquet`. + Parquet { path: PathBuf, source: ParquetError }, +} + +impl fmt::Display for CurateAdjReadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnfencedReadRequested => write!( + f, + "read_adj_factors_dataset_as_of requires a non-retrospective point-in-time or vault fence" + ), + Self::MissingSnapshotMetadata { path } => write!( + f, + "missing adj_factors snapshot metadata in Parquet footer at '{}' (refusing to open unverified Parquet)", + path.display() + ), + Self::InvalidSnapshotMetadata { path, message } => write!( + f, + "invalid adj_factors snapshot metadata in Parquet footer at '{}': {message}", + path.display() + ), + Self::UnsupportedSnapshotVersion { + path, + version, + supported, + } => write!( + f, + "unsupported adj_factors snapshot metadata version {version} at '{}' (supported: {supported})", + path.display() + ), + Self::RetrospectiveSnapshotRejected { path } => write!( + f, + "point-in-time reader rejected retrospective adj_factors snapshot at '{}'", + path.display() + ), + Self::IncompatibleFence { + path, + actual, + required, + } => write!( + f, + "point-in-time reader rejected adj_factors snapshot at '{}': persisted fence {:?} does not match required fence {:?}", + path.display(), + actual, + required + ), + Self::RowOutsideFence { + path, + listing_id, + ex_date, + known_at_micros, + fence, + } => write!( + f, + "adj_factors row (listing_id={listing_id}, ex_date={ex_date}, known_at_micros={known_at_micros}) in '{}' falls outside fence {:?}", + path.display(), + fence + ), + Self::SchemaMismatch { path } => write!( + f, + "adj_factors Parquet schema mismatch at '{}'", + path.display() + ), + Self::SnapshotIntegrityMismatch { path, detail } => write!( + f, + "adj_factors snapshot integrity mismatch at '{}': {detail}", + path.display() + ), + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for CurateAdjReadError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +/// Reopens a published `adj_factors` artifact from `/adj_factors/part.parquet` for +/// point-in-time research reads, requiring persisted [`AdjSnapshotKind::PointInTimeFenced`] footer +/// metadata whose exact fence matches `required_fence`. +/// +/// Fails closed if `required_fence` is retrospective, the Parquet footer lacks valid +/// `stock_bot.adj_factors.*` metadata, the published artifact is a +/// [`AdjSnapshotKind::RetrospectiveSnapshot`], the persisted fence differs from `required_fence`, +/// any row's `known_at` falls outside the fence, per-listing `cum_split_factor` suffix products +/// are inconsistent, or the bound snapshot checksum does not match. +pub fn read_adj_factors_dataset_as_of>( + out_dir: P, + required_fence: AdjPointInTimeFence, +) -> Result { + if required_fence.is_retrospective() { + return Err(CurateAdjReadError::UnfencedReadRequested); + } + let part_path = out_dir.as_ref().join("adj_factors").join("part.parquet"); + let reader = open_parquet_reader(&part_path)?; + let metadata = parse_snapshot_key_value_metadata( + &part_path, + reader.metadata().file_metadata().key_value_metadata(), + )?; + match metadata.snapshot_kind { + AdjSnapshotKind::RetrospectiveSnapshot => { + return Err(CurateAdjReadError::RetrospectiveSnapshotRejected { path: part_path }); + } + AdjSnapshotKind::PointInTimeFenced(actual) if actual != required_fence => { + return Err(CurateAdjReadError::IncompatibleFence { + path: part_path, + actual, + required: required_fence, + }); + } + AdjSnapshotKind::PointInTimeFenced(_) => {} + } + load_verified_parquet_snapshot(&part_path, &reader, &metadata) +} + +/// Reopens a published `adj_factors` artifact from `/adj_factors/part.parquet`, returning +/// its rows together with its verified [`AdjSnapshotKind`]. +/// +/// Requires valid `stock_bot.adj_factors.*` Parquet footer metadata and verifies schema, row +/// count, sort order, per-row fence admission (for fenced snapshots), per-listing +/// `cum_split_factor` suffix-product consistency, and the bound snapshot checksum. For +/// point-in-time research reads, prefer [`read_adj_factors_dataset_as_of`]. +pub fn read_adj_factors_dataset>( + out_dir: P, +) -> Result { + let part_path = out_dir.as_ref().join("adj_factors").join("part.parquet"); + let reader = open_parquet_reader(&part_path)?; + let metadata = parse_snapshot_key_value_metadata( + &part_path, + reader.metadata().file_metadata().key_value_metadata(), + )?; + load_verified_parquet_snapshot(&part_path, &reader, &metadata) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct PersistedAdjSnapshotMetadata { + format_version: u32, + snapshot_kind: AdjSnapshotKind, + rows_written: usize, + snapshot_checksum: u64, +} + +fn fnv1a_update(mut hash: u64, bytes: &[u8]) -> u64 { + for &b in bytes { + hash ^= u64::from(b); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash +} + +fn fnv1a_update_opt_i64(hash: u64, val: Option) -> u64 { + match val { + Some(v) => { + let hash = fnv1a_update(hash, &[1]); + fnv1a_update(hash, &v.to_le_bytes()) + } + None => fnv1a_update(hash, &[0]), + } +} + +fn compute_snapshot_checksum( + format_version: u32, + snapshot_kind: AdjSnapshotKind, + rows: &[AdjFactorsParquetRow], +) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + hash = fnv1a_update(hash, &format_version.to_le_bytes()); + let (kind_tag, as_of, vault_cutoff) = match snapshot_kind { + AdjSnapshotKind::RetrospectiveSnapshot => (0u8, None, None), + AdjSnapshotKind::PointInTimeFenced(fence) => { + (1u8, fence.as_of_micros, fence.vault_cutoff_micros) + } + }; + hash = fnv1a_update(hash, &[kind_tag]); + hash = fnv1a_update_opt_i64(hash, as_of); + hash = fnv1a_update_opt_i64(hash, vault_cutoff); + hash = fnv1a_update(hash, &(rows.len() as u64).to_le_bytes()); + + for row in rows { + hash = fnv1a_update(hash, &row.listing_id.to_le_bytes()); + hash = fnv1a_update(hash, &row.ex_date.to_le_bytes()); + hash = fnv1a_update(hash, &row.split_factor.to_bits().to_le_bytes()); + hash = fnv1a_update(hash, &row.div_cash.to_bits().to_le_bytes()); + match row.div_currency.as_deref() { + Some(curr) => { + hash = fnv1a_update(hash, &[1]); + hash = fnv1a_update(hash, &(curr.len() as u64).to_le_bytes()); + hash = fnv1a_update(hash, curr.as_bytes()); + } + None => { + hash = fnv1a_update(hash, &[0]); + } + } + hash = fnv1a_update(hash, &row.cum_split_factor.to_bits().to_le_bytes()); + hash = fnv1a_update(hash, &row.cum_total_factor.to_bits().to_le_bytes()); + hash = fnv1a_update(hash, &row.known_at_micros.to_le_bytes()); + } + hash +} + +fn format_opt_i64_kv(val: Option) -> String { + match val { + Some(v) => v.to_string(), + None => "none".to_string(), + } +} + +fn build_snapshot_key_value_metadata( + format_version: u32, + snapshot_kind: AdjSnapshotKind, + rows_written: usize, + snapshot_checksum: u64, +) -> Vec { + let (kind_str, as_of, vault_cutoff) = match snapshot_kind { + AdjSnapshotKind::RetrospectiveSnapshot => ("retrospective", None, None), + AdjSnapshotKind::PointInTimeFenced(fence) => ( + "point_in_time_fenced", + fence.as_of_micros, + fence.vault_cutoff_micros, + ), + }; + vec![ + KeyValue::new(KV_FORMAT_VERSION.to_string(), format_version.to_string()), + KeyValue::new(KV_SNAPSHOT_KIND.to_string(), kind_str.to_string()), + KeyValue::new(KV_AS_OF_MICROS.to_string(), format_opt_i64_kv(as_of)), + KeyValue::new( + KV_VAULT_CUTOFF_MICROS.to_string(), + format_opt_i64_kv(vault_cutoff), + ), + KeyValue::new(KV_ROWS_WRITTEN.to_string(), rows_written.to_string()), + KeyValue::new( + KV_SNAPSHOT_CHECKSUM.to_string(), + format!("0x{snapshot_checksum:016x}"), + ), + ] +} + +fn write_adj_factors_snapshot_parquet( + out_dir: &Path, + rows: &[AdjFactorsParquetRow], + snapshot_kind: AdjSnapshotKind, + options: AdjFactorsWriteOptions, +) -> Result { + write_adj_factors_snapshot_parquet_impl(out_dir, rows, snapshot_kind, options, |_, _| Ok(())) +} + +#[cfg(test)] +fn write_adj_factors_snapshot_parquet_with_hooks( + out_dir: &Path, + rows: &[AdjFactorsParquetRow], + snapshot_kind: AdjSnapshotKind, + options: AdjFactorsWriteOptions, + on_before_rename: F, +) -> Result +where + F: FnMut(&Path, Option<&Path>) -> io::Result<()>, +{ + write_adj_factors_snapshot_parquet_impl( + out_dir, + rows, + snapshot_kind, + options, + on_before_rename, + ) +} + +fn write_adj_factors_snapshot_parquet_impl( + out_dir: &Path, + rows: &[AdjFactorsParquetRow], + snapshot_kind: AdjSnapshotKind, + options: AdjFactorsWriteOptions, + mut on_before_rename: F, +) -> Result +where + F: FnMut(&Path, Option<&Path>) -> io::Result<()>, +{ + if options.row_group_rows == 0 { + return Err(ParquetAdjError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetAdjError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let adj_dir = out_dir.join("adj_factors"); + let schema = adj_factors_parquet_schema().map_err(|source| ParquetAdjError::Parquet { + path: adj_dir.clone(), + source, + })?; + let snapshot_checksum = + compute_snapshot_checksum(ADJ_SNAPSHOT_FORMAT_VERSION, snapshot_kind, rows); + let kv_metadata = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + snapshot_kind, + rows.len(), + snapshot_checksum, + ); + let props = Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("div_currency"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .set_key_value_metadata(Some(kv_metadata)) + .build(), + ); + + fs::create_dir_all(&adj_dir).map_err(|source| ParquetAdjError::Io { + path: adj_dir.clone(), + source, + })?; + + let dataset_mu = dataset_mutex(&adj_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&adj_dir, DEFAULT_LOCK_TIMEOUT)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(&adj_dir, &run_id)?; + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let final_path = adj_dir.join("part.parquet"); + + let map_pq = |source: ParquetError| ParquetAdjError::Parquet { + path: tmp_path.clone(), + source, + }; + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, tmp_file); + let mut writer = SerializedFileWriter::new(buf_writer, schema, props).map_err(map_pq)?; + + let mut row_groups_written = 0usize; + if !rows.is_empty() { + let cap = rows.len().min(options.row_group_rows); + let mut listing_id = Vec::with_capacity(cap); + let mut ex_date = Vec::with_capacity(cap); + let mut split_factor = Vec::with_capacity(cap); + let mut div_cash = Vec::with_capacity(cap); + let mut div_currency_ids = Vec::with_capacity(cap); + let mut div_currency_def_levels = Vec::with_capacity(cap); + let mut div_currency_interner = StringInterner::default(); + let mut cum_split_factor = Vec::with_capacity(cap); + let mut cum_total_factor = Vec::with_capacity(cap); + let mut known_at_micros = Vec::with_capacity(cap); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + for chunk in rows.chunks(options.row_group_rows) { + listing_id.clear(); + ex_date.clear(); + split_factor.clear(); + div_cash.clear(); + div_currency_ids.clear(); + div_currency_def_levels.clear(); + div_currency_interner.clear(); + cum_split_factor.clear(); + cum_total_factor.clear(); + known_at_micros.clear(); + + for row in chunk { + listing_id.push(row.listing_id); + ex_date.push(row.ex_date); + split_factor.push(row.split_factor); + div_cash.push(row.div_cash); + match row.div_currency.as_deref() { + Some(currency) => { + let id = div_currency_interner.intern(currency); + div_currency_ids.push(id); + div_currency_def_levels.push(1); + } + None => { + div_currency_def_levels.push(0); + } + } + cum_split_factor.push(row.cum_split_factor); + cum_total_factor.push(row.cum_total_factor); + known_at_micros.push(row.known_at_micros); + } + + let mut rg_writer = writer.next_row_group().map_err(map_pq)?; + write_i32_col(&mut rg_writer, &listing_id).map_err(map_pq)?; + write_i32_col(&mut rg_writer, &ex_date).map_err(map_pq)?; + write_f64_col(&mut rg_writer, &split_factor, None).map_err(map_pq)?; + write_f64_col(&mut rg_writer, &div_cash, None).map_err(map_pq)?; + write_optional_interned_str_col( + &mut rg_writer, + &div_currency_ids, + &div_currency_def_levels, + &div_currency_interner, + &mut scratch, + ) + .map_err(map_pq)?; + write_f64_col(&mut rg_writer, &cum_split_factor, None).map_err(map_pq)?; + write_f64_col(&mut rg_writer, &cum_total_factor, None).map_err(map_pq)?; + write_i64_col(&mut rg_writer, &known_at_micros).map_err(map_pq)?; + rg_writer.close().map_err(map_pq)?; + + row_groups_written += 1; + } + } + + let mut buf_writer = writer.into_inner().map_err(map_pq)?; + buf_writer.flush().map_err(|source| ParquetAdjError::Io { + path: tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetAdjError::Io { + path: tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetAdjError::Io { + path: tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetAdjError::Io { + path: tmp_path.clone(), + source, + })? + .len(); + drop(file); + + let backup_path = match fs::symlink_metadata(&final_path) { + Ok(meta) if !meta.is_dir() => Some(create_backup_preserving_live(&final_path, &run_id)?), + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetAdjError::Io { + path: final_path, + source, + }); + } + }; + + let commit_result = on_before_rename(&final_path, backup_path.as_deref()) + .and_then(|()| fs::rename(&tmp_path, &final_path)); + if let Err(source) = commit_result { + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetAdjError::Io { + path: final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetAdjError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + if let Err(remove_err) = fs::remove_file(&bak) { + let cause = ParquetAdjError::Io { + path: bak.clone(), + source: remove_err, + }; + return match fs::rename(&bak, &final_path) { + Ok(()) => Err(cause), + Err(restore_err) => Err(ParquetAdjError::RollbackFailed { + cause: Box::new(cause), + failures: vec![RollbackFailure { + final_path, + backup_path: Some(bak), + source: restore_err, + }], + }), + }; + } + } + + Ok(AdjFactorsWriteStats { + rows_written: rows.len(), + files_written: 1, + row_groups_written, + bytes_written: bytes, + }) +} + +fn open_parquet_reader(part_path: &Path) -> Result, CurateAdjReadError> { + let file = File::open(part_path).map_err(|source| CurateAdjReadError::Io { + path: part_path.to_path_buf(), + source, + })?; + SerializedFileReader::new(file).map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + }) +} + +fn parse_opt_i64_kv( + value: &str, + field: &str, + path: &Path, +) -> Result, CurateAdjReadError> { + if value == "none" { + return Ok(None); + } + value + .parse::() + .map(Some) + .map_err(|_| CurateAdjReadError::InvalidSnapshotMetadata { + path: path.to_path_buf(), + message: format!("invalid i64 value '{value}' for '{field}'"), + }) +} + +fn parse_snapshot_key_value_metadata( + path: &Path, + kv_meta: Option<&Vec>, +) -> Result { + let invalid = |msg: &str| CurateAdjReadError::InvalidSnapshotMetadata { + path: path.to_path_buf(), + message: msg.to_string(), + }; + + let Some(entries) = kv_meta else { + return Err(CurateAdjReadError::MissingSnapshotMetadata { + path: path.to_path_buf(), + }); + }; + + let mut found_any = false; + let mut format_version: Option = None; + let mut snapshot_kind_str: Option<&str> = None; + let mut as_of_micros: Option> = None; + let mut vault_cutoff_micros: Option> = None; + let mut rows_written: Option = None; + let mut snapshot_checksum: Option = None; + + for kv in entries { + if !kv.key.starts_with(KV_PREFIX) { + continue; + } + found_any = true; + let val = kv.value.as_deref().ok_or_else(|| { + CurateAdjReadError::InvalidSnapshotMetadata { + path: path.to_path_buf(), + message: format!("missing value for metadata key '{}'", kv.key), + } + })?; + + match kv.key.as_str() { + KV_FORMAT_VERSION => { + if format_version.is_some() { + return Err(invalid("duplicate 'stock_bot.adj_factors.format_version' key")); + } + format_version = Some( + val.parse::() + .map_err(|_| invalid("invalid 'stock_bot.adj_factors.format_version'"))?, + ); + } + KV_SNAPSHOT_KIND => { + if snapshot_kind_str.is_some() { + return Err(invalid("duplicate 'stock_bot.adj_factors.snapshot_kind' key")); + } + snapshot_kind_str = Some(val); + } + KV_AS_OF_MICROS => { + if as_of_micros.is_some() { + return Err(invalid("duplicate 'stock_bot.adj_factors.as_of_micros' key")); + } + as_of_micros = Some(parse_opt_i64_kv(val, KV_AS_OF_MICROS, path)?); + } + KV_VAULT_CUTOFF_MICROS => { + if vault_cutoff_micros.is_some() { + return Err(invalid( + "duplicate 'stock_bot.adj_factors.vault_cutoff_micros' key", + )); + } + vault_cutoff_micros = Some(parse_opt_i64_kv(val, KV_VAULT_CUTOFF_MICROS, path)?); + } + KV_ROWS_WRITTEN => { + if rows_written.is_some() { + return Err(invalid("duplicate 'stock_bot.adj_factors.rows_written' key")); + } + rows_written = Some( + val.parse::() + .map_err(|_| invalid("invalid 'stock_bot.adj_factors.rows_written'"))?, + ); + } + KV_SNAPSHOT_CHECKSUM => { + if snapshot_checksum.is_some() { + return Err(invalid( + "duplicate 'stock_bot.adj_factors.snapshot_checksum' key", + )); + } + let hex = val.strip_prefix("0x").ok_or_else(|| { + invalid("'stock_bot.adj_factors.snapshot_checksum' must start with '0x'") + })?; + if hex.len() != 16 { + return Err(invalid( + "'stock_bot.adj_factors.snapshot_checksum' must be 16 hex digits", + )); + } + snapshot_checksum = Some( + u64::from_str_radix(hex, 16) + .map_err(|_| invalid("invalid hex in 'stock_bot.adj_factors.snapshot_checksum'"))?, + ); + } + other => { + return Err(CurateAdjReadError::InvalidSnapshotMetadata { + path: path.to_path_buf(), + message: format!("unknown metadata key '{other}'"), + }); + } + } + } + + if !found_any { + return Err(CurateAdjReadError::MissingSnapshotMetadata { + path: path.to_path_buf(), + }); + } + + let format_version = format_version + .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.format_version'"))?; + if format_version != ADJ_SNAPSHOT_FORMAT_VERSION { + return Err(CurateAdjReadError::UnsupportedSnapshotVersion { + path: path.to_path_buf(), + version: format_version, + supported: ADJ_SNAPSHOT_FORMAT_VERSION, + }); + } + + let snapshot_kind_str = snapshot_kind_str + .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.snapshot_kind'"))?; + let as_of_micros = + as_of_micros.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.as_of_micros'"))?; + let vault_cutoff_micros = vault_cutoff_micros + .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.vault_cutoff_micros'"))?; + let rows_written = + rows_written.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.rows_written'"))?; + let snapshot_checksum = snapshot_checksum + .ok_or_else(|| invalid("missing 'stock_bot.adj_factors.snapshot_checksum'"))?; + + let snapshot_kind = match snapshot_kind_str { + "retrospective" => { + if as_of_micros.is_some() || vault_cutoff_micros.is_some() { + return Err(invalid( + "retrospective snapshot must have 'none' as_of_micros and vault_cutoff_micros", + )); + } + AdjSnapshotKind::RetrospectiveSnapshot + } + "point_in_time_fenced" => { + let fence = AdjPointInTimeFence { + as_of_micros, + vault_cutoff_micros, + }; + if fence.is_retrospective() { + return Err(invalid( + "point_in_time_fenced snapshot must specify as_of_micros and/or vault_cutoff_micros", + )); + } + AdjSnapshotKind::PointInTimeFenced(fence) + } + other => { + return Err(CurateAdjReadError::InvalidSnapshotMetadata { + path: path.to_path_buf(), + message: format!("unknown snapshot_kind '{other}'"), + }); + } + }; + + Ok(PersistedAdjSnapshotMetadata { + format_version, + snapshot_kind, + rows_written, + snapshot_checksum, + }) +} + +fn load_verified_parquet_snapshot( + part_path: &Path, + reader: &SerializedFileReader, + metadata: &PersistedAdjSnapshotMetadata, +) -> Result { + let expected_schema = adj_factors_parquet_schema().map_err(|source| { + CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + } + })?; + if reader.metadata().file_metadata().schema_descr().root_schema() != expected_schema.as_ref() { + return Err(CurateAdjReadError::SchemaMismatch { + path: part_path.to_path_buf(), + }); + } + + let footer_rows = + usize::try_from(reader.metadata().file_metadata().num_rows()).map_err(|_| { + CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "negative or overflowing Parquet footer row count {}", + reader.metadata().file_metadata().num_rows() + ), + } + })?; + if footer_rows != metadata.rows_written { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "parquet footer row count {footer_rows} does not match metadata rows_written {}", + metadata.rows_written + ), + }); + } + + let mut rows = Vec::with_capacity(footer_rows); + let file_meta = reader.metadata(); + for rg_idx in 0..file_meta.num_row_groups() { + let rg_reader = + reader + .get_row_group(rg_idx) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })?; + let num_rows = usize::try_from(file_meta.row_group(rg_idx).num_rows()).map_err(|_| { + CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: "negative or overflowing row-group row count".to_string(), + } + })?; + + let read_i32 = |col_idx: usize| -> Result, CurateAdjReadError> { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader + .get_column_reader(col_idx) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })? { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })?; + if read != num_rows { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "column {col_idx} returned {read} rows, expected {num_rows}" + ), + }); + } + } + _ => { + return Err(CurateAdjReadError::SchemaMismatch { + path: part_path.to_path_buf(), + }); + } + } + Ok(vals) + }; + let read_i64 = |col_idx: usize| -> Result, CurateAdjReadError> { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader + .get_column_reader(col_idx) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })? { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })?; + if read != num_rows { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "column {col_idx} returned {read} rows, expected {num_rows}" + ), + }); + } + } + _ => { + return Err(CurateAdjReadError::SchemaMismatch { + path: part_path.to_path_buf(), + }); + } + } + Ok(vals) + }; + let read_f64 = |col_idx: usize| -> Result, CurateAdjReadError> { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader + .get_column_reader(col_idx) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })? { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })?; + if read != num_rows { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "column {col_idx} returned {read} rows, expected {num_rows}" + ), + }); + } + } + _ => { + return Err(CurateAdjReadError::SchemaMismatch { + path: part_path.to_path_buf(), + }); + } + } + Ok(vals) + }; + let read_opt_str = |col_idx: usize| -> Result>, CurateAdjReadError> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader + .get_column_reader(col_idx) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })? { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .map_err(|source| CurateAdjReadError::Parquet { + path: part_path.to_path_buf(), + source, + })?; + if read != num_rows || levels_read != num_rows { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "column {col_idx} returned ({read}, {levels_read}) rows, expected {num_rows}" + ), + }); + } + } + _ => { + return Err(CurateAdjReadError::SchemaMismatch { + path: part_path.to_path_buf(), + }); + } + } + let mut val_idx = 0usize; + let mut out = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => out.push(None), + 1 => { + let bytes = vals.get(val_idx).ok_or_else(|| { + CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: "definition levels exceeded byte array values".to_string(), + } + })?; + let text = std::str::from_utf8(bytes.data()) + .map_err(|_| CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: "non-UTF8 div_currency value in Parquet".to_string(), + })? + .to_owned(); + val_idx += 1; + out.push(Some(text)); + } + other => { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!("unexpected definition level {other} in div_currency"), + }); + } + } + } + Ok(out) + }; + + let listing_id = read_i32(0)?; + let ex_date = read_i32(1)?; + let split_factor = read_f64(2)?; + let div_cash = read_f64(3)?; + let div_currency = read_opt_str(4)?; + let cum_split_factor = read_f64(5)?; + let cum_total_factor = read_f64(6)?; + let known_at_micros = read_i64(7)?; + + for i in 0..num_rows { + rows.push(AdjFactorsParquetRow { + listing_id: listing_id[i], + ex_date: ex_date[i], + split_factor: split_factor[i], + div_cash: div_cash[i], + div_currency: div_currency[i].clone().map(Cow::Owned), + cum_split_factor: cum_split_factor[i], + cum_total_factor: cum_total_factor[i], + known_at_micros: known_at_micros[i], + }); + } + } + + if rows.len() != metadata.rows_written { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "decoded {} rows, metadata declared {}", + rows.len(), + metadata.rows_written + ), + }); + } + + for pair in rows.windows(2) { + if (pair[0].listing_id, pair[0].ex_date) >= (pair[1].listing_id, pair[1].ex_date) { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "rows are not strictly ascending by (listing_id, ex_date): ({}, {}) followed by ({}, {})", + pair[0].listing_id, pair[0].ex_date, pair[1].listing_id, pair[1].ex_date + ), + }); + } + } + + // 1. Verify every row's known_at falls inside the verified fence (for fenced snapshots). + if let AdjSnapshotKind::PointInTimeFenced(fence) = metadata.snapshot_kind { + for row in &rows { + if !fence.admits(row.known_at_micros) { + return Err(CurateAdjReadError::RowOutsideFence { + path: part_path.to_path_buf(), + listing_id: row.listing_id, + ex_date: row.ex_date, + known_at_micros: row.known_at_micros, + fence, + }); + } + } + } + + // 2. Verify per-listing cum_split_factor suffix-product consistency in reverse. + let mut start = 0usize; + while start < rows.len() { + let listing_id = rows[start].listing_id; + let mut end = start + 1; + while end < rows.len() && rows[end].listing_id == listing_id { + end += 1; + } + let mut running_split = 1.0_f64; + for row in rows[start..end].iter().rev() { + if row.split_factor != 1.0 { + running_split *= row.split_factor; + } + if row.cum_split_factor.to_bits() != running_split.to_bits() { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "cum_split_factor mismatch for (listing_id={}, ex_date={}): persisted {} != recomputed {}", + row.listing_id, row.ex_date, row.cum_split_factor, running_split + ), + }); + } + } + start = end; + } + + // 3. Verify bound snapshot checksum covering format_version, snapshot_kind/fence, and all rows. + let actual_checksum = + compute_snapshot_checksum(metadata.format_version, metadata.snapshot_kind, &rows); + if actual_checksum != metadata.snapshot_checksum { + return Err(CurateAdjReadError::SnapshotIntegrityMismatch { + path: part_path.to_path_buf(), + detail: format!( + "snapshot checksum 0x{actual_checksum:016x} does not match footer 0x{:016x}", + metadata.snapshot_checksum + ), + }); + } + + Ok(AdjFactorsSnapshot { + rows, + snapshot_kind: metadata.snapshot_kind, + }) +} + +#[cfg(test)] +#[path = "curate_adj_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_adj_tests.rs b/tools/curate-etl/src/curate_adj_tests.rs new file mode 100644 index 00000000..b4a4d0b9 --- /dev/null +++ b/tools/curate-etl/src/curate_adj_tests.rs @@ -0,0 +1,2312 @@ +use super::*; + +use std::borrow::Cow; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use crate::parquet_adj::{adj_factors_parquet_schema, write_adj_factors_dataset}; +use crate::provider_mapping::ProviderMappingRow; +use crate::session_close::{ + SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_DATE, +}; +use crate::split::{ymd_to_epoch_days, SplitTable}; + +static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TestTempDir { + path: PathBuf, +} + +impl TestTempDir { + fn new(label: &str) -> Self { + let seq = TEST_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-adj-test-{label}-{}-{seq}", + std::process::id() + )); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } +} + +impl Drop for TestTempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn div( + ex_date: i32, + cash: f64, + currency: &str, + prev_close: Option, + prev_close_currency: Option<&str>, +) -> DividendEvent { + DividendEvent { + ex_date, + cash, + currency: currency.to_string(), + prev_close, + prev_close_currency: prev_close_currency.map(str::to_string), + } +} + +fn assert_conservation(output: &CurateAdjFactorsOutput) { + let s = &output.stats; + assert_eq!( + s.splits_in, + s.splits_dropped_unmapped + + s.splits_dropped_fenced + + s.splits_collision_collapsed + + s.builder.split_events_in, + "split conservation invariant failed: {s:?}" + ); + assert_eq!( + s.dividends_in, + s.dividends_dropped_unmapped + + s.dividends_dropped_fenced + + s.dividends_collision_collapsed + + s.builder.dividend_events_in, + "dividend conservation invariant failed: {s:?}" + ); + if output.snapshot_kind == AdjSnapshotKind::RetrospectiveSnapshot { + assert_eq!(s.splits_dropped_fenced, 0); + assert_eq!(s.dividends_dropped_fenced, 0); + } + assert_eq!( + s.listing_collision_collapsed, + s.splits_collision_collapsed + s.dividends_collision_collapsed, + "listing_collision_collapsed must equal split + dividend collapses: {s:?}" + ); + assert_eq!(s.rows_out, s.builder.rows_out); + assert_eq!(s.rows_out, output.rows.len()); + assert_eq!(s.listings_out, s.builder.keys_out); + + for pair in output.rows.windows(2) { + assert!( + (pair[0].listing_id, pair[0].ex_date) < (pair[1].listing_id, pair[1].ex_date), + "rows must be strictly sorted and unique on (listing_id, ex_date): {:?} vs {:?}", + (pair[0].listing_id, pair[0].ex_date), + (pair[1].listing_id, pair[1].ex_date) + ); + } +} + +fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(1.0); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); +} + +fn assert_row_bitwise_eq(actual: &AdjFactorsParquetRow, expected: &AdjFactorsParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ex_date, expected.ex_date); + assert_eq!(actual.split_factor.to_bits(), expected.split_factor.to_bits()); + assert_eq!(actual.div_cash.to_bits(), expected.div_cash.to_bits()); + assert_eq!(actual.div_currency, expected.div_currency); + assert_eq!( + actual.cum_split_factor.to_bits(), + expected.cum_split_factor.to_bits() + ); + assert_eq!( + actual.cum_total_factor.to_bits(), + expected.cum_total_factor.to_bits() + ); + assert_eq!(actual.known_at_micros, expected.known_at_micros); +} + +fn cum_split_after_parquet(rows: &[AdjFactorsParquetRow], listing_id: i32, bar_date: i32) -> f64 { + let idx = rows.partition_point(|r| match r.listing_id.cmp(&listing_id) { + Ordering::Less => true, + Ordering::Equal => r.ex_date <= bar_date, + Ordering::Greater => false, + }); + match rows.get(idx) { + Some(r) if r.listing_id == listing_id => r.cum_split_factor, + _ => 1.0, + } +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_opt_str = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional utf8"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + let text = std::str::from_utf8(vals[val_idx].data()) + .expect("valid utf8") + .to_owned(); + val_idx += 1; + result.push(Some(text)); + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + + let listing_id = read_i32(0); + let ex_date = read_i32(1); + let split_factor = read_f64(2); + let div_cash = read_f64(3); + let div_currency = read_opt_str(4); + let cum_split_factor = read_f64(5); + let cum_total_factor = read_f64(6); + let known_at_micros = read_i64(7); + + for i in 0..num_rows { + out.push(AdjFactorsParquetRow { + listing_id: listing_id[i], + ex_date: ex_date[i], + split_factor: split_factor[i], + div_cash: div_cash[i], + div_currency: div_currency[i].clone().map(Cow::Owned), + cum_split_factor: cum_split_factor[i], + cum_total_factor: cum_total_factor[i], + known_at_micros: known_at_micros[i], + }); + } + } + out +} + +#[test] +fn nvda_ten_for_one_split_matches_split_table_before_on_and_after_ex_date() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + let ex_date = day(2024, 6, 10); + + let splits = [("NVDA", SplitEvent { ex_date, ratio: 10.0 })]; + let out = curate_adj_factors( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.rows.len(), 1); + assert_eq!(out.stats.listings_out, 1); + assert_eq!(out.rows[0].listing_id, 42); + assert_eq!(out.rows[0].ex_date, ex_date); + assert_eq!(out.rows[0].split_factor, 10.0); + assert_eq!(out.rows[0].cum_split_factor, 10.0); + assert_eq!(out.rows[0].cum_total_factor, 10.0); + assert_eq!(out.rows[0].div_cash, 0.0); + assert_eq!(out.rows[0].div_currency, None); + + let split_table = SplitTable::from_events([(42_i32, SplitEvent { ex_date, ratio: 10.0 })]).unwrap(); + for bar_date in [ex_date - 5, ex_date - 1, ex_date, ex_date + 1, ex_date + 30] { + let expected = split_table.cum_factor_after(&42, bar_date); + let actual = cum_split_after_parquet(&out.rows, 42, bar_date); + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "mismatch on bar_date={bar_date}" + ); + } +} + +#[test] +fn ticker_rename_chains_cum_split_factor_continuously_under_one_listing_id() { + let rename_cutoff = day(2022, 6, 8); + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "OLD_TICK", day(2015, 1, 1), Some(rename_cutoff), 700), + map_row("qm", "NEW_TICK", rename_cutoff + 1, None, 700), + ]) + .unwrap(); + + let d1 = day(2020, 8, 31); // under OLD_TICK + let d2 = day(2024, 6, 10); // under NEW_TICK + + let out = curate_adj_factors( + &mapping, + "qm", + [ + ("OLD_TICK", SplitEvent { ex_date: d1, ratio: 4.0 }), + ("NEW_TICK", SplitEvent { ex_date: d2, ratio: 10.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.listings_out, 1); + assert_eq!(out.rows.len(), 2); + + // Earliest row must reflect the product of both splits (4.0 * 10.0 = 40.0). + assert_eq!(out.rows[0].listing_id, 700); + assert_eq!(out.rows[0].ex_date, d1); + assert_eq!(out.rows[0].split_factor, 4.0); + assert_eq!(out.rows[0].cum_split_factor, 40.0); + assert_eq!(out.rows[0].cum_total_factor, 40.0); + + // Later row has only its own split (10.0). + assert_eq!(out.rows[1].listing_id, 700); + assert_eq!(out.rows[1].ex_date, d2); + assert_eq!(out.rows[1].split_factor, 10.0); + assert_eq!(out.rows[1].cum_split_factor, 10.0); + assert_eq!(out.rows[1].cum_total_factor, 10.0); +} + +#[test] +fn ticker_reuse_produces_two_independent_chains_without_cross_listing_bleed() { + // FB 2012-2022 -> listing 1001, FB 2025+ -> listing 2002 (non-overlapping ranges) + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "FB", day(2012, 5, 18), Some(day(2022, 6, 8)), 1001), + map_row("qm", "FB", day(2025, 1, 2), None, 2002), + ]) + .unwrap(); + + let d_old = day(2018, 4, 15); + let d_gap = day(2023, 7, 1); // unmapped gap between ranges + let d_new = day(2025, 9, 10); + + let out = curate_adj_factors( + &mapping, + "qm", + [ + ("FB", SplitEvent { ex_date: d_old, ratio: 2.0 }), + ("FB", SplitEvent { ex_date: d_gap, ratio: 3.0 }), + ("FB", SplitEvent { ex_date: d_new, ratio: 5.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.splits_in, 3); + assert_eq!(out.stats.splits_dropped_unmapped, 1); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.rows.len(), 2); + + // Listing 1001 must NOT be affected by listing 2002's 5:1 split. + assert_eq!(out.rows[0].listing_id, 1001); + assert_eq!(out.rows[0].ex_date, d_old); + assert_eq!(out.rows[0].split_factor, 2.0); + assert_eq!(out.rows[0].cum_split_factor, 2.0); + + // Listing 2002 has its own independent 5:1 split. + assert_eq!(out.rows[1].listing_id, 2002); + assert_eq!(out.rows[1].ex_date, d_new); + assert_eq!(out.rows[1].split_factor, 5.0); + assert_eq!(out.rows[1].cum_split_factor, 5.0); +} + +#[test] +fn unmapped_splits_and_dividends_are_dropped_and_counted_separately() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "AAPL", + day(2020, 1, 1), + Some(day(2024, 12, 31)), + 10, + )]) + .unwrap(); + + let out = curate_adj_factors( + &mapping, + "qm", + [ + ("AAPL", SplitEvent { ex_date: day(2020, 8, 31), ratio: 4.0 }), + ("AAPL", SplitEvent { ex_date: day(2019, 1, 1), ratio: 2.0 }), // before valid_from + ("UNKNOWN", SplitEvent { ex_date: day(2022, 5, 1), ratio: 3.0 }), + ], + [ + ("AAPL", div(day(2024, 2, 9), 0.24, "USD", Some(188.0), Some("USD"))), + ("AAPL", div(day(2025, 2, 10), 0.25, "USD", Some(220.0), Some("USD"))), // after valid_to + ("NO_SUCH", div(day(2023, 5, 12), 0.50, "USD", Some(50.0), Some("USD"))), + ("NO_SUCH", div(day(2023, 8, 12), 0.50, "USD", Some(52.0), Some("USD"))), + ], + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.splits_in, 3); + assert_eq!(out.stats.splits_dropped_unmapped, 2); + assert_eq!(out.stats.dividends_in, 4); + assert_eq!(out.stats.dividends_dropped_unmapped, 3); + assert_eq!(out.stats.builder.split_events_in, 1); + assert_eq!(out.stats.builder.dividend_events_in, 1); + assert_eq!(out.stats.rows_out, 2); + assert_eq!(out.stats.listings_out, 1); +} + +#[test] +fn bitwise_identical_cross_key_events_collapse_and_are_counted() { + // Two distinct source keys overlapping on the same listing_id. + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "SYM_A", day(2020, 1, 1), None, 55), + map_row("qm", "SYM_B", day(2020, 1, 1), None, 55), + map_row("qm", "SYM_C", day(2020, 1, 1), None, 55), + ]) + .unwrap(); + + let d_split = day(2022, 6, 15); + let d_div = day(2023, 9, 15); + let div_ev = div(d_div, 1.25, "USD", Some(100.0), Some("USD")); + + let out = curate_adj_factors( + &mapping, + "qm", + [ + ("SYM_A", SplitEvent { ex_date: d_split, ratio: 2.0 }), + ("SYM_B", SplitEvent { ex_date: d_split, ratio: 2.0 }), + ("SYM_C", SplitEvent { ex_date: d_split, ratio: 2.0 }), + ], + [ + ("SYM_A", div_ev.clone()), + ("SYM_B", div_ev), + ], + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.splits_in, 3); + assert_eq!(out.stats.splits_collision_collapsed, 2); + assert_eq!(out.stats.dividends_in, 2); + assert_eq!(out.stats.dividends_collision_collapsed, 1); + assert_eq!(out.stats.listing_collision_collapsed, 3); + assert_eq!(out.stats.builder.split_events_in, 1); + assert_eq!(out.stats.builder.dividend_events_in, 1); + assert_eq!(out.rows.len(), 2); + + // Split was collapsed to a single 2:1 (NOT 2*2*2 = 8:1). + assert_eq!(out.rows[0].split_factor, 2.0); + assert_eq!(out.rows[0].cum_split_factor, 2.0); + // Dividend was collapsed to a single $1.25 (NOT $2.50). + assert_eq!(out.rows[1].div_cash, 1.25); + assert_rel_eq(out.rows[1].cum_total_factor, 100.0 / 98.75, 1e-12); +} + +#[test] +fn conflicting_cross_key_split_fails_closed_and_publishes_no_parquet() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "ALIAS_1", day(2020, 1, 1), None, 77), + map_row("qm", "ALIAS_2", day(2020, 1, 1), None, 77), + ]) + .unwrap(); + + let d = day(2023, 5, 1); + let splits = [ + ("ALIAS_1", SplitEvent { ex_date: d, ratio: 2.0 }), + ("ALIAS_2", SplitEvent { ex_date: d, ratio: 3.0 }), + ]; + + let err = curate_adj_factors( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap_err(); + assert_eq!( + err, + CurateAdjError::ConflictingCrossKeySplit { + listing_id: 77, + ex_date: d, + first_key: "ALIAS_1".to_string(), + first_ratio: 2.0, + second_key: "ALIAS_2".to_string(), + second_ratio: 3.0, + } + ); + assert!(err.source().is_none()); + let msg = err.to_string(); + assert!(msg.contains("77") && msg.contains("ALIAS_1") && msg.contains("ALIAS_2")); + + let temp = TestTempDir::new("conflict-split"); + let write_err = curate_and_write_adj_factors( + &temp.path, + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + AdjFactorsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeySplit { listing_id: 77, .. }) + )); + assert!(write_err.source().is_some()); + assert!( + !temp.path.join("adj_factors/part.parquet").exists(), + "curate error must not publish adj_factors/part.parquet" + ); + assert!( + !temp.path.join("adj_factors").exists(), + "curate error must leave out_dir untouched" + ); +} + +#[test] +fn conflicting_cross_key_dividend_fails_closed_on_any_field_mismatch() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "KEY_A", day(2020, 1, 1), None, 88), + map_row("qm", "KEY_B", day(2020, 1, 1), None, 88), + ]) + .unwrap(); + let d = day(2024, 3, 15); + let base = div(d, 0.50, "USD", Some(50.0), Some("USD")); + + let variants = [ + div(d, 0.75, "USD", Some(50.0), Some("USD")), // differing cash + div(d, 0.50, "CAD", Some(50.0), Some("USD")), // differing currency + div(d, 0.50, "USD", Some(51.0), Some("USD")), // differing prev_close + div(d, 0.50, "USD", Some(50.0), Some("CAD")), // differing prev_close_currency + div(d, 0.50, "USD", None, None), // missing prev_close vs present + ]; + + for (idx, other) in variants.into_iter().enumerate() { + let err = curate_adj_factors( + &mapping, + "qm", + std::iter::empty::<(&str, SplitEvent)>(), + [("KEY_A", base.clone()), ("KEY_B", other.clone())], + ) + .unwrap_err(); + assert_eq!( + err, + CurateAdjError::ConflictingCrossKeyDividend { + listing_id: 88, + ex_date: d, + first_key: "KEY_A".to_string(), + second_key: "KEY_B".to_string(), + }, + "variant {idx} should fail closed" + ); + + let temp = TestTempDir::new(&format!("conflict-div-{idx}")); + let write_err = curate_and_write_adj_factors( + &temp.path, + &mapping, + "qm", + std::iter::empty::<(&str, SplitEvent)>(), + [("KEY_A", base.clone()), ("KEY_B", other)], + AdjFactorsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeyDividend { + listing_id: 88, + .. + }) + )); + assert!(!temp.path.join("adj_factors/part.parquet").exists()); + } +} + +#[test] +fn same_key_multi_events_noops_and_dividend_compounding_preserve_builder_semantics() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "COMP", + day(2020, 1, 1), + None, + 300, + )]) + .unwrap(); + + let d_split = day(2022, 3, 1); + let d_noop = day(2022, 6, 1); + let d_div = day(2023, 9, 15); + let d_zero_div = day(2023, 12, 15); + + let out = curate_adj_factors( + &mapping, + "qm", + [ + // Same-key same-day splits multiply (2.0 * 1.5 = 3.0). + ("COMP", SplitEvent { ex_date: d_split, ratio: 2.0 }), + ("COMP", SplitEvent { ex_date: d_split, ratio: 1.5 }), + // 1:1 no-op split dropped by builder. + ("COMP", SplitEvent { ex_date: d_noop, ratio: 1.0 }), + ], + [ + // Same-key regular + special dividend sum (0.50 + 1.50 = 2.00). + ("COMP", div(d_div, 0.50, "USD", Some(100.0), Some("USD"))), + ("COMP", div(d_div, 1.50, "USD", Some(100.0), Some("USD"))), + // Zero-cash dividend dropped by builder. + ("COMP", div(d_zero_div, 0.0, "", None, None)), + ], + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.listing_collision_collapsed, 0); + assert_eq!(out.stats.builder.split_noops_dropped, 1); + assert_eq!(out.stats.builder.dividend_zero_cash_dropped, 1); + assert_eq!(out.rows.len(), 2); + + let expected_div_factor = 100.0 / 98.0; + + // Earlier split row: cum_total_factor > cum_split_factor because of later dividend. + assert_eq!(out.rows[0].ex_date, d_split); + assert_eq!(out.rows[0].split_factor, 3.0); + assert_eq!(out.rows[0].cum_split_factor, 3.0); + assert!(out.rows[0].cum_total_factor > out.rows[0].cum_split_factor); + assert_rel_eq(out.rows[0].cum_total_factor, 3.0 * expected_div_factor, 1e-12); + + // Later dividend row. + assert_eq!(out.rows[1].ex_date, d_div); + assert_eq!(out.rows[1].split_factor, 1.0); + assert_eq!(out.rows[1].div_cash, 2.0); + assert_eq!(out.rows[1].div_currency.as_deref(), Some("USD")); + assert_eq!(out.rows[1].cum_split_factor, 1.0); + assert_rel_eq(out.rows[1].cum_total_factor, expected_div_factor, 1e-12); +} + +#[test] +fn invalid_builder_inputs_and_blank_mapping_source_return_typed_errors() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "BAD", + day(2020, 1, 1), + None, + 50, + )]) + .unwrap(); + + // Blank mapping_source + for blank in ["", " ", "\t\n"] { + let err = curate_adj_factors( + &mapping, + blank, + std::iter::empty::<(&str, SplitEvent)>(), + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap_err(); + assert_eq!(err, CurateAdjError::EmptyMappingSource); + assert!(err.source().is_none()); + } + + // Invalid split ratio (NaN, 0.0, negative) propagates AdjError + let d = day(2023, 1, 10); + let err = curate_adj_factors( + &mapping, + "qm", + [("BAD", SplitEvent { ex_date: d, ratio: -1.0 })], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap_err(); + assert_eq!( + err, + CurateAdjError::Adj(AdjError::InvalidSplitRatio { + ex_date: d, + ratio: -1.0 + }) + ); + assert!(err.source().is_some()); + + // Invalid dividend cash propagates AdjError + let err = curate_adj_factors( + &mapping, + "qm", + std::iter::empty::<(&str, SplitEvent)>(), + [("BAD", div(d, f64::NAN, "USD", None, None))], + ) + .unwrap_err(); + assert!(matches!( + err, + CurateAdjError::Adj(AdjError::InvalidDividendCash { ex_date, .. }) if ex_date == d + )); +} + +#[test] +fn known_at_matches_est_winter_and_edt_summer_and_out_of_range_ex_date_errors_without_panicking() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "TZ", + i32::MIN, + None, + 99, + )]) + .unwrap(); + + let winter_est = day(2024, 1, 15); // EST -> 21:00 UTC + let summer_edt = day(2024, 7, 15); // EDT -> 20:00 UTC + + let out = curate_adj_factors( + &mapping, + "qm", + [ + ("TZ", SplitEvent { ex_date: winter_est, ratio: 2.0 }), + ("TZ", SplitEvent { ex_date: summer_edt, ratio: 3.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.rows.len(), 2); + + let expected_winter = et_session_close_utc_micros(winter_est).unwrap(); + let expected_summer = et_session_close_utc_micros(summer_edt).unwrap(); + assert_eq!(out.rows[0].known_at_micros, expected_winter); + assert_eq!(out.rows[1].known_at_micros, expected_summer); + // Sanity-check UTC hours: 21:00 UTC in EST, 20:00 UTC in EDT. + assert_eq!( + (out.rows[0].known_at_micros - i64::from(winter_est) * 86_400_000_000) / 3_600_000_000, + 21 + ); + assert_eq!( + (out.rows[1].known_at_micros - i64::from(summer_edt) * 86_400_000_000) / 3_600_000_000, + 20 + ); + + // Out-of-range dates outside 1976-01-01..=2030-12-31 must return typed error without panicking. + let bad_dates = [ + day(1975, 12, 31), + day(2031, 1, 1), + i32::MIN, + i32::MAX, + ]; + for bad_date in bad_dates { + let err = curate_adj_factors( + &mapping, + "qm", + [("TZ", SplitEvent { ex_date: bad_date, ratio: 2.0 })], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap_err(); + assert_eq!( + err, + CurateAdjError::ExDateOutOfRange { + listing_id: 99, + ex_date: bad_date, + source: SessionCloseError::DateOutOfRange { + epoch_day: bad_date, + min_supported: SESSION_CLOSE_MIN_SUPPORTED_DATE, + max_supported: SESSION_CLOSE_MAX_SUPPORTED_DATE, + }, + } + ); + assert!(err.source().is_some()); + let msg = err.to_string(); + assert!( + msg.contains("99") && msg.contains(&bad_date.to_string()), + "Display must name listing_id and ex_date, got: {msg}" + ); + } + + // Also verify boundary dates 1976-01-01 and 2030-12-31 succeed. + let boundary_out = curate_adj_factors( + &mapping, + "qm", + [ + ("TZ", SplitEvent { ex_date: SESSION_CLOSE_MIN_SUPPORTED_DATE, ratio: 2.0 }), + ("TZ", SplitEvent { ex_date: SESSION_CLOSE_MAX_SUPPORTED_DATE, ratio: 2.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + assert_eq!(boundary_out.rows.len(), 2); +} + +#[test] +fn permutation_invariance_holds_across_splits_and_dividends() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "A_OLD", day(2010, 1, 1), Some(day(2020, 12, 31)), 100), + map_row("qm", "A_NEW", day(2021, 1, 1), None, 100), + map_row("qm", "A_ALIAS", day(2021, 1, 1), None, 100), + map_row("qm", "B", day(2015, 1, 1), None, 200), + ]) + .unwrap(); + + let base_splits = vec![ + ("A_OLD", SplitEvent { ex_date: day(2018, 5, 1), ratio: 2.0 }), + ("A_NEW", SplitEvent { ex_date: day(2023, 6, 1), ratio: 5.0 }), + ("A_ALIAS", SplitEvent { ex_date: day(2023, 6, 1), ratio: 5.0 }), + ("B", SplitEvent { ex_date: day(2022, 1, 10), ratio: 0.25 }), + ("UNMAPPED", SplitEvent { ex_date: day(2022, 3, 1), ratio: 2.0 }), + ]; + let base_divs = vec![ + ("A_OLD", div(day(2019, 3, 15), 0.40, "USD", Some(80.0), Some("USD"))), + ("A_NEW", div(day(2024, 3, 15), 0.50, "USD", Some(100.0), Some("USD"))), + ("A_ALIAS", div(day(2024, 3, 15), 0.50, "USD", Some(100.0), Some("USD"))), + ("B", div(day(2024, 4, 1), 1.00, "CAD", Some(40.0), Some("CAD"))), + ("B", div(day(2024, 4, 1), 0.25, "CAD", Some(40.0), Some("CAD"))), + ]; + + let baseline = curate_adj_factors(&mapping, "qm", base_splits.clone(), base_divs.clone()).unwrap(); + assert_conservation(&baseline); + + let mut rev_splits = base_splits; + rev_splits.reverse(); + let mut rev_divs = base_divs; + rev_divs.reverse(); + + let reversed = curate_adj_factors(&mapping, "qm", rev_splits, rev_divs).unwrap(); + assert_conservation(&reversed); + assert_eq!(reversed.stats, baseline.stats); + assert_eq!(reversed.rows.len(), baseline.rows.len()); + for (a, b) in reversed.rows.iter().zip(baseline.rows.iter()) { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn curate_and_write_adj_factors_round_trips_parquet_schema_and_rows() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "NVDA", day(1999, 1, 22), None, 10), + map_row("qm", "RY.TO", day(2000, 1, 1), None, 20), + map_row("qm", "RY_ALIAS", day(2000, 1, 1), None, 20), + ]) + .unwrap(); + + let splits = vec![ + ("NVDA", SplitEvent { ex_date: day(2021, 7, 20), ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: day(2024, 6, 10), ratio: 10.0 }), + ("RY.TO", SplitEvent { ex_date: day(2022, 4, 1), ratio: 2.0 }), + ("RY_ALIAS", SplitEvent { ex_date: day(2022, 4, 1), ratio: 2.0 }), + ]; + let dividends = vec![ + ("NVDA", div(day(2024, 6, 11), 0.01, "USD", Some(120.0), Some("USD"))), + ("RY.TO", div(day(2024, 1, 25), 1.38, "CAD", Some(132.0), Some("CAD"))), + ("RY.TO", div(day(2024, 7, 25), 1.42, "CAD", None, None)), + ]; + + let in_mem = curate_adj_factors(&mapping, "qm", splits.clone(), dividends.clone()).unwrap(); + assert_conservation(&in_mem); + + let temp = TestTempDir::new("round-trip"); + let report = curate_and_write_adj_factors( + &temp.path, + &mapping, + "qm", + splits, + dividends, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report.curate_stats, in_mem.stats); + assert_eq!(report.write_stats.rows_written, in_mem.rows.len()); + assert_eq!(report.write_stats.files_written, 1); + assert!(report.write_stats.bytes_written > 0); + + let part_path = temp.path.join("adj_factors/part.parquet"); + assert!(part_path.is_file()); + + // Verify Parquet schema matches contract schema from adj_factors_parquet_schema(). + let expected_schema = adj_factors_parquet_schema().unwrap(); + let file = File::open(&part_path).unwrap(); + let reader = SerializedFileReader::new(file).unwrap(); + assert_eq!( + reader.metadata().file_metadata().schema_descr().root_schema(), + expected_schema.as_ref() + ); + + // Read back all rows and assert bitwise identity plus strict (listing_id, ex_date) ordering. + let read_back = read_parquet_rows(&part_path); + assert_eq!(read_back.len(), in_mem.rows.len()); + for (actual, expected) in read_back.iter().zip(in_mem.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + for pair in read_back.windows(2) { + assert!((pair[0].listing_id, pair[0].ex_date) < (pair[1].listing_id, pair[1].ex_date)); + } + + // Empty input publishes an explicit 0-row Parquet with embedded footer metadata that round-trips. + let empty_temp = TestTempDir::new("empty"); + let empty_report = curate_and_write_adj_factors( + &empty_temp.path, + &mapping, + "qm", + std::iter::empty::<(&str, SplitEvent)>(), + std::iter::empty::<(&str, DividendEvent)>(), + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_report.curate_stats.rows_out, 0); + assert_eq!(empty_report.write_stats.rows_written, 0); + assert_eq!(empty_report.write_stats.files_written, 1); + assert!(empty_report.write_stats.bytes_written > 0); + assert_eq!(empty_report.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); + assert!(empty_temp.path.join("adj_factors/part.parquet").is_file()); + assert!(!empty_temp.path.join("adj_factors/snapshot.json").exists()); + let empty_loaded = read_adj_factors_dataset(&empty_temp.path).unwrap(); + assert!(empty_loaded.rows.is_empty()); + assert_eq!(empty_loaded.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); +} + +#[test] +fn point_in_time_fencing_keeps_earlier_adjusted_read_identical_when_future_actions_are_appended() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "NVDA", day(1999, 1, 22), None, 42), + map_row("qm", "NVDA_ALIAS", day(1999, 1, 22), None, 42), + ]) + .unwrap(); + + let d_split_2021 = day(2021, 7, 20); // 4:1 split + let d_div_2022 = day(2022, 9, 7); // $0.04 dividend on $137.00 prev_close + let d_split_2024 = day(2024, 6, 10); // 10:1 split (future relative to Dec 2023) + let d_div_2024 = day(2024, 9, 12); // future dividend + + let bar_pre_2021 = day(2021, 1, 4); + let raw_close = 800.0_f64; + + // Dec 31, 2023 23:59:59.999999 UTC + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let fence = AdjPointInTimeFence::as_of(as_of_dec_2023); + + // Baseline: only events through 2023 exist. + let base_splits = vec![("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 })]; + let base_divs = vec![( + "NVDA", + div(d_div_2022, 0.04, "USD", Some(137.0), Some("USD")), + )]; + + let pit_before = curate_adj_factors_as_of( + &mapping, + "qm", + base_splits.clone(), + base_divs.clone(), + fence, + ) + .unwrap(); + assert_conservation(&pit_before); + assert_eq!(pit_before.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence)); + assert_eq!(pit_before.stats.splits_dropped_fenced, 0); + assert_eq!(pit_before.stats.dividends_dropped_fenced, 0); + + let (split_f_before, total_f_before) = adj_factors_for_bar(&pit_before.rows, 42, bar_pre_2021); + assert_eq!(split_f_before, 4.0); + assert_eq!(raw_close / split_f_before, 200.0); + + // Now append the June 2024 10:1 split, a Sept 2024 dividend, AND a conflicting future alias + // split on June 2024 — none of them existed as of Dec 31, 2023. + let mut with_future_splits = base_splits.clone(); + with_future_splits.push(("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 })); + with_future_splits.push(("NVDA_ALIAS", SplitEvent { ex_date: d_split_2024, ratio: 99.0 })); + let mut with_future_divs = base_divs.clone(); + with_future_divs.push(( + "NVDA", + div(d_div_2024, 0.01, "USD", Some(115.0), Some("USD")), + )); + + let pit_after = curate_adj_factors_as_of( + &mapping, + "qm", + with_future_splits, + with_future_divs, + fence, + ) + .unwrap(); + assert_conservation(&pit_after); + assert_eq!(pit_after.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence)); + assert_eq!(pit_after.stats.splits_dropped_fenced, 2); + assert_eq!(pit_after.stats.dividends_dropped_fenced, 1); + assert_eq!(pit_after.rows.len(), pit_before.rows.len()); + + // Every curated row must be bitwise identical to the pre-future baseline. + for (actual, expected) in pit_after.rows.iter().zip(pit_before.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + // Earlier bar's split-adjusted and total-adjusted reads stay bitwise identical (divide by 4, + // never 40). + let (split_f_after, total_f_after) = adj_factors_for_bar(&pit_after.rows, 42, bar_pre_2021); + assert_eq!(split_f_after.to_bits(), split_f_before.to_bits()); + assert_eq!(total_f_after.to_bits(), total_f_before.to_bits()); + assert_eq!((raw_close / split_f_after).to_bits(), 200.0_f64.to_bits()); + + // Contrast with retrospective full-history snapshot (without the conflicting alias): + // explicitly tagged as RetrospectiveSnapshot, with cum_split_factor == 40.0 on the 2021 row. + let retro = curate_adj_factors( + &mapping, + "qm", + [ + ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), + ], + [ + ("NVDA", div(d_div_2022, 0.04, "USD", Some(137.0), Some("USD"))), + ("NVDA", div(d_div_2024, 0.01, "USD", Some(115.0), Some("USD"))), + ], + ) + .unwrap(); + assert_conservation(&retro); + assert_eq!(retro.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); + let (retro_split_f, _) = adj_factors_for_bar(&retro.rows, 42, bar_pre_2021); + assert_eq!(retro_split_f, 40.0); +} + +#[test] +fn vault_cutoff_is_strictly_exclusive_and_overrides_later_as_of() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + + let d_2021 = day(2021, 7, 20); + let d_2024 = day(2024, 6, 10); + let known_2024 = et_session_close_utc_micros(d_2024).unwrap(); + let splits = [ + ("NVDA", SplitEvent { ex_date: d_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_2024, ratio: 10.0 }), + ]; + + // as_of is inclusive (<=): known_2024 - 1 excludes 2024 split; known_2024 includes it. + let before_as_of = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + AdjPointInTimeFence::as_of(known_2024 - 1), + ) + .unwrap(); + assert_conservation(&before_as_of); + assert_eq!(before_as_of.rows.len(), 1); + assert_eq!(before_as_of.rows[0].cum_split_factor, 4.0); + + let at_as_of = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + AdjPointInTimeFence::as_of(known_2024), + ) + .unwrap(); + assert_conservation(&at_as_of); + assert_eq!(at_as_of.rows.len(), 2); + assert_eq!(at_as_of.rows[0].cum_split_factor, 40.0); + + // vault_cutoff is strictly exclusive (<): at known_2024 it excludes 2024 split even if as_of + // is later than vault_cutoff. + let vault_at_boundary = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + AdjPointInTimeFence::as_of_with_vault_cutoff(known_2024 + 86_400_000_000, known_2024), + ) + .unwrap(); + assert_conservation(&vault_at_boundary); + assert_eq!(vault_at_boundary.rows.len(), 1); + assert_eq!(vault_at_boundary.stats.splits_dropped_fenced, 1); + assert_eq!(vault_at_boundary.rows[0].cum_split_factor, 4.0); + + // vault_cutoff = known_2024 + 1 admits the 2024 split when no earlier as_of blocks it. + let vault_past_boundary = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + AdjPointInTimeFence::vault_fenced(known_2024 + 1), + ) + .unwrap(); + assert_conservation(&vault_past_boundary); + assert_eq!(vault_past_boundary.rows.len(), 2); + assert_eq!(vault_past_boundary.rows[0].cum_split_factor, 40.0); +} + +#[test] +fn curate_and_write_adj_factors_as_of_round_trips_and_rejects_out_of_range_ex_date() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + i32::MIN, + None, + 42, + )]) + .unwrap(); + + let d_2021 = day(2021, 7, 20); + let d_2024 = day(2024, 6, 10); + let vault_2024_01_01 = i64::from(day(2024, 1, 1)) * 86_400_000_000; + let fence = AdjPointInTimeFence::vault_fenced(vault_2024_01_01); + + let temp = TestTempDir::new("pit-round-trip"); + let report = curate_and_write_adj_factors_as_of( + &temp.path, + &mapping, + "qm", + [ + ("NVDA", SplitEvent { ex_date: d_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_2024, ratio: 10.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + fence, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence)); + assert_eq!(report.curate_stats.splits_dropped_fenced, 1); + assert_eq!(report.write_stats.rows_written, 1); + + let read_back = read_parquet_rows(&temp.path.join("adj_factors/part.parquet")); + assert_eq!(read_back.len(), 1); + assert_eq!(read_back[0].ex_date, d_2021); + assert_eq!(read_back[0].cum_split_factor, 4.0); + assert_eq!(adj_factors_for_bar(&read_back, 42, day(2021, 1, 4)), (4.0, 4.0)); + assert_eq!(adj_factors_for_bar(&read_back, 42, d_2021), (1.0, 1.0)); + assert_eq!(adj_factors_for_bar(&read_back, 999, day(2021, 1, 4)), (1.0, 1.0)); + + // Out-of-range ex_date under a fenced call returns typed ExDateOutOfRange without panicking + // and publishes no Parquet file. + let err_temp = TestTempDir::new("pit-oor"); + let err = curate_and_write_adj_factors_as_of( + &err_temp.path, + &mapping, + "qm", + [("NVDA", SplitEvent { ex_date: day(2031, 1, 1), ratio: 2.0 })], + std::iter::empty::<(&str, DividendEvent)>(), + fence, + AdjFactorsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + CurateAdjWriteError::Curate(CurateAdjError::ExDateOutOfRange { listing_id: 42, .. }) + )); + assert!(!err_temp.path.join("adj_factors/part.parquet").exists()); + assert!(!err_temp.path.join("adj_factors").exists()); +} + +#[test] +fn reopened_parquet_artifact_persists_fence_and_rejects_retrospective_or_incompatible_pit_reads() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + + let d_split_2021 = day(2021, 7, 20); // 4:1 split + let d_split_2024 = day(2024, 6, 10); // 10:1 split + let pre_2021_bar = day(2021, 1, 4); + + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let as_of_dec_2022 = i64::from(day(2023, 1, 1)) * 86_400_000_000 - 1; + let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; + let vault_jan_2024 = i64::from(day(2024, 1, 1)) * 86_400_000_000; + + let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); + let splits = [ + ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), + ]; + + // 1. Publish retrospective snapshot; point-in-time reader MUST reject it on reopen. + let retro_dir = TestTempDir::new("reopen-retro"); + curate_and_write_adj_factors( + &retro_dir.path, + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + + let pit_err = read_adj_factors_dataset_as_of(&retro_dir.path, fence_dec_2023).unwrap_err(); + assert!(matches!( + pit_err, + CurateAdjReadError::RetrospectiveSnapshotRejected { .. } + )); + + // General reader still opens it and explicitly reports RetrospectiveSnapshot. + let retro_loaded = read_adj_factors_dataset(&retro_dir.path).unwrap(); + assert_eq!(retro_loaded.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); + assert_eq!(retro_loaded.factors_for_bar(42, pre_2021_bar), (40.0, 40.0)); + + // 2. Publish Dec 2023 fenced snapshot; reopening with matching fence returns factor 4.0. + let fenced_dir = TestTempDir::new("reopen-fenced"); + curate_and_write_adj_factors_as_of( + &fenced_dir.path, + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2023, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + + let reopened = read_adj_factors_dataset_as_of(&fenced_dir.path, fence_dec_2023).unwrap(); + assert_eq!(reopened.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); + assert_eq!(reopened.rows.len(), 1); + assert_eq!(reopened.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); + + // 3. Reopening with any incompatible or unfenced fence MUST fail closed. + for incompatible in [ + AdjPointInTimeFence::as_of(as_of_dec_2022), + AdjPointInTimeFence::as_of(as_of_dec_2024), + AdjPointInTimeFence::vault_fenced(vault_jan_2024), + AdjPointInTimeFence::as_of_with_vault_cutoff(as_of_dec_2023, vault_jan_2024), + ] { + let err = read_adj_factors_dataset_as_of(&fenced_dir.path, incompatible).unwrap_err(); + assert!(matches!( + err, + CurateAdjReadError::IncompatibleFence { actual, required, .. } + if actual == fence_dec_2023 && required == incompatible + )); + } + let unfenced_err = read_adj_factors_dataset_as_of( + &fenced_dir.path, + AdjPointInTimeFence::retrospective(), + ) + .unwrap_err(); + assert!(matches!(unfenced_err, CurateAdjReadError::UnfencedReadRequested)); + + // 4. Raw Parquet written via write_adj_factors_dataset carries no snapshot footer metadata -> + // fails closed with MissingSnapshotMetadata. + let retro_curated = curate_adj_factors( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + write_adj_factors_dataset( + &fenced_dir.path, + &retro_curated.rows, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + let missing_err = read_adj_factors_dataset_as_of(&fenced_dir.path, fence_dec_2023).unwrap_err(); + assert!(matches!( + missing_err, + CurateAdjReadError::MissingSnapshotMetadata { .. } + )); + + // 5. Unsupported format_version in Parquet footer fails closed. + let unsupported_kv = vec![ + KeyValue::new(KV_FORMAT_VERSION.to_string(), "99".to_string()), + KeyValue::new( + KV_SNAPSHOT_KIND.to_string(), + "point_in_time_fenced".to_string(), + ), + KeyValue::new(KV_AS_OF_MICROS.to_string(), as_of_dec_2023.to_string()), + KeyValue::new(KV_VAULT_CUTOFF_MICROS.to_string(), "none".to_string()), + KeyValue::new(KV_ROWS_WRITTEN.to_string(), "0".to_string()), + KeyValue::new( + KV_SNAPSHOT_CHECKSUM.to_string(), + "0xcbf29ce484222325".to_string(), + ), + ]; + write_forged_parquet_with_kv(&fenced_dir.path, &[], unsupported_kv); + let version_err = read_adj_factors_dataset(&fenced_dir.path).unwrap_err(); + assert!(matches!( + version_err, + CurateAdjReadError::UnsupportedSnapshotVersion { + version: 99, + supported: 1, + .. + } + )); +} + +fn write_forged_parquet_with_kv( + out_dir: &Path, + rows: &[AdjFactorsParquetRow], + kv_metadata: Vec, +) { + let adj_dir = out_dir.join("adj_factors"); + fs::create_dir_all(&adj_dir).unwrap(); + let part_path = adj_dir.join("part.parquet"); + let schema = adj_factors_parquet_schema().unwrap(); + let props = Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(ZstdLevel::try_new(3).unwrap())) + .set_key_value_metadata(Some(kv_metadata)) + .build(), + ); + let file = BufWriter::new(File::create(&part_path).unwrap()); + let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); + if !rows.is_empty() { + let mut listing_id = Vec::with_capacity(rows.len()); + let mut ex_date = Vec::with_capacity(rows.len()); + let mut split_factor = Vec::with_capacity(rows.len()); + let mut div_cash = Vec::with_capacity(rows.len()); + let mut div_currency_ids = Vec::with_capacity(rows.len()); + let mut div_currency_def_levels = Vec::with_capacity(rows.len()); + let mut div_currency_interner = StringInterner::default(); + let mut cum_split_factor = Vec::with_capacity(rows.len()); + let mut cum_total_factor = Vec::with_capacity(rows.len()); + let mut known_at_micros = Vec::with_capacity(rows.len()); + let mut scratch = Vec::new(); + for row in rows { + listing_id.push(row.listing_id); + ex_date.push(row.ex_date); + split_factor.push(row.split_factor); + div_cash.push(row.div_cash); + match row.div_currency.as_deref() { + Some(c) => { + div_currency_ids.push(div_currency_interner.intern(c)); + div_currency_def_levels.push(1); + } + None => div_currency_def_levels.push(0), + } + cum_split_factor.push(row.cum_split_factor); + cum_total_factor.push(row.cum_total_factor); + known_at_micros.push(row.known_at_micros); + } + let mut rg = writer.next_row_group().unwrap(); + write_i32_col(&mut rg, &listing_id).unwrap(); + write_i32_col(&mut rg, &ex_date).unwrap(); + write_f64_col(&mut rg, &split_factor, None).unwrap(); + write_f64_col(&mut rg, &div_cash, None).unwrap(); + write_optional_interned_str_col( + &mut rg, + &div_currency_ids, + &div_currency_def_levels, + &div_currency_interner, + &mut scratch, + ) + .unwrap(); + write_f64_col(&mut rg, &cum_split_factor, None).unwrap(); + write_f64_col(&mut rg, &cum_total_factor, None).unwrap(); + write_i64_col(&mut rg, &known_at_micros).unwrap(); + rg.close().unwrap(); + } + writer.close().unwrap(); +} + +fn assert_no_transient_files(adj_dir: &Path) { + for entry in fs::read_dir(adj_dir).unwrap() { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!( + name, "part.parquet", + "unexpected leftover file in adj_factors dir: {name}" + ); + } +} + +#[test] +fn empty_fenced_rebuild_atomically_supersedes_previous_nonempty_parquet_snapshot() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + + let d_split_2024 = day(2024, 6, 10); // 10:1 split + let bar_2023 = day(2023, 6, 15); + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let as_of_dec_2025 = i64::from(day(2026, 1, 1)) * 86_400_000_000 - 1; + let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); + let fence_dec_2025 = AdjPointInTimeFence::as_of(as_of_dec_2025); + + let splits = [("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 })]; + let dir = TestTempDir::new("empty-fenced-supersede"); + + // Step 1: Publish a nonempty snapshot containing the June 2024 10:1 split. + let first_report = curate_and_write_adj_factors_as_of( + &dir.path, + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2025, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(first_report.write_stats.rows_written, 1); + let first_loaded = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2025).unwrap(); + assert_eq!(first_loaded.factors_for_bar(42, bar_2023), (10.0, 10.0)); + + // Step 2: Rebuild the SAME output root as of Dec 2023 with that split as the only input. + // The fence excludes every event -> 0 rows MUST supersede the old part.parquet. + let second_report = curate_and_write_adj_factors_as_of( + &dir.path, + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2023, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(second_report.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); + assert_eq!(second_report.curate_stats.splits_dropped_fenced, 1); + assert_eq!(second_report.curate_stats.rows_out, 0); + assert_eq!(second_report.write_stats.rows_written, 0); + assert_eq!(second_report.write_stats.files_written, 1); + assert!(second_report.write_stats.bytes_written > 0); + assert_no_transient_files(&dir.path.join("adj_factors")); + + // Reopening via the verified PIT reader sees 0 rows and factor (1.0, 1.0) — never 10.0. + let reopened = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap(); + assert_eq!(reopened.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); + assert!(reopened.rows.is_empty()); + assert_eq!(reopened.factors_for_bar(42, bar_2023), (1.0, 1.0)); + + // Reopening part.parquet directly also sees a valid 0-row Parquet with contract schema. + let part_path = dir.path.join("adj_factors/part.parquet"); + let expected_schema = adj_factors_parquet_schema().unwrap(); + let reader = SerializedFileReader::new(File::open(&part_path).unwrap()).unwrap(); + assert_eq!( + reader.metadata().file_metadata().schema_descr().root_schema(), + expected_schema.as_ref() + ); + assert_eq!(reader.metadata().file_metadata().num_rows(), 0); + let raw_rows = read_parquet_rows(&part_path); + assert!(raw_rows.is_empty()); + assert_eq!(adj_factors_for_bar(&raw_rows, 42, bar_2023), (1.0, 1.0)); + + // Old fence is now rejected as incompatible. + let old_fence_err = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2025).unwrap_err(); + assert!(matches!( + old_fence_err, + CurateAdjReadError::IncompatibleFence { .. } + )); +} + +#[test] +fn concurrent_overlapping_publishes_never_leave_torn_snapshot_or_transient_files() { + use std::sync::Barrier; + + let mapping = Arc::new( + ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(1999, 1, 22), None, 42)]) + .unwrap(), + ); + let d_split_2021 = day(2021, 7, 20); + let d_split_2024 = day(2024, 6, 10); + let pre_2021_bar = day(2021, 1, 4); + + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; + let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); + let fence_dec_2024 = AdjPointInTimeFence::as_of(as_of_dec_2024); + + let splits = vec![ + ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), + ]; + + let dir = TestTempDir::new("concurrent-publish"); + let barrier = Arc::new(Barrier::new(2)); + + for _round in 0..8 { + std::thread::scope(|scope| { + let b1 = Arc::clone(&barrier); + let m1 = Arc::clone(&mapping); + let s1 = splits.clone(); + let p1 = dir.path.clone(); + let h1 = scope.spawn(move || { + b1.wait(); + curate_and_write_adj_factors_as_of( + &p1, + &m1, + "qm", + s1, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2023, + AdjFactorsWriteOptions::default(), + ) + }); + + let b2 = Arc::clone(&barrier); + let m2 = Arc::clone(&mapping); + let s2 = splits.clone(); + let p2 = dir.path.clone(); + let h2 = scope.spawn(move || { + b2.wait(); + curate_and_write_adj_factors_as_of( + &p2, + &m2, + "qm", + s2, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2024, + AdjFactorsWriteOptions::default(), + ) + }); + + let r1 = h1.join().unwrap().unwrap(); + let r2 = h2.join().unwrap().unwrap(); + assert_eq!(r1.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); + assert_eq!(r2.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2024)); + }); + + assert_no_transient_files(&dir.path.join("adj_factors")); + + // Reopening must succeed with a self-consistent snapshot matching one of the two exact fences. + let loaded = read_adj_factors_dataset(&dir.path).unwrap(); + match loaded.snapshot_kind { + AdjSnapshotKind::PointInTimeFenced(f) if f == fence_dec_2023 => { + assert_eq!(loaded.rows.len(), 1); + assert_eq!(loaded.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); + let pit_ok = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap(); + assert_eq!(pit_ok.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); + let pit_err = + read_adj_factors_dataset_as_of(&dir.path, fence_dec_2024).unwrap_err(); + assert!(matches!( + pit_err, + CurateAdjReadError::IncompatibleFence { actual, required, .. } + if actual == fence_dec_2023 && required == fence_dec_2024 + )); + } + AdjSnapshotKind::PointInTimeFenced(f) if f == fence_dec_2024 => { + assert_eq!(loaded.rows.len(), 2); + assert_eq!(loaded.factors_for_bar(42, pre_2021_bar), (40.0, 40.0)); + let pit_ok = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2024).unwrap(); + assert_eq!(pit_ok.factors_for_bar(42, pre_2021_bar), (40.0, 40.0)); + let pit_err = + read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap_err(); + assert!(matches!( + pit_err, + CurateAdjReadError::IncompatibleFence { actual, required, .. } + if actual == fence_dec_2024 && required == fence_dec_2023 + )); + } + other => panic!("unexpected snapshot_kind after concurrent publish: {other:?}"), + } + } +} + +#[test] +fn interrupted_replacement_before_rename_preserves_previous_snapshot_and_cleans_up() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + + let d_split_2021 = day(2021, 7, 20); + let d_split_2024 = day(2024, 6, 10); + let pre_2021_bar = day(2021, 1, 4); + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; + let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); + let fence_dec_2024 = AdjPointInTimeFence::as_of(as_of_dec_2024); + + let splits = [ + ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), + ]; + + let dir = TestTempDir::new("interrupted-replacement"); + + // Step 1: Publish a valid Dec 2023 snapshot (factor 4.0). + curate_and_write_adj_factors_as_of( + &dir.path, + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2023, + AdjFactorsWriteOptions::default(), + ) + .unwrap(); + + // Step 2: Attempt to replace with Dec 2024 snapshot, injecting an I/O failure after staging + + // backup and before fs::rename. + let dec_2024 = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2024, + ) + .unwrap(); + let mut saw_backup = false; + let err = write_adj_factors_snapshot_parquet_with_hooks( + &dir.path, + &dec_2024.rows, + dec_2024.snapshot_kind, + AdjFactorsWriteOptions::default(), + |_final_path, backup_path| { + saw_backup = backup_path.is_some_and(Path::is_file); + Err(io::Error::new( + io::ErrorKind::Interrupted, + "injected pre-rename failure", + )) + }, + ) + .unwrap_err(); + + assert!(saw_backup, "backup file must have been created before hook ran"); + assert!(matches!(err, ParquetAdjError::Io { .. })); + assert_no_transient_files(&dir.path.join("adj_factors")); + + // Step 3: Prior Dec 2023 snapshot must remain intact and readable with factor 4.0. + let reopened = read_adj_factors_dataset_as_of(&dir.path, fence_dec_2023).unwrap(); + assert_eq!(reopened.snapshot_kind, AdjSnapshotKind::PointInTimeFenced(fence_dec_2023)); + assert_eq!(reopened.rows.len(), 1); + assert_eq!(reopened.factors_for_bar(42, pre_2021_bar), (4.0, 4.0)); +} + +#[test] +fn tampered_cutoff_out_of_fence_and_forged_chain_are_rejected_on_reopen() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + + let d_split_2021 = day(2021, 7, 20); + let d_split_2024 = day(2024, 6, 10); + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let as_of_dec_2024 = i64::from(day(2025, 1, 1)) * 86_400_000_000 - 1; + let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); + let fence_dec_2024 = AdjPointInTimeFence::as_of(as_of_dec_2024); + + let splits = [ + ("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 }), + ("NVDA", SplitEvent { ex_date: d_split_2024, ratio: 10.0 }), + ]; + + let dec_2024 = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2024, + ) + .unwrap(); + assert_eq!(dec_2024.rows.len(), 2); + assert_eq!(dec_2024.rows[0].cum_split_factor, 40.0); + + // Case 1: Rewrite Dec 2024 Parquet changing ONLY as_of_micros in footer to Dec 2023 + // (keeping Dec 2024 rows and old Dec 2024 checksum) -> must be rejected (never returns 40.0). + let dir1 = TestTempDir::new("tampered-cutoff-only"); + let old_checksum = compute_snapshot_checksum( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2024), + &dec_2024.rows, + ); + let tampered_kv = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), + dec_2024.rows.len(), + old_checksum, + ); + write_forged_parquet_with_kv(&dir1.path, &dec_2024.rows, tampered_kv); + let err1 = read_adj_factors_dataset_as_of(&dir1.path, fence_dec_2023).unwrap_err(); + assert!( + matches!( + err1, + CurateAdjReadError::RowOutsideFence { .. } + | CurateAdjReadError::SnapshotIntegrityMismatch { .. } + ), + "expected RowOutsideFence or SnapshotIntegrityMismatch, got: {err1:?}" + ); + + // Case 2: Forge a Parquet file declaring Dec 2023 with a recomputed checksum over Dec 2024 + // rows -> rejected with RowOutsideFence. + let dir2 = TestTempDir::new("forged-out-of-fence"); + let forged_checksum_2 = compute_snapshot_checksum( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), + &dec_2024.rows, + ); + let forged_kv_2 = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), + dec_2024.rows.len(), + forged_checksum_2, + ); + write_forged_parquet_with_kv(&dir2.path, &dec_2024.rows, forged_kv_2); + let err2 = read_adj_factors_dataset_as_of(&dir2.path, fence_dec_2023).unwrap_err(); + assert!( + matches!( + err2, + CurateAdjReadError::RowOutsideFence { + listing_id: 42, + ex_date, + fence, + .. + } if ex_date == d_split_2024 && fence == fence_dec_2023 + ), + "expected RowOutsideFence for 2024 split, got: {err2:?}" + ); + + // Case 3: Forge a Parquet file declaring Dec 2023 with a recomputed checksum over ONLY the + // pre-2024 row carrying stale cum_split_factor = 40.0 (split_factor = 4.0) -> rejected with + // SnapshotIntegrityMismatch by per-listing suffix-product verification. + let dir3 = TestTempDir::new("forged-stale-chain"); + let stale_rows = vec![dec_2024.rows[0].clone()]; + assert_eq!(stale_rows[0].split_factor, 4.0); + assert_eq!(stale_rows[0].cum_split_factor, 40.0); + let forged_checksum_3 = compute_snapshot_checksum( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), + &stale_rows, + ); + let forged_kv_3 = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), + stale_rows.len(), + forged_checksum_3, + ); + write_forged_parquet_with_kv(&dir3.path, &stale_rows, forged_kv_3); + let err3 = read_adj_factors_dataset_as_of(&dir3.path, fence_dec_2023).unwrap_err(); + assert!( + matches!(err3, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), + "expected SnapshotIntegrityMismatch for stale cum_split_factor=40.0, got: {err3:?}" + ); +} + +#[test] +fn checksum_binds_cutoff_and_snapshot_kind_even_when_all_rows_remain_admitted() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + + let d_split_2021 = day(2021, 7, 20); + let as_of_dec_2023 = i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1; + let fence_dec_2023 = AdjPointInTimeFence::as_of(as_of_dec_2023); + + let splits = [("NVDA", SplitEvent { ex_date: d_split_2021, ratio: 4.0 })]; + let dec_2023 = curate_adj_factors_as_of( + &mapping, + "qm", + splits, + std::iter::empty::<(&str, DividendEvent)>(), + fence_dec_2023, + ) + .unwrap(); + assert_conservation(&dec_2023); + assert_eq!(dec_2023.rows.len(), 1); + let row_known_at = dec_2023.rows[0].known_at_micros; + + let original_checksum = compute_snapshot_checksum( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(fence_dec_2023), + &dec_2023.rows, + ); + + // Edit 1: Shift as_of_micros forward by +1 day (still admits the 2021 row) while keeping + // the original checksum -> must fail with SnapshotIntegrityMismatch (not RowOutsideFence). + let edited_as_of_fence = AdjPointInTimeFence::as_of(as_of_dec_2023 + 86_400_000_000); + assert!(edited_as_of_fence.admits(row_known_at)); + let dir_as_of = TestTempDir::new("checksum-binds-as-of"); + let kv_as_of = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(edited_as_of_fence), + dec_2023.rows.len(), + original_checksum, + ); + write_forged_parquet_with_kv(&dir_as_of.path, &dec_2023.rows, kv_as_of); + let err_as_of = read_adj_factors_dataset_as_of(&dir_as_of.path, edited_as_of_fence).unwrap_err(); + assert!( + matches!(err_as_of, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), + "expected SnapshotIntegrityMismatch for edited as_of_micros, got: {err_as_of:?}" + ); + + // Edit 2: Add a vault_cutoff_micros after the 2021 row's known_at (still admits the row) + // while keeping the original checksum -> must fail with SnapshotIntegrityMismatch. + let vault_after_2021 = i64::from(day(2024, 6, 1)) * 86_400_000_000; + let edited_vault_fence = + AdjPointInTimeFence::as_of_with_vault_cutoff(as_of_dec_2023, vault_after_2021); + assert!(edited_vault_fence.admits(row_known_at)); + let dir_vault = TestTempDir::new("checksum-binds-vault"); + let kv_vault = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::PointInTimeFenced(edited_vault_fence), + dec_2023.rows.len(), + original_checksum, + ); + write_forged_parquet_with_kv(&dir_vault.path, &dec_2023.rows, kv_vault); + let err_vault = + read_adj_factors_dataset_as_of(&dir_vault.path, edited_vault_fence).unwrap_err(); + assert!( + matches!(err_vault, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), + "expected SnapshotIntegrityMismatch for edited vault_cutoff_micros, got: {err_vault:?}" + ); + + // Edit 3: Relabel the snapshot as RetrospectiveSnapshot while keeping the original checksum + // -> must fail with SnapshotIntegrityMismatch. + let dir_retro = TestTempDir::new("checksum-binds-kind"); + let kv_retro = build_snapshot_key_value_metadata( + ADJ_SNAPSHOT_FORMAT_VERSION, + AdjSnapshotKind::RetrospectiveSnapshot, + dec_2023.rows.len(), + original_checksum, + ); + write_forged_parquet_with_kv(&dir_retro.path, &dec_2023.rows, kv_retro); + let err_retro = read_adj_factors_dataset(&dir_retro.path).unwrap_err(); + assert!( + matches!(err_retro, CurateAdjReadError::SnapshotIntegrityMismatch { .. }), + "expected SnapshotIntegrityMismatch for relabeled snapshot_kind, got: {err_retro:?}" + ); +} + +#[test] +fn unverified_missing_and_corrupt_parquet_files_fail_closed_with_typed_errors() { + let fence = AdjPointInTimeFence::as_of(i64::from(day(2024, 1, 1)) * 86_400_000_000 - 1); + + // 1. Missing adj_factors/part.parquet -> CurateAdjReadError::Io + let missing_dir = TestTempDir::new("read-missing-file"); + let missing_err = read_adj_factors_dataset(&missing_dir.path).unwrap_err(); + assert!( + matches!(missing_err, CurateAdjReadError::Io { .. }), + "expected Io for missing part.parquet, got: {missing_err:?}" + ); + let missing_pit_err = read_adj_factors_dataset_as_of(&missing_dir.path, fence).unwrap_err(); + assert!( + matches!(missing_pit_err, CurateAdjReadError::Io { .. }), + "expected Io for missing part.parquet in PIT reader, got: {missing_pit_err:?}" + ); + + // 2. Raw Parquet written via write_adj_factors_dataset (no stock_bot.adj_factors.* keys) + // -> CurateAdjReadError::MissingSnapshotMetadata + let raw_dir = TestTempDir::new("read-raw-parquet"); + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "NVDA", + day(1999, 1, 22), + None, + 42, + )]) + .unwrap(); + let curated = curate_adj_factors( + &mapping, + "qm", + [("NVDA", SplitEvent { ex_date: day(2021, 7, 20), ratio: 4.0 })], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + write_adj_factors_dataset(&raw_dir.path, &curated.rows, AdjFactorsWriteOptions::default()) + .unwrap(); + let raw_err = read_adj_factors_dataset(&raw_dir.path).unwrap_err(); + assert!( + matches!(raw_err, CurateAdjReadError::MissingSnapshotMetadata { .. }), + "expected MissingSnapshotMetadata for raw Parquet, got: {raw_err:?}" + ); + let raw_pit_err = read_adj_factors_dataset_as_of(&raw_dir.path, fence).unwrap_err(); + assert!( + matches!(raw_pit_err, CurateAdjReadError::MissingSnapshotMetadata { .. }), + "expected MissingSnapshotMetadata for raw Parquet in PIT reader, got: {raw_pit_err:?}" + ); + + // 3. Garbage bytes written to adj_factors/part.parquet -> CurateAdjReadError::Parquet + let corrupt_dir = TestTempDir::new("read-garbage-bytes"); + let adj_dir = corrupt_dir.path.join("adj_factors"); + fs::create_dir_all(&adj_dir).unwrap(); + fs::write(adj_dir.join("part.parquet"), b"not a valid parquet file at all").unwrap(); + let corrupt_err = read_adj_factors_dataset(&corrupt_dir.path).unwrap_err(); + assert!( + matches!(corrupt_err, CurateAdjReadError::Parquet { .. }), + "expected Parquet error for garbage bytes, got: {corrupt_err:?}" + ); + let corrupt_pit_err = read_adj_factors_dataset_as_of(&corrupt_dir.path, fence).unwrap_err(); + assert!( + matches!(corrupt_pit_err, CurateAdjReadError::Parquet { .. }), + "expected Parquet error for garbage bytes in PIT reader, got: {corrupt_pit_err:?}" + ); +} + +#[test] +fn asymmetric_cross_key_multi_event_days_fail_closed() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "PRIMARY", day(2020, 1, 1), None, 777), + map_row("qm", "ALIAS", day(2020, 1, 1), None, 777), + ]) + .unwrap(); + + let d = day(2023, 8, 15); + + // Case 1: Primary emits regular + special dividend on (777, d), alias emits only regular. + let regular = div(d, 0.25, "USD", Some(100.0), Some("USD")); + let special = div(d, 1.50, "USD", Some(100.0), Some("USD")); + let div_err = curate_adj_factors( + &mapping, + "qm", + std::iter::empty::<(&str, SplitEvent)>(), + [ + ("PRIMARY", regular.clone()), + ("PRIMARY", special), + ("ALIAS", regular), + ], + ) + .unwrap_err(); + assert!( + matches!( + div_err, + CurateAdjError::ConflictingCrossKeyDividend { + listing_id: 777, + ex_date, + .. + } if ex_date == d + ), + "expected ConflictingCrossKeyDividend, got: {div_err:?}" + ); + + // Case 2: Primary emits two differing splits on (777, d), alias emits only one of them. + let split_err = curate_adj_factors( + &mapping, + "qm", + [ + ("PRIMARY", SplitEvent { ex_date: d, ratio: 2.0 }), + ("PRIMARY", SplitEvent { ex_date: d, ratio: 3.0 }), + ("ALIAS", SplitEvent { ex_date: d, ratio: 2.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap_err(); + assert!( + matches!( + split_err, + CurateAdjError::ConflictingCrossKeySplit { + listing_id: 777, + ex_date, + .. + } if ex_date == d + ), + "expected ConflictingCrossKeySplit, got: {split_err:?}" + ); +} + +#[test] +fn bitwise_identical_cross_key_noop_splits_collapse_then_drop_with_conservation() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "NOOP_A", day(2020, 1, 1), None, 808), + map_row("qm", "NOOP_B", day(2020, 1, 1), None, 808), + ]) + .unwrap(); + let d = day(2023, 5, 1); + + let out = curate_adj_factors( + &mapping, + "qm", + [ + ("NOOP_A", SplitEvent { ex_date: d, ratio: 1.0 }), + ("NOOP_B", SplitEvent { ex_date: d, ratio: 1.0 }), + ], + std::iter::empty::<(&str, DividendEvent)>(), + ) + .unwrap(); + + assert_conservation(&out); + assert_eq!(out.stats.splits_in, 2); + assert_eq!(out.stats.splits_dropped_unmapped, 0); + assert_eq!(out.stats.splits_dropped_fenced, 0); + assert_eq!(out.stats.splits_collision_collapsed, 1); + assert_eq!(out.stats.listing_collision_collapsed, 1); + assert_eq!(out.stats.builder.split_events_in, 1); + assert_eq!(out.stats.builder.split_noops_dropped, 1); + assert_eq!(out.stats.rows_out, 0); + assert_eq!(out.stats.listings_out, 0); + assert!(out.rows.is_empty()); +} + +#[test] +fn unmapped_out_of_range_dates_count_as_unmapped_without_error() { + let mapping = ProviderMappingTable::from_rows([map_row( + "qm", + "MAPPED", + day(2020, 1, 1), + Some(day(2024, 12, 31)), + 101, + )]) + .unwrap(); + + let pre_1976 = day(1975, 12, 31); + let in_range_day = day(2022, 6, 15); + + let splits = vec![ + ("UNMAPPED", SplitEvent { ex_date: pre_1976, ratio: 2.0 }), + ("UNMAPPED", SplitEvent { ex_date: i32::MIN, ratio: 3.0 }), + ("UNMAPPED", SplitEvent { ex_date: i32::MAX, ratio: 4.0 }), + ("MAPPED", SplitEvent { ex_date: pre_1976, ratio: 5.0 }), + ("MAPPED", SplitEvent { ex_date: i32::MIN, ratio: 6.0 }), + ("MAPPED", SplitEvent { ex_date: i32::MAX, ratio: 7.0 }), + ("MAPPED", SplitEvent { ex_date: in_range_day, ratio: 2.0 }), + ]; + let dividends = vec![ + ("UNMAPPED", div(pre_1976, 0.5, "USD", Some(10.0), Some("USD"))), + ("UNMAPPED", div(i32::MIN, 0.5, "USD", Some(10.0), Some("USD"))), + ("UNMAPPED", div(i32::MAX, 0.5, "USD", Some(10.0), Some("USD"))), + ("MAPPED", div(pre_1976, 0.25, "USD", Some(10.0), Some("USD"))), + ("MAPPED", div(i32::MIN, 0.25, "USD", Some(10.0), Some("USD"))), + ("MAPPED", div(i32::MAX, 0.25, "USD", Some(10.0), Some("USD"))), + ]; + + // Retrospective mode: all 6 out-of-range unmapped splits and 6 dividends drop cleanly. + let retro = curate_adj_factors(&mapping, "qm", splits.clone(), dividends.clone()).unwrap(); + assert_conservation(&retro); + assert_eq!(retro.stats.splits_in, 7); + assert_eq!(retro.stats.splits_dropped_unmapped, 6); + assert_eq!(retro.stats.dividends_in, 6); + assert_eq!(retro.stats.dividends_dropped_unmapped, 6); + assert_eq!(retro.stats.rows_out, 1); + assert_eq!(retro.rows[0].listing_id, 101); + assert_eq!(retro.rows[0].ex_date, in_range_day); + + // Point-in-time fenced mode: unmapped out-of-range events still count as unmapped, not + // ExDateOutOfRange, before fencing runs. + let fence = AdjPointInTimeFence::as_of(i64::from(day(2023, 1, 1)) * 86_400_000_000 - 1); + let fenced = curate_adj_factors_as_of(&mapping, "qm", splits, dividends, fence).unwrap(); + assert_conservation(&fenced); + assert_eq!(fenced.stats.splits_in, 7); + assert_eq!(fenced.stats.splits_dropped_unmapped, 6); + assert_eq!(fenced.stats.splits_dropped_fenced, 0); + assert_eq!(fenced.stats.dividends_in, 6); + assert_eq!(fenced.stats.dividends_dropped_unmapped, 6); + assert_eq!(fenced.stats.dividends_dropped_fenced, 0); + assert_eq!(fenced.stats.rows_out, 1); + assert_eq!(fenced.rows[0].listing_id, 101); + assert_eq!(fenced.rows[0].ex_date, in_range_day); +} + +struct TestRng(u64); + +impl TestRng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + fn range_usize(&mut self, upper: usize) -> usize { + (self.next_u64() as usize) % upper + } + + fn range_i32(&mut self, lo: i32, hi_inclusive: i32) -> i32 { + let span = u64::from((hi_inclusive - lo) as u32) + 1; + lo + (self.next_u64() % span) as i32 + } +} + +type SeededAdjFixture = ( + ProviderMappingTable, + Vec<(String, SplitEvent)>, + Vec<(String, DividendEvent)>, +); + +fn build_seeded_multi_listing_fixture(seed: u64) -> SeededAdjFixture { + let mut rng = TestRng(seed); + let min_date = day(2016, 1, 4); + let max_date = day(2025, 12, 15); + + let mut mapping_rows = Vec::new(); + let mut keys = Vec::new(); + for idx in 0..12_i32 { + let listing_id = 1_000 + idx; + let key = format!("SYM_{idx:02}"); + mapping_rows.push(map_row("qm", &key, day(2010, 1, 1), None, listing_id)); + keys.push(key); + } + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + + let split_ratios = [2.0_f64, 3.0, 4.0, 0.5, 0.25, 1.5, 1.0]; + let currencies = ["USD", "CAD"]; + + let mut splits = Vec::new(); + let mut dividends = Vec::new(); + + // Deterministic same-day multi-split and reciprocal split scenarios on listing 1000 & 1001. + let same_day_split = day(2020, 4, 15); + splits.push(("SYM_00".to_string(), SplitEvent { ex_date: same_day_split, ratio: 2.0 })); + splits.push(("SYM_00".to_string(), SplitEvent { ex_date: same_day_split, ratio: 3.0 })); + // Reciprocal splits (2:1 followed by 1:2) across distinct dates and on the same day. + splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2019, 3, 11), ratio: 2.0 })); + splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2021, 9, 20), ratio: 0.5 })); + splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2022, 5, 2), ratio: 4.0 })); + splits.push(("SYM_01".to_string(), SplitEvent { ex_date: day(2022, 5, 2), ratio: 0.25 })); + + // Same-day regular + special dividend on listing 1002. + let same_day_div = day(2021, 11, 10); + dividends.push(( + "SYM_02".to_string(), + div(same_day_div, 0.35, "USD", Some(80.0), Some("USD")), + )); + dividends.push(( + "SYM_02".to_string(), + div(same_day_div, 1.25, "USD", Some(80.0), Some("USD")), + )); + + // Seeded random splits and dividends spanning 2016..=2025. + for _ in 0..48 { + let key = keys[rng.range_usize(keys.len())].clone(); + let ex_date = rng.range_i32(min_date, max_date); + let ratio = split_ratios[rng.range_usize(split_ratios.len())]; + splits.push((key, SplitEvent { ex_date, ratio })); + } + for _ in 0..140 { + let key = keys[rng.range_usize(keys.len())].clone(); + let ex_date = rng.range_i32(min_date, max_date); + let cash = (rng.range_usize(200) as f64) * 0.01; // includes 0.0 no-op dividends + let currency = currencies[rng.range_usize(currencies.len())]; + let prev_close = if rng.range_usize(5) == 0 { + None + } else { + Some(20.0 + (rng.range_usize(400) as f64) * 0.5) + }; + let prev_close_currency = prev_close.map(|_| currency); + dividends.push((key, div(ex_date, cash, currency, prev_close, prev_close_currency))); + } + + (mapping, splits, dividends) +} + +#[test] +fn seeded_multi_row_group_round_trip_and_cutoff_equivalence() { + let (mapping, splits, dividends) = build_seeded_multi_listing_fixture(0x5EED_AD01); + let cutoff_as_of = i64::from(day(2022, 1, 1)) * 86_400_000_000 - 1; + let fence = AdjPointInTimeFence::as_of(cutoff_as_of); + + let opts = AdjFactorsWriteOptions { + row_group_rows: 7, + ..AdjFactorsWriteOptions::default() + }; + + // 1. Retrospective multi-row-group round-trip (row_group_rows = 7) is bit-for-bit identical. + let retro_dir = TestTempDir::new("seeded-rg7-retro"); + let retro_expected = + curate_adj_factors(&mapping, "qm", splits.clone(), dividends.clone()).unwrap(); + assert_conservation(&retro_expected); + assert!( + retro_expected.rows.len() > 14, + "fixture must span multiple 7-row row groups" + ); + + let retro_report = curate_and_write_adj_factors( + &retro_dir.path, + &mapping, + "qm", + splits.clone(), + dividends.clone(), + opts, + ) + .unwrap(); + assert_eq!(retro_report.write_stats.rows_written, retro_expected.rows.len()); + + let part_path = retro_dir.path.join("adj_factors/part.parquet"); + let raw_reader = SerializedFileReader::new(File::open(&part_path).unwrap()).unwrap(); + assert!( + raw_reader.metadata().num_row_groups() > 1, + "expected multiple row groups with row_group_rows=7" + ); + + let retro_reopened = read_adj_factors_dataset(&retro_dir.path).unwrap(); + assert_eq!(retro_reopened.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); + assert_eq!(retro_reopened.rows.len(), retro_expected.rows.len()); + for (actual, expected) in retro_reopened.rows.iter().zip(&retro_expected.rows) { + assert_row_bitwise_eq(actual, expected); + } + + // 2. Fenced multi-row-group round-trip is bit-for-bit identical. + let fenced_dir = TestTempDir::new("seeded-rg7-fenced"); + let fenced_expected = + curate_adj_factors_as_of(&mapping, "qm", splits.clone(), dividends.clone(), fence) + .unwrap(); + assert_conservation(&fenced_expected); + assert!(fenced_expected.stats.splits_dropped_fenced > 0); + assert!(fenced_expected.stats.dividends_dropped_fenced > 0); + assert!(fenced_expected.rows.len() > 7); + + curate_and_write_adj_factors_as_of( + &fenced_dir.path, + &mapping, + "qm", + splits.clone(), + dividends.clone(), + fence, + opts, + ) + .unwrap(); + let fenced_reopened = read_adj_factors_dataset_as_of(&fenced_dir.path, fence).unwrap(); + assert_eq!( + fenced_reopened.snapshot_kind, + AdjSnapshotKind::PointInTimeFenced(fence) + ); + assert_eq!(fenced_reopened.rows.len(), fenced_expected.rows.len()); + for (actual, expected) in fenced_reopened.rows.iter().zip(&fenced_expected.rows) { + assert_row_bitwise_eq(actual, expected); + } + + // 3. Cutoff equivalence: curating full history with `fence` produces rows bitwise-identical + // to curating only the events admitted by `fence`. + let admitted_splits: Vec<_> = splits + .into_iter() + .filter(|(_, ev)| { + let known_at = et_session_close_utc_micros(ev.ex_date).unwrap(); + fence.admits(known_at) + }) + .collect(); + let admitted_dividends: Vec<_> = dividends + .into_iter() + .filter(|(_, ev)| { + let known_at = et_session_close_utc_micros(ev.ex_date).unwrap(); + fence.admits(known_at) + }) + .collect(); + let pre_filtered = + curate_adj_factors(&mapping, "qm", admitted_splits, admitted_dividends).unwrap(); + assert_conservation(&pre_filtered); + assert_eq!(fenced_expected.rows.len(), pre_filtered.rows.len()); + for (actual, expected) in fenced_expected.rows.iter().zip(&pre_filtered.rows) { + assert_row_bitwise_eq(actual, expected); + } +} + +#[test] +fn seeded_lookahead_invariance_across_500_pre_cutoff_bar_queries() { + let (mapping, splits, dividends) = build_seeded_multi_listing_fixture(0x5EED_AD02); + let cutoff_day = day(2021, 12, 31); + let cutoff_as_of = et_session_close_utc_micros(cutoff_day).unwrap(); + let vault_cutoff = i64::from(day(2022, 7, 1)) * 86_400_000_000; + let fence = AdjPointInTimeFence::as_of_with_vault_cutoff(cutoff_as_of, vault_cutoff); + + let full_fenced = + curate_adj_factors_as_of(&mapping, "qm", splits.clone(), dividends.clone(), fence).unwrap(); + assert_conservation(&full_fenced); + assert!( + full_fenced.stats.splits_dropped_fenced > 0 + && full_fenced.stats.dividends_dropped_fenced > 0, + "fixture must contain post-cutoff future events to exercise look-ahead invariance" + ); + + let past_splits: Vec<_> = splits + .into_iter() + .filter(|(_, ev)| fence.admits(et_session_close_utc_micros(ev.ex_date).unwrap())) + .collect(); + let past_dividends: Vec<_> = dividends + .into_iter() + .filter(|(_, ev)| fence.admits(et_session_close_utc_micros(ev.ex_date).unwrap())) + .collect(); + let past_only_fenced = + curate_adj_factors_as_of(&mapping, "qm", past_splits, past_dividends, fence).unwrap(); + assert_conservation(&past_only_fenced); + + let mut query_rng = TestRng(0x5EED_0500); + let query_start = day(2015, 1, 2); + for _ in 0..500 { + let listing_id = 1_000 + query_rng.range_i32(0, 11); + let bar_date = query_rng.range_i32(query_start, cutoff_day); + + let (split_with_future, total_with_future) = + adj_factors_for_bar(&full_fenced.rows, listing_id, bar_date); + let (split_past_only, total_past_only) = + adj_factors_for_bar(&past_only_fenced.rows, listing_id, bar_date); + + assert_eq!( + split_with_future.to_bits(), + split_past_only.to_bits(), + "split factor look-ahead leak for listing_id={listing_id} bar_date={bar_date}" + ); + assert_eq!( + total_with_future.to_bits(), + total_past_only.to_bits(), + "total factor look-ahead leak for listing_id={listing_id} bar_date={bar_date}" + ); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 978251c4..cab0cfd4 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -4,6 +4,8 @@ pub mod adj; pub mod bars; pub mod bench; pub mod bson_eod_prices; +pub mod bson_qm_actions; +pub mod bson_stream; pub mod cli; pub mod corporate_actions; pub mod events; @@ -32,6 +34,18 @@ pub use bson_eod_prices::{ decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar, }; +pub use bson_qm_actions::{ + decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc, + decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, BsonQmActionDecodeStats, + BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, + FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE, +}; +pub use bson_stream::{ + decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, + decode_qm_dividend_stream, decode_qm_split_chunks, decode_qm_split_stream, BsonStreamError, + BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, + DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, +}; pub use corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow, CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, @@ -122,6 +136,15 @@ pub use curate_fx::{ FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START, }; +pub mod curate_adj; +pub use curate_adj::{ + adj_factors_for_bar, curate_adj_factors, curate_adj_factors_as_of, + curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, read_adj_factors_dataset, + read_adj_factors_dataset_as_of, AdjFactorsSnapshot, AdjPointInTimeFence, AdjSnapshotKind, + CurateAdjError, CurateAdjFactorsOutput, CurateAdjFactorsStats, CurateAdjFactorsWriteReport, + CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION, +}; + pub mod curate_corporate_actions; pub use curate_corporate_actions::{ curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index fca9bfb2..05e12444 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -5,12 +5,13 @@ use std::process::ExitCode; use curate_etl::bench::{ run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, - run_corporate_actions_benchmark, run_curate_bars_benchmark, - run_curate_corporate_actions_benchmark, run_curate_events_benchmark, run_curate_fx_benchmark, - run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, - run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, - run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, - run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, + run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark, + run_curate_adj_benchmark, run_curate_bars_benchmark, run_curate_corporate_actions_benchmark, + run_curate_events_benchmark, run_curate_fx_benchmark, run_curate_shorts_benchmark, + run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, + run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, + run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, + run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -504,6 +505,82 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchBsonQmActions(rows)) => { + let report = run_bson_qm_actions_benchmark(rows); + println!("curate-etl bench-bson-qm-actions"); + println!( + " input: rows={} splits={} dividends={} bytes={}", + report.rows, report.split_rows, report.dividend_rows, report.bytes + ); + println!( + " splits: decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})", + report.split_stats.decoded, + report.split_stats.split_noop_ratio_one, + report.split_stats.rejected_total(), + report.split_stats.rejected_missing_field, + report.split_stats.rejected_empty_field, + report.split_stats.rejected_wrong_type, + report.split_stats.rejected_malformed_date, + report.split_stats.rejected_invalid_number, + report.split_stats.rejected_corrupt_document + ); + println!( + " dividends: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})", + report.dividend_stats.decoded, + report.dividend_stats.rejected_total(), + report.dividend_stats.rejected_missing_field, + report.dividend_stats.rejected_empty_field, + report.dividend_stats.rejected_wrong_type, + report.dividend_stats.rejected_malformed_date, + report.dividend_stats.rejected_invalid_number, + report.dividend_stats.rejected_corrupt_document + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s latency={:.2} ns/doc checksum=0x{:016x}", + report.elapsed_ms, + report.docs_per_sec, + report.mb_per_sec, + report.ns_per_doc, + report.checksum + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchBsonStream(rows)) => { + let report = match run_bson_stream_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: bson-stream benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-bson-stream"); + println!(" input: rows={} bytes={}", report.rows, report.bytes); + println!( + " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}", + report.stats.decoded, + report.stats.rejected_total(), + report.stats.rejected_missing_field, + report.stats.rejected_empty_field, + report.stats.rejected_wrong_type, + report.stats.rejected_malformed_date, + report.stats.rejected_invalid_number, + report.stats.rejected_corrupt_document, + report.checksum + ); + println!( + " buffer: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s", + report.buffer_elapsed_ms, report.buffer_rows_per_sec, report.buffer_mib_per_sec + ); + println!( + " stream: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s ratio={:.3}x peak_buffer_capacity={} bytes", + report.stream_elapsed_ms, + report.stream_rows_per_sec, + report.stream_mib_per_sec, + report.stream_to_buffer_ratio, + report.peak_buffer_capacity + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchCurateBars(rows)) => { let report = match run_curate_bars_benchmark(rows) { Ok(report) => report, @@ -759,6 +836,67 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchCurateAdj(events)) => { + let report = match run_curate_adj_benchmark(events) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-adj benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.events > 0 { + (report.rows_out as f64 / report.events as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-adj"); + println!( + " input: events={} splits={} dividends={} keys={}", + report.events, report.splits_in, report.dividends_in, report.key_count + ); + println!( + " builder: rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}", + report.stats.builder.rows_out, + report.stats.builder.keys_out, + report.stats.builder.split_noops_dropped, + report.stats.builder.dividend_zero_cash_dropped, + report.stats.builder.dividends_missing_prev_close, + report.stats.builder.dividends_currency_mismatch, + report.stats.builder.dividends_not_below_prev_close + ); + println!( + " stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.listings_out, + report.stage_elapsed_ms, + report.stage_events_per_sec, + report.stage_ns_per_event, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.2} ms throughput={:.0} events/s", + report.total_elapsed_ms, report.total_events_per_sec + ); + println!( + " curate: splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}", + report.stats.splits_dropped_unmapped, + report.stats.dividends_dropped_unmapped, + report.stats.splits_collision_collapsed, + report.stats.dividends_collision_collapsed, + report.stats.listing_collision_collapsed + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchCurateCorporateActions(events)) => { let report = match run_curate_corporate_actions_benchmark(events) { Ok(report) => report, diff --git a/tools/curate-etl/tests/bson_qm_actions_contract.rs b/tools/curate-etl/tests/bson_qm_actions_contract.rs new file mode 100644 index 00000000..1b43f1e2 --- /dev/null +++ b/tools/curate-etl/tests/bson_qm_actions_contract.rs @@ -0,0 +1,205 @@ +//! Public-API integration contract test for `qmSplits` and `qmDividends` raw BSON decoders (`M1.2w`). + +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use bson::DateTime; +use curate_etl::{ + build_corporate_actions, curate_adj_factors, decode_qm_dividend_buffer, + decode_qm_dividend_bytes, decode_qm_dividend_doc, decode_qm_split_buffer, + decode_qm_split_bytes, decode_qm_split_doc, ymd_to_epoch_days, BsonQmActionError, + CorporateActionKind, KnownAtSource, ProviderMappingRow, ProviderMappingTable, SplitTable, + FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, + FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE, +}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +#[test] +fn public_field_constants_and_single_doc_decoders_match_contract() { + assert_eq!(FIELD_QM_SEARCH_CODE, "qmSearchCode"); + assert_eq!(FIELD_DATE, "date"); + assert_eq!(FIELD_DECLARED, "declared"); + assert_eq!(FIELD_SPLIT_RATIO, "splitratio"); + assert_eq!(FIELD_USD_FX_RATE, "usdFxRate"); + assert_eq!(FIELD_DIVIDEND_CASH, "amount"); + assert_eq!(FIELD_DIVIDEND_CURRENCY, "currency"); + + let mut split_doc = RawDocumentBuf::new(); + split_doc.append(cstr!("qmSearchCode"), "NVDA"); + split_doc.append(cstr!("date"), "2024-06-10"); + split_doc.append(cstr!("declared"), "2024-05-22"); + split_doc.append(cstr!("splitratio"), 10_i32); + split_doc.append(cstr!("usdFxRate"), 1_i32); + + let split = decode_qm_split_doc(&split_doc).unwrap(); + assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split); + assert_eq!(split.qm_search_code, "NVDA"); + assert_eq!(split.ex_date, day(2024, 6, 10)); + assert_eq!(split.ratio, 10.0); + assert_eq!(split.declared_date, Some(day(2024, 5, 22))); + + let mut div_doc = RawDocumentBuf::new(); + div_doc.append(cstr!("qmSearchCode"), "RY:CA"); + div_doc.append( + cstr!("date"), + DateTime::from_millis(i64::from(day(2024, 11, 15)) * 86_400_000), + ); + div_doc.append(cstr!("declared"), RawBsonRef::Null); + div_doc.append(cstr!("amount"), 1.42_f64); + div_doc.append(cstr!("currency"), "CAD"); + div_doc.append(cstr!("usdFxRate"), 1_i32); + + let div = decode_qm_dividend_doc(&div_doc).unwrap(); + assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div); + assert_eq!(div.qm_search_code, "RY:CA"); + assert_eq!(div.ex_date, day(2024, 11, 15)); + assert_eq!(div.cash, 1.42); + assert_eq!(div.currency, "CAD"); + assert_eq!(div.declared_date, None); +} + +#[test] +fn public_buffer_decoders_reconcile_and_feed_all_downstream_builders() { + let mut split_buf = Vec::new(); + + let mut s_nvda = RawDocumentBuf::new(); + s_nvda.append(cstr!("qmSearchCode"), "NVDA"); + s_nvda.append(cstr!("date"), "2024-06-10"); + s_nvda.append(cstr!("declared"), "2024-05-22"); + s_nvda.append(cstr!("splitratio"), 10.0_f64); + split_buf.extend_from_slice(s_nvda.as_bytes()); + + let mut s_noop = RawDocumentBuf::new(); + s_noop.append(cstr!("qmSearchCode"), "NVDA"); + s_noop.append(cstr!("date"), "2024-07-01"); + s_noop.append(cstr!("splitratio"), 1_i64); + split_buf.extend_from_slice(s_noop.as_bytes()); + + let mut s_bad = RawDocumentBuf::new(); + s_bad.append(cstr!("qmSearchCode"), "NVDA"); + s_bad.append(cstr!("date"), "2024-07-02"); + s_bad.append(cstr!("splitratio"), -3.0_f64); + split_buf.extend_from_slice(s_bad.as_bytes()); + + let mut div_buf = Vec::new(); + + let mut d_ry = RawDocumentBuf::new(); + d_ry.append(cstr!("qmSearchCode"), "RY:CA"); + d_ry.append(cstr!("date"), "2024-11-15"); + d_ry.append(cstr!("declared"), "2024-10-30"); + d_ry.append(cstr!("amount"), 1.42_f64); + d_ry.append(cstr!("currency"), "CAD"); + d_ry.append(cstr!("usdFxRate"), 1_i32); + div_buf.extend_from_slice(d_ry.as_bytes()); + + let mut d_bad = RawDocumentBuf::new(); + d_bad.append(cstr!("qmSearchCode"), "RY:CA"); + d_bad.append(cstr!("date"), "2023-02-29"); + d_bad.append(cstr!("amount"), 1.0_f64); + d_bad.append(cstr!("currency"), "CAD"); + div_buf.extend_from_slice(d_bad.as_bytes()); + + let mapping = ProviderMappingTable::from_rows([ + ProviderMappingRow { + source: "qm".to_string(), + source_id: "NVDA".to_string(), + listing_id: 101, + valid_from: day(2020, 1, 1), + valid_to: None, + }, + ProviderMappingRow { + source: "qm".to_string(), + source_id: "RY:CA".to_string(), + listing_id: 303, + valid_from: day(2020, 1, 1), + valid_to: None, + }, + ]) + .unwrap(); + + let mut split_events = Vec::new(); + let mut split_actions = Vec::new(); + let mut split_errs = Vec::new(); + let split_stats = decode_qm_split_buffer( + &split_buf, + |s| { + split_events.push((s.qm_search_code.to_owned(), s.to_split_event())); + if let Some(pair) = + s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date)) + { + split_actions.push(pair); + } + }, + |_, err| split_errs.push(err), + ); + + assert_eq!(split_stats.docs_in, 3); + assert_eq!(split_stats.decoded, 2); + assert_eq!(split_stats.split_noop_ratio_one, 1); + assert_eq!(split_stats.rejected_invalid_number, 1); + assert_eq!( + split_stats.decoded + split_stats.rejected_total(), + split_stats.docs_in + ); + assert!(matches!( + split_errs.as_slice(), + [BsonQmActionError::InvalidNumber { + field: FIELD_SPLIT_RATIO, + .. + }] + )); + + let mut div_events = Vec::new(); + let mut div_actions = Vec::new(); + let mut div_errs = Vec::new(); + let div_stats = decode_qm_dividend_buffer( + &div_buf, + |d| { + div_events.push(( + d.qm_search_code.to_owned(), + d.to_dividend_event(Some(142.0), Some("CAD".to_string())), + )); + if let Some(pair) = + d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date)) + { + div_actions.push(pair); + } + }, + |_, err| div_errs.push(err), + ); + + assert_eq!(div_stats.docs_in, 2); + assert_eq!(div_stats.decoded, 1); + assert_eq!(div_stats.rejected_malformed_date, 1); + assert_eq!( + div_stats.decoded + div_stats.rejected_total(), + div_stats.docs_in + ); + assert!(matches!( + div_errs.as_slice(), + [BsonQmActionError::MalformedDate { field: FIELD_DATE }] + )); + + // Feed SplitTable. + let split_table = SplitTable::from_events(split_events.iter().cloned()).unwrap(); + assert_eq!(split_table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0); + + // Feed curate_adj_factors. + let adj = curate_adj_factors(&mapping, "qm", split_events, div_events).unwrap(); + assert_eq!(adj.rows.len(), 2); + assert_eq!(adj.stats.builder.split_noops_dropped, 1); + assert_eq!(adj.rows[0].listing_id, 101); + assert_eq!(adj.rows[0].split_factor, 10.0); + assert_eq!(adj.rows[1].listing_id, 303); + assert_eq!(adj.rows[1].div_cash, 1.42); + assert_eq!(adj.rows[1].div_currency.as_deref(), Some("CAD")); + + // Feed build_corporate_actions. + let ca = build_corporate_actions(split_actions, div_actions, std::iter::empty()).unwrap(); + assert_eq!(ca.rows.len(), 2); + assert_eq!(ca.rows[0].kind, CorporateActionKind::Split); + assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate); + assert_eq!(ca.rows[1].kind, CorporateActionKind::Dividend); + assert_eq!(ca.rows[1].known_at_source, KnownAtSource::DeclaredDate); +} diff --git a/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs b/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs new file mode 100644 index 00000000..471f281f --- /dev/null +++ b/tools/curate-etl/tests/bson_qm_actions_qa_contract.rs @@ -0,0 +1,520 @@ +//! QA contract tests for the public `qmSplits` / `qmDividends` raw BSON decoders (T-107 / M1.2w). +//! +//! Covers gaps left by `src/bson_qm_actions_tests.rs` and `tests/bson_qm_actions_contract.rs`, +//! using only the public API: +//! - zero-copy: `qm_search_code` / `currency` borrow from the input buffer; +//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; +//! - `usdFxRate` / unknown fields with corrupt payloads are skipped without decoding, while the +//! same corruption inside a known field is a typed `CorruptBson` naming that field; +//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch); +//! - `split_noop_ratio_one` counts exactly `1.0`, not near-one ratios; +//! - error callbacks receive the exact byte offset of the rejected document; empty buffer, +//! truncated tail after good docs, `i32::MAX` declared length; +//! - seeded byte-mutation fuzz for both collections: never panics, always reconciles, and every +//! streamed row equals the single-document decode of the same bytes; +//! - benchmark guard: synthetic docs actually decode (rejections stay near the injected ~0.5%), +//! so a field-constant change cannot silently turn the benchmark into a rejection-path timing; +//! - `bench-bson-qm-actions` binary: identical checksum across two runs, invalid args exit 1. + +use std::process::{Command, Output}; + +use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; +use bson::DateTime; +use curate_etl::bench::run_bson_qm_actions_benchmark; +use curate_etl::{ + decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc, + decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, iter_raw_bson_docs, + ymd_to_epoch_days, BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DIVIDEND_CASH, + FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, +}; + +const MILLIS_PER_DAY: i64 = 86_400_000; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn split_doc(code: &str, date: &str, ratio: f64) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), "ignored"); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("splitratio"), ratio); + doc.append(cstr!("usdFxRate"), 1_i32); + doc +} + +fn dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), "ignored"); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("date"), date); + doc.append(cstr!("declared"), "2024-05-01"); + doc.append(cstr!("amount"), cash); + doc.append(cstr!("currency"), currency); + doc.append(cstr!("usdFxRate"), 1_i32); + doc +} + +fn ptr_within(s: &str, buf: &[u8]) -> bool { + let range = buf.as_ptr_range(); + let p = s.as_ptr(); + range.contains(&p) && (p as usize + s.len()) <= range.end as usize +} + +/// Overwrites the first occurrence of `needle` in `bytes` with `replacement` (same length). +fn patch(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) { + assert_eq!(needle.len(), replacement.len()); + let pos = bytes + .windows(needle.len()) + .position(|w| w == needle) + .expect("needle present"); + bytes[pos..pos + needle.len()].copy_from_slice(replacement); +} + +#[test] +fn decoded_strings_borrow_directly_from_the_input_buffer() { + let s = split_doc("NVDA", "2024-06-10", 10.0); + let split = decode_qm_split_bytes(s.as_bytes()).unwrap(); + assert!(ptr_within(split.qm_search_code, s.as_bytes())); + + let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + let mut buf = Vec::new(); + buf.extend_from_slice(d.as_bytes()); + let mut seen = Vec::new(); + decode_qm_dividend_buffer(&buf, |div| seen.push(div), |_, e| panic!("{e}")); + assert_eq!(seen.len(), 1); + assert!(ptr_within(seen[0].qm_search_code, &buf)); + assert!(ptr_within(seen[0].currency, &buf)); +} + +#[test] +fn field_order_is_irrelevant_keys_are_case_sensitive_and_nested_lookalikes_are_ignored() { + // Reverse field order decodes identically. + let mut rev = RawDocumentBuf::new(); + rev.append(cstr!("usdFxRate"), 1.0_f64); + rev.append(cstr!("currency"), "CAD"); + rev.append(cstr!("amount"), 1.42_f64); + rev.append(cstr!("declared"), "2024-05-01"); + rev.append(cstr!("date"), "2024-11-15"); + rev.append(cstr!("qmSearchCode"), "RY:CA"); + let fwd = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + assert_eq!( + decode_qm_dividend_doc(&rev).unwrap(), + decode_qm_dividend_doc(&fwd).unwrap() + ); + + // Differently-cased keys are unknown fields, so the required field is missing. + let mut cased = RawDocumentBuf::new(); + cased.append(cstr!("QmSearchCode"), "NVDA"); + cased.append(cstr!("date"), "2024-06-10"); + cased.append(cstr!("splitratio"), 10.0_f64); + assert_eq!( + decode_qm_split_doc(&cased).unwrap_err(), + BsonQmActionError::MissingField { + field: FIELD_QM_SEARCH_CODE + } + ); + let mut cased_ratio = RawDocumentBuf::new(); + cased_ratio.append(cstr!("qmSearchCode"), "NVDA"); + cased_ratio.append(cstr!("date"), "2024-06-10"); + cased_ratio.append(cstr!("splitRatio"), 10.0_f64); + assert_eq!( + decode_qm_split_doc(&cased_ratio).unwrap_err(), + BsonQmActionError::MissingField { + field: FIELD_SPLIT_RATIO + } + ); + + // A nested sub-document carrying look-alike keys must neither satisfy nor poison the decode. + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("splitratio"), -99.0_f64); + nested.append(cstr!("amount"), "bad"); + nested.append(cstr!("currency"), 7_i32); + nested.append(cstr!("date"), "not-a-date"); + let mut outer = split_doc("NVDA", "2024-06-10", 10.0); + outer.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); + let split = decode_qm_split_doc(&outer).unwrap(); + assert_eq!(split.ratio, 10.0); + + let mut outer_div = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + outer_div.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); + let div = decode_qm_dividend_doc(&outer_div).unwrap(); + assert_eq!((div.cash, div.currency), (1.42, "CAD")); + + let mut only_nested = RawDocumentBuf::new(); + only_nested.append(cstr!("qmSearchCode"), "NVDA"); + only_nested.append(cstr!("date"), "2024-06-10"); + only_nested.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref())); + assert_eq!( + decode_qm_split_doc(&only_nested).unwrap_err(), + BsonQmActionError::MissingField { + field: FIELD_SPLIT_RATIO + } + ); +} + +#[test] +fn corrupt_payload_in_ignored_field_is_skipped_but_in_known_field_names_that_field() { + // Unknown field / `usdFxRate` with invalid UTF-8 string bytes: framing is valid, payload is + // never decoded. + let mut d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD"); + d.append(cstr!("zzExtra"), "XYZW"); + let mut bytes = d.as_bytes().to_vec(); + patch(&mut bytes, b"XYZW", &[0xFF, 0xFE, 0xFD, 0xFC]); + let div = decode_qm_dividend_bytes(&bytes).unwrap(); + assert_eq!(div.currency, "CAD"); + + let mut s = split_doc("NVDA", "2024-06-10", 10.0); + s.append(cstr!("usdFxRate"), "QQQQ"); + let mut bytes = s.as_bytes().to_vec(); + patch(&mut bytes, b"QQQQ", &[0xC3, 0x28, 0xA0, 0xA1]); + assert_eq!(decode_qm_split_bytes(&bytes).unwrap().ratio, 10.0); + + // Same corruption inside `currency` is a typed CorruptBson naming the field (no panic). + let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "QQQ"); + let mut bytes = d.as_bytes().to_vec(); + patch(&mut bytes, b"QQQ", &[0xFF, 0xFE, 0xFD]); + match decode_qm_dividend_bytes(&bytes).unwrap_err() { + BsonQmActionError::CorruptBson { offset, detail } => { + assert_eq!(offset, 0); + assert!(detail.contains(FIELD_DIVIDEND_CURRENCY), "{detail}"); + } + other => panic!("expected CorruptBson, got {other:?}"), + } +} + +#[test] +fn datetime_dates_floor_to_utc_day_at_boundaries() { + let cases = [ + (-1_i64, -1_i32), + (0, 0), + (-MILLIS_PER_DAY, -1), + (-MILLIS_PER_DAY - 1, -2), + ( + i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1, + day(2024, 6, 10), + ), + ( + i64::from(day(2024, 6, 11)) * MILLIS_PER_DAY, + day(2024, 6, 11), + ), + ]; + for (ms, expected) in cases { + let mut s = RawDocumentBuf::new(); + s.append(cstr!("qmSearchCode"), "IBM"); + s.append(cstr!("date"), DateTime::from_millis(ms)); + s.append(cstr!("declared"), DateTime::from_millis(ms)); + s.append(cstr!("splitratio"), 2_i64); + let split = decode_qm_split_doc(&s).unwrap(); + assert_eq!(split.ex_date, expected, "ms={ms}"); + assert_eq!(split.declared_date, Some(expected), "ms={ms}"); + + let mut d = RawDocumentBuf::new(); + d.append(cstr!("qmSearchCode"), "IBM"); + d.append(cstr!("date"), DateTime::from_millis(ms)); + d.append(cstr!("amount"), 1_i32); + d.append(cstr!("currency"), "USD"); + assert_eq!( + decode_qm_dividend_doc(&d).unwrap().ex_date, + expected, + "ms={ms}" + ); + } +} + +#[test] +fn noop_counter_counts_only_exact_ratio_one() { + let mut buf = Vec::new(); + for ratio in [1.0, 1.000_000_000_1, 0.999_999_999_9, 1.0, 2.0] { + buf.extend_from_slice(split_doc("X", "2024-03-15", ratio).as_bytes()); + } + let mut n = 0; + let stats = decode_qm_split_buffer(&buf, |_| n += 1, |_, e| panic!("{e}")); + assert_eq!(n, 5); + assert_eq!(stats.decoded, 5); + assert_eq!(stats.split_noop_ratio_one, 2); + assert_eq!(stats.rejected_total(), 0); + + // Dividends never touch the split no-op counter. + let d = dividend_doc("X", "2024-03-15", 1.0, "USD"); + let stats = decode_qm_dividend_buffer(d.as_bytes(), |_| {}, |_, e| panic!("{e}")); + assert_eq!(stats.split_noop_ratio_one, 0); +} + +#[test] +fn error_callbacks_report_exact_offsets_and_framing_failures_stop_cleanly() { + // Empty buffer: nothing in, nothing out. + let stats = decode_qm_split_buffer(&[], |_| panic!(), |_, _| panic!()); + assert_eq!(stats, Default::default()); + let stats = decode_qm_dividend_buffer(&[], |_| panic!(), |_, _| panic!()); + assert_eq!(stats, Default::default()); + + let good = dividend_doc("A", "2024-06-10", 0.5, "USD"); + let bad_cash = dividend_doc("B", "2024-06-10", -0.5, "USD"); + let bad_date = dividend_doc("C", "2024-13-01", 0.5, "USD"); + let mut buf = Vec::new(); + let mut expected_err_offsets = Vec::new(); + buf.extend_from_slice(good.as_bytes()); + expected_err_offsets.push(buf.len()); + buf.extend_from_slice(bad_cash.as_bytes()); + expected_err_offsets.push(buf.len()); + buf.extend_from_slice(bad_date.as_bytes()); + buf.extend_from_slice(good.as_bytes()); + // Truncated tail: declares a full doc but only half is present. + expected_err_offsets.push(buf.len()); + let tail_start = buf.len(); + buf.extend_from_slice(&good.as_bytes()[..good.as_bytes().len() / 2]); + + let mut errs = Vec::new(); + let mut codes = Vec::new(); + let stats = decode_qm_dividend_buffer( + &buf, + |d: RawQmDividend<'_>| codes.push(d.qm_search_code), + |off, e| errs.push((off, e)), + ); + assert_eq!(codes, vec!["A", "A"]); + assert_eq!( + errs.iter().map(|(o, _)| *o).collect::>(), + expected_err_offsets + ); + assert!(matches!( + errs[0].1, + BsonQmActionError::InvalidNumber { + field: FIELD_DIVIDEND_CASH, + .. + } + )); + assert!(matches!( + errs[2].1, + BsonQmActionError::TruncatedDocument { + offset, + declared_len: Some(_), + .. + } if offset == tail_start + )); + assert_eq!(stats.docs_in, 5); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + + // i32::MAX declared length after a good split doc terminates without panicking. + let mut buf = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec(); + let bad_at = buf.len(); + buf.extend_from_slice(&i32::MAX.to_le_bytes()); + buf.extend_from_slice(&[0u8; 8]); + let mut errs = Vec::new(); + let stats = decode_qm_split_buffer(&buf, |_| {}, |off, e| errs.push((off, e))); + assert_eq!(stats.docs_in, 2); + assert_eq!(stats.decoded, 1); + assert_eq!(errs.len(), 1); + assert_eq!(errs[0].0, bad_at); + assert!(matches!( + errs[0].1, + BsonQmActionError::TruncatedDocument { .. } + )); + + // Single-doc decoder: trailing bytes are rejected as a length mismatch, not silently ignored. + let mut trailing = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec(); + trailing.push(0); + assert!(matches!( + decode_qm_split_bytes(&trailing).unwrap_err(), + BsonQmActionError::CorruptDocumentLength { .. } + )); +} + +/// `std`-only SplitMix64 so the fuzz corpus is fixed across runs. +struct SplitMix64(u64); + +impl SplitMix64 { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +fn mutate(rng: &mut SplitMix64, base: &[u8]) -> Vec { + let mut buf = base.to_vec(); + let flips = 1 + (rng.next() % 4) as usize; + for _ in 0..flips { + let pos = (rng.next() as usize) % buf.len(); + buf[pos] = rng.next() as u8; + } + if rng.next() % 4 == 0 { + let cut = (rng.next() as usize) % buf.len(); + buf.truncate(cut); + } + buf +} + +fn framed_slices(buf: &[u8]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut iter = iter_raw_bson_docs(buf); + while let Some(item) = iter.next_with_offset() { + if let Ok((off, doc)) = item { + out.push((off, doc.as_bytes().len())); + } + } + out +} + +#[test] +fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles_for_both_collections() { + let mut split_base = Vec::new(); + let mut div_base = Vec::new(); + for i in 0..8 { + let code = format!("Q{i}:CA"); + split_base.extend_from_slice(split_doc(&code, "2024-06-07", 1.0 + i as f64).as_bytes()); + div_base + .extend_from_slice(dividend_doc(&code, "2024-06-07", 0.1 * i as f64, "CAD").as_bytes()); + } + + let split_key = |s: &RawQmSplit<'_>| { + ( + s.qm_search_code.to_string(), + s.ex_date, + s.ratio.to_bits(), + s.declared_date, + ) + }; + let div_key = |d: &RawQmDividend<'_>| { + ( + d.qm_search_code.to_string(), + d.ex_date, + d.cash.to_bits(), + d.currency.to_string(), + d.declared_date, + ) + }; + + let mut rng = SplitMix64(0x0B50_7E57_0A11_0107); + for _ in 0..2_000 { + let buf = mutate(&mut rng, &split_base); + let mut rows = Vec::new(); + let stats = decode_qm_split_buffer(&buf, |s| rows.push(s), |_, _| {}); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(stats.decoded, rows.len()); + assert_eq!( + stats.split_noop_ratio_one, + rows.iter().filter(|s| s.ratio == 1.0).count() + ); + let expected: Vec<_> = framed_slices(&buf) + .into_iter() + .filter_map(|(o, l)| decode_qm_split_bytes(&buf[o..o + l]).ok()) + .collect(); + assert_eq!( + rows.iter().map(split_key).collect::>(), + expected.iter().map(split_key).collect::>() + ); + for s in &rows { + assert!(s.ratio.is_finite() && s.ratio > 0.0); + assert!(!s.qm_search_code.trim().is_empty()); + } + + let buf = mutate(&mut rng, &div_base); + let mut rows = Vec::new(); + let stats = decode_qm_dividend_buffer(&buf, |d| rows.push(d), |_, _| {}); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(stats.decoded, rows.len()); + assert_eq!(stats.split_noop_ratio_one, 0); + let expected: Vec<_> = framed_slices(&buf) + .into_iter() + .filter_map(|(o, l)| decode_qm_dividend_bytes(&buf[o..o + l]).ok()) + .collect(); + assert_eq!( + rows.iter().map(div_key).collect::>(), + expected.iter().map(div_key).collect::>() + ); + for d in &rows { + assert!(d.cash.is_finite() && d.cash >= 0.0 && !d.cash.is_sign_negative()); + assert!(!d.currency.trim().is_empty()); + } + } +} + +#[test] +fn benchmark_corpus_mostly_decodes_so_it_times_the_happy_path() { + let report = run_bson_qm_actions_benchmark(20_000); + let s = report.split_stats; + let d = report.dividend_stats; + assert_eq!(s.docs_in + d.docs_in, 20_000); + // Injected errors are ~0.5% per collection; allow generous headroom but fail if a renamed + // field constant makes the corpus reject en masse. + assert!( + s.rejected_total() * 50 < s.docs_in, + "split rejections too high: {s:?}" + ); + assert!( + d.rejected_total() * 50 < d.docs_in, + "dividend rejections too high: {d:?}" + ); + assert_eq!(s.rejected_corrupt_document + d.rejected_corrupt_document, 0); +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn stable_output(out: &Output) -> String { + let text = String::from_utf8_lossy(&out.stdout); + let checksum = text + .split_whitespace() + .find(|t| t.starts_with("checksum=0x")) + .unwrap_or_else(|| panic!("no checksum in output: {text}")); + let stats: Vec<&str> = text + .lines() + .map(str::trim_start) + .filter(|l| { + l.starts_with("input:") || l.starts_with("splits:") || l.starts_with("dividends:") + }) + .collect(); + assert_eq!(stats.len(), 3, "missing stats lines: {text}"); + format!("{checksum} {}", stats.join(" | ")) +} + +#[test] +fn bench_binary_prints_identical_checksum_and_stats_across_runs() { + let a = run_bin(&["bench-bson-qm-actions", "5000"]); + let b = run_bin(&["bench-bson-qm-actions", "5000"]); + assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); + + let text = String::from_utf8_lossy(&a.stdout); + assert!(text.contains("rows=5000"), "{text}"); + for needle in [ + "elapsed=", + "docs/s", + "MB/s", + "noop_ratio_one=", + "checksum=0x", + ] { + assert!(text.contains(needle), "missing {needle}: {text}"); + } + assert_eq!(stable_output(&a), stable_output(&b)); +} + +#[test] +fn bench_binary_rejects_invalid_row_counts_and_is_listed_in_usage() { + for args in [ + &["bench-bson-qm-actions", "0"][..], + &["bench-bson-qm-actions", "-5"][..], + &["bench-bson-qm-actions", "abc"][..], + &["bench-bson-qm-actions", "10", "20"][..], + ] { + let out = run_bin(args); + assert_eq!(out.status.code(), Some(1), "{args:?}"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("error:"), "{args:?}: {err}"); + assert!(out.stdout.is_empty(), "{args:?} wrote to stdout"); + } + + let out = run_bin(&["--help"]); + assert!(out.status.success()); + assert!(String::from_utf8_lossy(&out.stdout).contains("bench-bson-qm-actions")); +} diff --git a/tools/curate-etl/tests/bson_stream_qa_contract.rs b/tools/curate-etl/tests/bson_stream_qa_contract.rs new file mode 100644 index 00000000..63532041 --- /dev/null +++ b/tools/curate-etl/tests/bson_stream_qa_contract.rs @@ -0,0 +1,273 @@ +//! QA contract tests for the public `bson_stream` API (T-109 / M1.2y). +//! +//! Covers gaps left by `src/bson_stream_tests.rs`, using only the public crate API: +//! - seeded byte-mutation fuzz: for every mutated `eodPrices` stream the streamed decode never +//! panics, yields exactly the buffer decoder's rows and per-document errors in order, and a +//! buffer framing error maps to a stream `Err` at the same absolute offset; +//! - `RawBsonChunkReader::new` (default options) frames a multi-document stream end to end; +//! - `decode_*_chunks` resumed on a reader that already failed returns the sticky error at once; +//! - `BsonStreamError` `Display` names the offset and `source()` exposes the original I/O error; +//! - `bench-bson-stream` binary: completes on a small row count with a ratio and peak buffer +//! line, identical checksum across two runs, invalid args exit non-zero. + +use std::error::Error as _; +use std::io::{self, Cursor, Read}; +use std::process::{Command, Output}; + +use bson::raw::{cstr, RawDocumentBuf}; +use curate_etl::{ + decode_eod_price_buffer, decode_eod_price_chunks, decode_eod_price_stream, + decode_qm_split_chunks, BsonEodPriceError, BsonStreamError, BsonStreamOptions, + RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, +}; + +struct SplitMix64(u64); + +impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } +} + +/// Reader returning seeded pseudo-random short reads of 1..=97 bytes. +struct JitterReader<'a> { + data: &'a [u8], + pos: usize, + rng: SplitMix64, +} + +impl Read for JitterReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let remaining = self.data.len() - self.pos; + if remaining == 0 { + return Ok(0); + } + let step = (self.rng.next_u64() % 97) as usize + 1; + let take = remaining.min(step).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +/// Reader that yields its data once and then fails every subsequent read. +struct FailAfterData { + data: Vec, + pos: usize, + reads_after_fail: usize, +} + +impl Read for FailAfterData { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos == self.data.len() { + self.reads_after_fail += 1; + return Err(io::Error::new(io::ErrorKind::ConnectionReset, "cursor dropped")); + } + let take = (self.data.len() - self.pos).min(buf.len()); + buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); + self.pos += take; + Ok(take) + } +} + +fn eod_doc(code: &str, day: u32, close: f64) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("date"), format!("2024-06-{day:02}")); + doc.append(cstr!("open"), close - 0.5); + doc.append(cstr!("high"), close + 1.0); + doc.append(cstr!("low"), close - 1.0); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), 1_000_i64 + day as i64); + doc.append(cstr!("exchange"), "TSX"); + doc.into_bytes() +} + +fn eod_fixture(count: usize) -> Vec { + let mut out = Vec::new(); + for i in 0..count { + out.extend_from_slice(&eod_doc(&format!("Q{i:03}.TO"), 1 + (i % 28) as u32, 10.0 + i as f64)); + } + out +} + +type Row = (String, i32, u64, u64); + +fn buffer_decode(bytes: &[u8]) -> (Vec, Vec<(u64, String)>) { + let mut rows = Vec::new(); + let mut errs = Vec::new(); + decode_eod_price_buffer( + bytes, + |b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())), + |off, e| errs.push((off as u64, format!("{e:?}"))), + ); + (rows, errs) +} + +fn is_framing_error(debug: &str) -> bool { + debug.starts_with("CorruptDocumentLength") || debug.starts_with("TruncatedDocument") +} + +#[test] +fn seeded_mutation_fuzz_stream_matches_buffer_rows_errors_and_framing_offset() { + let clean = eod_fixture(24); + let mut rng = SplitMix64(0x5EED_B50E); + let mut framing_cases = 0usize; + let mut ok_cases = 0usize; + + for case in 0..400u64 { + let mut bytes = clean.clone(); + let flips = 1 + (rng.next_u64() % 4) as usize; + for _ in 0..flips { + let idx = (rng.next_u64() as usize) % bytes.len(); + bytes[idx] = rng.next_u64() as u8; + } + if rng.next_u64() % 5 == 0 { + let cut = (rng.next_u64() as usize) % bytes.len(); + bytes.truncate(cut); + } + + let (exp_rows, mut exp_errs) = buffer_decode(&bytes); + let exp_framing = match exp_errs.last() { + Some((off, dbg)) if is_framing_error(dbg) => { + let off = *off; + exp_errs.pop(); + Some(off) + } + _ => None, + }; + + let cap = [1usize, 4, 37, 256, 4096][(case % 5) as usize]; + let mut rows = Vec::new(); + let mut errs = Vec::new(); + let result = decode_eod_price_stream( + JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) }, + BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 }, + |b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())), + |off, e: BsonEodPriceError| errs.push((off, format!("{e:?}"))), + ); + + assert_eq!(rows, exp_rows, "case={case} cap={cap}: rows diverge"); + assert_eq!(errs, exp_errs, "case={case} cap={cap}: per-doc errors diverge"); + match (exp_framing, result) { + (None, Ok(stats)) => { + ok_cases += 1; + assert_eq!(stats.decoded, exp_rows.len(), "case={case}"); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in, "case={case}"); + } + (Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. })) + | (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => { + framing_cases += 1; + assert_eq!(offset, off, "case={case} cap={cap}: framing offset"); + } + (exp, got) => panic!("case={case} cap={cap}: expected framing={exp:?}, got {got:?}"), + } + } + // The sweep must exercise both outcomes, or it proves nothing. + assert!(framing_cases >= 20, "framing_cases={framing_cases}"); + assert!(ok_cases >= 20, "ok_cases={ok_cases}"); +} + +#[test] +fn default_reader_frames_whole_stream_with_default_capacity() { + let input = eod_fixture(50); + let mut reader = RawBsonChunkReader::new(JitterReader { data: &input, pos: 0, rng: SplitMix64(7) }); + let mut joined = Vec::new(); + while let Some(chunk) = reader.next_chunk().expect("valid stream") { + assert_eq!(chunk.start_offset, joined.len() as u64); + joined.extend_from_slice(chunk.bytes); + } + assert_eq!(joined, input); + assert_eq!(reader.docs_framed(), 50); + assert_eq!(reader.bytes_read(), input.len() as u64); + assert_eq!(reader.buffer_capacity(), DEFAULT_CHUNK_CAPACITY_BYTES); +} + +#[test] +fn chunk_helpers_on_failed_reader_return_sticky_error_without_rereading() { + let input = eod_fixture(3); + let len = input.len() as u64; + let mut reader = RawBsonChunkReader::with_options( + FailAfterData { data: input, pos: 0, reads_after_fail: 0 }, + BsonStreamOptions { chunk_capacity_bytes: 64, max_doc_bytes: 4096 }, + ) + .unwrap(); + + let mut bars = 0usize; + let err = decode_eod_price_chunks(&mut reader, |_| bars += 1, |_, _| panic!("no per-doc errors")) + .expect_err("I/O failure must surface"); + assert_eq!(bars, 3, "all complete docs delivered before the I/O error"); + let BsonStreamError::Io { offset, ref source } = err else { panic!("expected Io, got {err:?}") }; + assert_eq!(offset, len); + assert_eq!(source.kind(), io::ErrorKind::ConnectionReset); + + // A different helper resumed on the same failed reader must fail immediately. + let again = decode_qm_split_chunks(&mut reader, |_| panic!("no rows"), |_, _| panic!("no errors")) + .expect_err("sticky error"); + assert!(matches!(again, BsonStreamError::Io { offset, .. } if offset == len)); + assert_eq!(reader.into_inner().reads_after_fail, 1, "source read exactly once after data"); +} + +#[test] +fn error_display_names_offset_and_io_source_is_exposed() { + let mut bytes = eod_doc("A.TO", 3, 5.0); + let first_len = bytes.len(); + bytes.extend_from_slice(&2_i32.to_le_bytes()); + let err = decode_eod_price_stream(Cursor::new(bytes), BsonStreamOptions::default(), |_| {}, |_, _| {}) + .expect_err("corrupt length"); + assert!(err.source().is_none()); + let text = err.to_string(); + assert!(text.contains(&format!("offset {first_len}")), "{text}"); + assert!(text.contains("length 2"), "{text}"); + + let io_err = decode_eod_price_stream( + FailAfterData { data: Vec::new(), pos: 0, reads_after_fail: 0 }, + BsonStreamOptions::default(), + |_| {}, + |_, _| {}, + ) + .expect_err("io"); + let src = io_err.source().expect("Io exposes source"); + assert!(src.to_string().contains("cursor dropped"), "{src}"); + assert!(io_err.to_string().contains("offset 0"), "{io_err}"); + + assert!(BsonStreamError::InvalidChunkCapacity.to_string().contains("chunk_capacity_bytes")); + assert!(BsonStreamError::InvalidMaxDocBytes.to_string().contains("max_doc_bytes")); +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn checksum_of(out: &Output) -> String { + let text = String::from_utf8_lossy(&out.stdout); + text.split_whitespace() + .find(|t| t.starts_with("checksum=0x")) + .unwrap_or_else(|| panic!("no checksum in output: {text}")) + .to_owned() +} + +#[test] +fn bench_bson_stream_binary_is_deterministic_and_rejects_bad_args() { + let a = run_bin(&["bench-bson-stream", "5000"]); + let b = run_bin(&["bench-bson-stream", "5000"]); + assert!(a.status.success(), "stderr: {}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success()); + assert_eq!(checksum_of(&a), checksum_of(&b)); + let text = String::from_utf8_lossy(&a.stdout).to_lowercase(); + assert!(text.contains("rows=5000"), "{text}"); + assert!(text.contains("ratio"), "{text}"); + assert!(text.contains("peak_buffer_capacity"), "{text}"); + + for bad in [&["bench-bson-stream", "abc"][..], &["bench-bson-stream", "1", "2"][..]] { + let out = run_bin(bad); + assert!(!out.status.success(), "args {bad:?} must fail"); + } +} diff --git a/tools/curate-etl/tests/curate_adj_qa_contract.rs b/tools/curate-etl/tests/curate_adj_qa_contract.rs new file mode 100644 index 00000000..de5164d4 --- /dev/null +++ b/tools/curate-etl/tests/curate_adj_qa_contract.rs @@ -0,0 +1,418 @@ +//! QA contract tests for the public `adj_factors` curation stage (T-106 / M1.2v). +//! +//! Complements the in-crate `curate_adj_tests.rs` with checks against independent references +//! built only from the public API: +//! - seeded differential test: per-bar split factors across ticker renames, ticker reuse and +//! unmapped gaps equal a naive per-listing product of later split ratios; +//! - fenced publish → separate reopen equals the naive reference over only the events whose +//! conservative `16:00 ET` known_at is `<= as_of`, and every reopened row honours the fence; +//! - re-publishing a smaller fenced snapshot over a larger retrospective one leaves exactly one +//! `part.parquet` whose footer carries the `stock_bot.adj_factors.*` keys and contract schema; +//! - `bench-curate-adj` binary run: checksum/bytes/rows pinned to the README values, temp dir +//! cleaned. + +use std::collections::{BTreeMap, HashSet}; +use std::fs::{self, File}; +use std::path::PathBuf; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + adj_factors_for_bar, adj_factors_parquet_schema, curate_adj_factors, + curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, et_session_close_utc_micros, + read_adj_factors_dataset, read_adj_factors_dataset_as_of, ymd_to_epoch_days, + AdjFactorsWriteOptions, AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError, + DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent, +}; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-adj-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +struct SplitMix64(u64); + +impl SplitMix64 { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn map_row(key: &str, from: i32, to: Option, listing_id: i32) -> ProviderMappingRow { + ProviderMappingRow { + source: "qm".to_string(), + source_id: key.to_string(), + valid_from: from, + valid_to: to, + listing_id, + } +} + +/// Exactly representable ratios so the naive product is order-independent. +const RATIOS: [f64; 6] = [2.0, 0.5, 4.0, 0.25, 3.0, 1.0]; + +struct Fixture { + mapping: ProviderMappingTable, + splits: Vec<(String, SplitEvent)>, + /// Naive reference: listing_id -> (ex_date -> ratio) for every mapped split (incl. 1:1). + reference: BTreeMap>, + min: i32, + max: i32, +} + +/// Layout per listing group `g` (deterministic): +/// - listing `3g+1`: single key `S{g}` for the whole span; +/// - listing `3g+2`: key `OLD{g}` until 2012-12-31, renamed to `NEW{g}` from 2013-01-01; +/// - key `RE{g}` maps to listing `3g+3` until 2015-06-30, unmapped through 2015, then to listing +/// `100_000 + g` from 2016-01-01 (ticker reuse with a gap). +fn seeded_fixture(seed: u64, groups: i32, events: usize) -> Fixture { + let min = day(2000, 1, 1); + let max = day(2025, 12, 31); + let rename = day(2012, 12, 31); + let reuse_old_end = day(2015, 6, 30); + let reuse_new_start = day(2016, 1, 1); + + let mut rows = Vec::new(); + for g in 0..groups { + rows.push(map_row(&format!("S{g}"), min, None, 3 * g + 1)); + rows.push(map_row(&format!("OLD{g}"), min, Some(rename), 3 * g + 2)); + rows.push(map_row(&format!("NEW{g}"), rename + 1, None, 3 * g + 2)); + rows.push(map_row( + &format!("RE{g}"), + min, + Some(reuse_old_end), + 3 * g + 3, + )); + rows.push(map_row( + &format!("RE{g}"), + reuse_new_start, + None, + 100_000 + g, + )); + } + let mapping = ProviderMappingTable::from_rows(rows).expect("valid mapping"); + + let mut rng = SplitMix64(seed); + let mut seen: HashSet<(String, i32)> = HashSet::new(); + let mut splits = Vec::new(); + let mut reference: BTreeMap> = BTreeMap::new(); + while splits.len() < events { + let g = rng.below(groups as u64) as i32; + let ex_date = min + rng.below((max - min + 1) as u64) as i32; + let (key, listing) = match rng.below(4) { + 0 => (format!("S{g}"), Some(3 * g + 1)), + 1 if ex_date <= rename => (format!("OLD{g}"), Some(3 * g + 2)), + 1 => (format!("NEW{g}"), Some(3 * g + 2)), + 2 if ex_date <= reuse_old_end => (format!("RE{g}"), Some(3 * g + 3)), + 2 if ex_date < reuse_new_start => (format!("RE{g}"), None), + 2 => (format!("RE{g}"), Some(100_000 + g)), + _ => (format!("UNMAPPED{g}"), None), + }; + // One event per (key, ex_date): same-key same-day multiplication is the builder's own + // contract and is covered in-crate. + if !seen.insert((key.clone(), ex_date)) { + continue; + } + let ratio = RATIOS[rng.below(RATIOS.len() as u64) as usize]; + if let Some(listing_id) = listing { + reference + .entry(listing_id) + .or_default() + .insert(ex_date, ratio); + } + splits.push((key, SplitEvent { ex_date, ratio })); + } + Fixture { + mapping, + splits, + reference, + min, + max, + } +} + +/// Product of every reference split ratio with `ex_date > bar_date` for `listing_id`. +fn naive_factor( + reference: &BTreeMap>, + listing_id: i32, + bar_date: i32, + admit: impl Fn(i32) -> bool, +) -> f64 { + reference.get(&listing_id).map_or(1.0, |events| { + events + .range(bar_date + 1..) + .filter(|(ex, _)| admit(**ex)) + .map(|(_, r)| *r) + .product() + }) +} + +const NO_DIVIDENDS: [(String, DividendEvent); 0] = []; + +#[test] +fn seeded_split_factors_match_naive_per_listing_reference_across_rename_reuse_and_gaps() { + let fx = seeded_fixture(0xAD0A_115E_ED00, 40, 3_000); + let out = + curate_adj_factors(&fx.mapping, "qm", fx.splits.clone(), NO_DIVIDENDS).expect("curate"); + + assert_eq!(out.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot); + let mapped: usize = fx.reference.values().map(BTreeMap::len).sum(); + assert_eq!(out.stats.splits_in, fx.splits.len()); + assert_eq!( + out.stats.splits_dropped_unmapped, + fx.splits.len() - mapped, + "unmapped count must equal events with no covering range" + ); + assert_eq!(out.stats.splits_collision_collapsed, 0); + assert_eq!(out.stats.builder.split_events_in, mapped); + let noops = fx + .reference + .values() + .flat_map(BTreeMap::values) + .filter(|r| **r == 1.0) + .count(); + assert_eq!(out.stats.builder.split_noops_dropped, noops); + assert_eq!(out.stats.rows_out, mapped - noops); + assert!(out.stats.splits_dropped_unmapped > 0 && noops > 0); + + let mut rng = SplitMix64(0x0B5E_55ED); + let listings: Vec = fx.reference.keys().copied().collect(); + for _ in 0..5_000 { + let listing_id = listings[rng.below(listings.len() as u64) as usize]; + let bar = fx.min - 5 + rng.below((fx.max - fx.min + 10) as u64) as i32; + let expected = naive_factor(&fx.reference, listing_id, bar, |_| true); + let (split, _total) = adj_factors_for_bar(&out.rows, listing_id, bar); + assert_eq!( + split.to_bits(), + expected.to_bits(), + "listing {listing_id} bar {bar}: got {split}, expected {expected}" + ); + } + // Unknown listing never picks up another listing's chain. + assert_eq!(adj_factors_for_bar(&out.rows, 99_999, fx.min), (1.0, 1.0)); +} + +#[test] +fn fenced_publish_then_separate_reopen_matches_naive_filtered_reference() { + let fx = seeded_fixture(0xFE11_CE00, 25, 2_000); + let tmp = TempDir::new("fenced-reopen"); + // As of 2018-03-14 12:00 UTC: an ex-date of 2018-03-14 (close 20:00 UTC) is still unknown. + let as_of = et_session_close_utc_micros(day(2018, 3, 14)).unwrap() - 8 * 3_600_000_000; + let fence = AdjPointInTimeFence::as_of(as_of); + + let report = curate_and_write_adj_factors_as_of( + &tmp.0, + &fx.mapping, + "qm", + fx.splits.clone(), + NO_DIVIDENDS, + fence, + AdjFactorsWriteOptions { + row_group_rows: 11, + ..Default::default() + }, + ) + .expect("fenced publish"); + assert_eq!( + report.snapshot_kind, + AdjSnapshotKind::PointInTimeFenced(fence) + ); + assert!(report.curate_stats.splits_dropped_fenced > 0); + + // Separate read step: only the published artifact is consulted. + let snap = read_adj_factors_dataset_as_of(&tmp.0, fence).expect("reopen"); + assert_eq!( + snap.snapshot_kind, + AdjSnapshotKind::PointInTimeFenced(fence) + ); + assert_eq!(snap.rows.len(), report.write_stats.rows_written); + for row in &snap.rows { + assert!(row.known_at_micros <= as_of, "row beyond as_of: {row:?}"); + } + for w in snap.rows.windows(2) { + assert!((w[0].listing_id, w[0].ex_date) < (w[1].listing_id, w[1].ex_date)); + } + + let admitted = |ex: i32| et_session_close_utc_micros(ex).unwrap() <= as_of; + let mut rng = SplitMix64(0xA5_0F); + let listings: Vec = fx.reference.keys().copied().collect(); + for _ in 0..3_000 { + let listing_id = listings[rng.below(listings.len() as u64) as usize]; + let bar = fx.min + rng.below((day(2018, 3, 14) - fx.min) as u64) as i32; + let expected = naive_factor(&fx.reference, listing_id, bar, admitted); + let (split, _) = snap.factors_for_bar(listing_id, bar); + assert_eq!( + split.to_bits(), + expected.to_bits(), + "listing {listing_id} bar {bar} as_of {as_of}" + ); + } + + // A neighbouring fence one microsecond later is a different artifact and must be refused. + let other = AdjPointInTimeFence::as_of(as_of + 1); + assert!(matches!( + read_adj_factors_dataset_as_of(&tmp.0, other), + Err(CurateAdjReadError::IncompatibleFence { .. }) + )); +} + +#[test] +fn smaller_fenced_republish_supersedes_larger_retrospective_snapshot_in_one_file() { + let fx = seeded_fixture(0x5_0BE5, 30, 2_500); + let tmp = TempDir::new("republish"); + + let retro = curate_and_write_adj_factors( + &tmp.0, + &fx.mapping, + "qm", + fx.splits.clone(), + NO_DIVIDENDS, + AdjFactorsWriteOptions::default(), + ) + .expect("retrospective publish"); + let fence = AdjPointInTimeFence::as_of_with_vault_cutoff( + et_session_close_utc_micros(day(2024, 6, 28)).unwrap(), + et_session_close_utc_micros(day(2005, 1, 3)).unwrap(), + ); + assert!(matches!( + read_adj_factors_dataset_as_of(&tmp.0, fence), + Err(CurateAdjReadError::RetrospectiveSnapshotRejected { .. }) + )); + + let fenced = curate_and_write_adj_factors_as_of( + &tmp.0, + &fx.mapping, + "qm", + fx.splits.clone(), + NO_DIVIDENDS, + fence, + AdjFactorsWriteOptions::default(), + ) + .expect("fenced publish"); + assert!(fenced.write_stats.rows_written < retro.write_stats.rows_written); + + let names: Vec = fs::read_dir(tmp.0.join("adj_factors")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, vec!["part.parquet".to_string()]); + + // Vault cutoff wins over the later as_of: every row is strictly before the vault boundary. + let snap = read_adj_factors_dataset(&tmp.0).expect("reopen"); + assert_eq!( + snap.snapshot_kind, + AdjSnapshotKind::PointInTimeFenced(fence) + ); + assert_eq!(snap.rows.len(), fenced.write_stats.rows_written); + let vault = fence.vault_cutoff_micros.unwrap(); + assert!(snap.rows.iter().all(|r| r.known_at_micros < vault)); + + // A generic Parquet reader sees the contract schema and the bound footer keys. + let path = tmp.0.join("adj_factors").join("part.parquet"); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let file_meta = reader.metadata().file_metadata(); + assert_eq!( + file_meta.schema(), + adj_factors_parquet_schema().unwrap().as_ref() + ); + assert_eq!(file_meta.num_rows() as usize, snap.rows.len()); + let kv: BTreeMap> = file_meta + .key_value_metadata() + .expect("footer key_value_metadata") + .iter() + .map(|kv| (kv.key.clone(), kv.value.clone())) + .filter(|(k, _)| k.starts_with("stock_bot.adj_factors.")) + .collect(); + let get = |k: &str| kv[&format!("stock_bot.adj_factors.{k}")].as_deref(); + assert_eq!(kv.len(), 6, "{kv:?}"); + assert_eq!(get("format_version"), Some("1")); + assert_eq!(get("snapshot_kind"), Some("point_in_time_fenced")); + assert_eq!( + get("as_of_micros"), + Some(fence.as_of_micros.unwrap().to_string().as_str()) + ); + assert_eq!(get("vault_cutoff_micros"), Some(vault.to_string().as_str())); + assert_eq!( + get("rows_written"), + Some(snap.rows.len().to_string().as_str()) + ); +} + +fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { + text.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(|t| &t[prefix.len()..]) +} + +#[test] +fn bench_curate_adj_default_run_matches_readme_values_and_cleans_temp_dir() { + let tmp = TempDir::new("bench-tmpdir"); + let output = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .arg("bench-curate-adj") + .env("TMPDIR", &tmp.0) + .output() + .expect("run curate-etl"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + + // Values recorded in tools/curate-etl/README.md (`bench-curate-adj`, default 1,000,000). + assert_eq!(field(&stdout, "events="), Some("1000000"), "{stdout}"); + assert_eq!(field(&stdout, "splits="), Some("40221"), "{stdout}"); + assert_eq!(field(&stdout, "dividends="), Some("959779"), "{stdout}"); + assert_eq!( + field(&stdout, "checksum="), + Some("0x024ec73a1afe7e6b"), + "{stdout}" + ); + assert_eq!(field(&stdout, "bytes="), Some("11872037"), "{stdout}"); + assert_eq!( + field(&stdout, "read_back_rows="), + Some("946414"), + "{stdout}" + ); + assert_eq!(field(&stdout, "rows_out="), Some("946414"), "{stdout}"); + assert_eq!(field(&stdout, "coll_collapsed="), Some("4930"), "{stdout}"); + + let leftovers: Vec<_> = fs::read_dir(&tmp.0) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert!( + leftovers.is_empty(), + "bench left temp entries: {leftovers:?}" + ); +}