diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index d4acfcaa..9d31195d 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`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, and the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`. +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 @@ -707,6 +707,38 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59 - 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: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 334ae66a..133309de 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -20,6 +20,9 @@ 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, @@ -83,6 +86,7 @@ pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000; 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; @@ -3620,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"]; @@ -3755,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; @@ -3797,6 +3807,184 @@ 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 { @@ -6830,6 +7018,64 @@ 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); diff --git a/tools/curate-etl/src/bson_eod_prices.rs b/tools/curate-etl/src/bson_eod_prices.rs index b80c77ec..1303f4c9 100644 --- a/tools/curate-etl/src/bson_eod_prices.rs +++ b/tools/curate-etl/src/bson_eod_prices.rs @@ -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] diff --git a/tools/curate-etl/src/bson_qm_actions.rs b/tools/curate-etl/src/bson_qm_actions.rs index 45905af7..4efb6aff 100644 --- a/tools/curate-etl/src/bson_qm_actions.rs +++ b/tools/curate-etl/src/bson_qm_actions.rs @@ -393,6 +393,27 @@ impl BsonQmActionDecodeStats { | 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] diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs new file mode 100644 index 00000000..17d2831b --- /dev/null +++ b/tools/curate-etl/src/bson_stream.rs @@ -0,0 +1,663 @@ +//! 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. 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 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(); + Self { + reader, + options, + buf: vec![0u8; options.chunk_capacity_bytes], + 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()?; + Ok(Self { + reader, + options, + buf: vec![0u8; options.chunk_capacity_bytes], + 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 first_doc_len_checked = false; + loop { + // Inspect the leading 4-byte length prefix as soon as it is buffered so an already- + // buffered corrupt length fails immediately without extra I/O, and oversized single + // documents grow the buffer before filling. + if !first_doc_len_checked && self.filled >= 4 { + let declared_len = read_i32_le(&self.buf[0..4]); + if declared_len < MIN_BSON_DOC_BYTES as i32 + || (declared_len as usize) > self.options.max_doc_bytes + { + 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()); + } + let doc_len = declared_len as usize; + if doc_len > self.buf.len() { + self.grow_buf_exact(doc_len); + } + first_doc_len_checked = true; + } + + if 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 `first_doc_len <= self.buf.len() == self.filled`, 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; + } + } + } + + // Frame as many complete length-prefixed documents as are buffered. + let mut chunk_end = 0usize; + let mut chunk_docs = 0u64; + 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 + { + // Yield any complete preceding documents first; the next call will compact this + // corrupt header to index 0 and surface `CorruptDocumentLength`. + break; + } + let doc_len = declared_len as usize; + if doc_len > self.filled - chunk_end { + break; + } + chunk_end += doc_len; + chunk_docs += 1; + } + + 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..15cf22c1 --- /dev/null +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -0,0 +1,1105 @@ +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); +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 23968085..99ada5dd 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -6,10 +6,11 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS, - DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_ADJ_BENCH_EVENTS, - DEFAULT_CURATE_BARS_BENCH_ROWS, 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_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS, + 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, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, @@ -36,6 +37,7 @@ pub enum CliAction { BenchParquetCorporateActions(usize), BenchBsonEodPrices(usize), BenchBsonQmActions(usize), + BenchBsonStream(usize), BenchCurateBars(usize), BenchCurateShorts(usize), BenchCurateEvents(usize), @@ -67,6 +69,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {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\ @@ -97,6 +100,7 @@ pub fn format_usage_stderr(name: &str) -> String { {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\ @@ -278,6 +282,16 @@ pub fn parse_args(args: &[String]) -> Result { ["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)), @@ -633,6 +647,22 @@ mod tests { 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"); @@ -652,6 +682,7 @@ mod tests { 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")); @@ -675,6 +706,7 @@ mod tests { 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")); diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 434f595c..93561c7b 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -5,6 +5,7 @@ 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; @@ -39,6 +40,12 @@ pub use bson_qm_actions::{ 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, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 0b894b7b..878670a1 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_bson_qm_actions_benchmark, run_corporate_actions_benchmark, run_curate_adj_benchmark, - run_curate_bars_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_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}; @@ -544,6 +545,42 @@ fn main() -> ExitCode { ); 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,