T-109: M1.2y — tools/curate-etl: bounded-memory streaming reader for concatenated raw BSON (impl Read → whole-document chunks → existing eodPrices / qmSplits / qmDividends decoders) with tests and local benchmark (no new crates, no MongoDB connection)

This commit is contained in:
Studio 2026-11-28 23:48:43 -05:00
parent 7ea03c95ac
commit 5131c2525f
9 changed files with 2196 additions and 33 deletions

View file

@ -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<R: std::io::Read>` (`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<u8>` 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<BsonEodDecodeStats, BsonStreamError>`
- `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
- `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
- 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:

View file

@ -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<u8>` 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<u8> {
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<u8>` 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<usize> {
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<BsonStreamBenchReport, BsonStreamError> {
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);

View file

@ -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]

View file

@ -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]

View file

@ -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<i32>,
},
/// 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<i32>,
},
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<R: io::Read> {
reader: R,
options: BsonStreamOptions,
buf: Vec<u8>,
filled: usize,
consumed: usize,
buf_start_offset: u64,
bytes_read: u64,
docs_framed: u64,
eof_reached: bool,
pending_io_err: Option<io::Error>,
terminal: TerminalState,
}
impl<R: io::Read> RawBsonChunkReader<R> {
/// 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<Self, BsonStreamError> {
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<Option<RawBsonChunk<'_>>, 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<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_bar: F,
mut on_error: E,
) -> Result<BsonEodDecodeStats, BsonStreamError>
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<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_bar: F,
on_error: E,
) -> Result<BsonEodDecodeStats, BsonStreamError>
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<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_split: F,
mut on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
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<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_split: F,
on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
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<R, F, E>(
reader: &mut RawBsonChunkReader<R>,
mut on_dividend: F,
mut on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
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<R, F, E>(
reader: R,
options: BsonStreamOptions,
on_dividend: F,
on_error: E,
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
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;

File diff suppressed because it is too large Load diff

View file

@ -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<CliAction, String> {
["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::<usize>() {
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::<usize>() {
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"));

View file

@ -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,

View file

@ -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,