diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index f397feb3..d9217c92 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -6,5 +6,6 @@ authors.workspace = true license.workspace = true [dependencies] +bson = { version = "=3.1.0", default-features = false } parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 848ed021..83387f91 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (single direct dependency: `parquet` 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`, and the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`. +Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`. ## Scope & Sign Conventions @@ -433,6 +433,28 @@ Rules: - Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000` - Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x` +## `eodPrices` Raw BSON Decoder (`M1.2o`) + +`decode_eod_price_doc`, `decode_eod_price_bytes`, `iter_raw_bson_docs`, and `decode_eod_price_buffer` (`src/bson_eod_prices.rs`) decode raw MongoDB `eodPrices` BSON documents in a single forward pass over `RawDocument::iter_elements()` without allocating a `String` or `bson::Document` per row. + +1. **Pinned dependency & driver compatibility:** + - Adds `bson = { version = "=3.1.0", default-features = false }` (MSRV `1.81+`, tested against workspace `rustc 1.88.0`, no `serde` derive). + - Paired with the official `mongodb` `3.x` Rust driver using `features = ["bson-3"]` so the upcoming MongoDB cursor task reuses the same `bson` 3.x crate without pulling in a duplicate `bson` major version. +2. **Empirical field contract & cited sources:** + - Grounded in `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56`, `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157`, `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18`, and `design/DATA-CONTRACTS.md` §1 (line 13). + - `eodSearchCode`: BSON UTF-8 `String` (borrowed verbatim as `&str`; empty or whitespace-only is rejected). + - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (converted to UTC epoch days via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps map accurately). + - `open`, `high`, `low`, `close`, `volume`: every BSON numeric representation MongoDB can store for a JS number (`Double`, `Int32`, `Int64`); must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). Per `design/DATA-CONTRACTS.md` §1, OHLC is raw and `volume` is retroactively split-adjusted, mapping directly to `EodDailyBar::adj_volume`. + - Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`, `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without decoding their values. +3. **Zero-allocation key mapping:** + - Decodes into borrowed `RawEodDailyBar<'a>` and converts to `EodDailyBar` via `into_eod_daily_bar(|code, date| ...)` or `try_into_eod_daily_bar(|code, date| mapping.resolve("eod", code, date))`, avoiding per-row `String` allocations across 846M documents. +4. **Typed errors & stream skip/accounting policy:** + - Never panics on untrusted input. `BsonEodPriceError` names the offending field on every field-level error: `MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, `TruncatedDocument`, `CorruptDocumentLength`, and `CorruptBson`. + - `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`). + - `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`. +5. **Deferred out of `M1.2o`:** + - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). + ## Local Benchmarks ### `bench-split` @@ -631,9 +653,19 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000` - Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x` +### `bench-bson-eod-prices` + +Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic `eodPrices` documents (including `_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) pre-encoded into one contiguous length-prefixed buffer up front, timing decode-only via `decode_eod_price_buffer`: + +```bash +cargo run --release -p curate-etl --offline -- bench-bson-eod-prices [rows] +``` + +- Measured local baseline & `846,000,000`-doc single-core extrapolation: pending first offline release run after `cargo fetch` populates `bson = "=3.1.0"` in the host Cargo cache (sandbox shell has network disabled). + ## Deferred Follow-Ups (`M1.3+` / `M2`) -This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add: +This crate currently depends only on `bson` (`=3.1.0`, `default-features = false`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add: - `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata - `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 787a75d3..7d3d9fd5 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -8,11 +8,15 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; +use bson::oid::ObjectId; +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime; use parquet::errors::ParquetError; use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; +use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats}; use crate::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, @@ -74,6 +78,7 @@ pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000; /// + `cash_amount` (8) + `currency` (3) + `successor_listing_id` (4) + `terminal_return` (8) /// + `known_at` (8) + `known_at_source` (~13) = 72 bytes. pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; +pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; @@ -98,6 +103,7 @@ const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4; const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D; const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F; +const BSON_EOD_PRICES_BENCH_SEED: u64 = 0x570C_4B07_B504_E0D1; const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; @@ -3589,6 +3595,195 @@ pub fn run_parquet_corporate_actions_benchmark( Ok(report) } +/// Summary metrics produced by [`run_bson_eod_prices_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BsonEodPricesBenchReport { + pub rows: usize, + pub bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub ns_per_row: f64, + pub checksum: u64, + 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(), + }; + } + + const SYMBOL_POOL: usize = 2_000; + const EXCHANGES: [&str; 4] = ["NASDAQ", "NYSE", "TSX", "TSXV"]; + const PROVIDER_EXCHANGES: [&str; 4] = ["US", "US", "TO", "V"]; + const MILLIS_PER_DAY: i64 = 86_400_000; + + let min_date = ymd_to_epoch_days(2010, 1, 4).unwrap_or(14_613); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let mut date_days: Vec = Vec::with_capacity(4_200); + let mut date_strings: Vec = Vec::with_capacity(4_200); + for d in min_date..=max_date { + let dow = (d + 4).rem_euclid(7); + if dow == 0 || dow == 6 { + continue; + } + let (y, m, day) = epoch_days_to_ymd(d); + date_days.push(d); + date_strings.push(format!("{y:04}-{m:02}-{day:02}")); + } + + let symbols: Vec<(String, String, &'static str, &'static str)> = (0..SYMBOL_POOL) + .map(|i| { + let ex_idx = i % EXCHANGES.len(); + let sym = format!("SYM{i:04}"); + let prov = PROVIDER_EXCHANGES[ex_idx]; + let code = format!("{sym}.{prov}"); + (sym, code, EXCHANGES[ex_idx], prov) + }) + .collect(); + + let mut rng = SplitMix64::new(BSON_EOD_PRICES_BENCH_SEED); + // ~240 bytes per realistic eodPrices document with extra metadata fields. + let mut buffer: Vec = Vec::with_capacity(rows.saturating_mul(256)); + + for i in 0..rows { + let sym_idx = (rng.next_u64() as usize) % symbols.len(); + let (ref symbol, ref code, exchange, provider_exchange) = symbols[sym_idx]; + let date_idx = (rng.next_u64() as usize) % date_days.len(); + let epoch_day = date_days[date_idx]; + let date_str = &date_strings[date_idx]; + + let base_cents = 100 + (rng.next_u64() % 50_000) as i64; + let open = base_cents as f64 / 100.0; + let spread = 1.0 + (rng.next_u64() % 200) as f64 / 100.0; + let high = open + spread; + let low = (open - spread * 0.5).max(0.01); + let close = low + (high - low) * ((rng.next_u64() % 100) as f64 / 100.0); + let volume_i64 = 1_000 + (rng.next_u64() % 50_000_000) as i64; + + let mut oid_bytes = [0u8; 12]; + let seq = (i as u64).to_be_bytes(); + oid_bytes[4..12].copy_from_slice(&seq); + + let created_ms = i64::from(epoch_day) * MILLIS_PER_DAY + 79_200_000; + let updated_ms = created_ms + 60_000; + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("_id"), ObjectId::from_bytes(oid_bytes)); + doc.append(cstr!("symbol"), symbol.as_str()); + doc.append(cstr!("exchange"), exchange); + doc.append(cstr!("providerExchange"), provider_exchange); + doc.append(cstr!("source"), "eod"); + + // Inject ~0.5% deterministic rejected rows across 4 distinct error categories. + let bad_roll = rng.next_u64() % 1_000; + doc.append(cstr!("eodSearchCode"), code.as_str()); + if bad_roll == 0 { + // Malformed date string. + doc.append(cstr!("date"), "2023-02-29"); + } else if rng.next_u64() % 20 == 0 { + // ~5% BSON DateTime dates. + doc.append( + cstr!("date"), + DateTime::from_millis(i64::from(epoch_day) * MILLIS_PER_DAY), + ); + } else { + doc.append(cstr!("date"), date_str.as_str()); + } + + if bad_roll == 1 { + // Wrong BSON type on open. + doc.append(cstr!("open"), "bad"); + } else if i % 10 == 0 { + doc.append(cstr!("open"), (base_cents / 100) as i32); + } else { + doc.append(cstr!("open"), open); + } + + if bad_roll == 2 { + // Negative price on high. + doc.append(cstr!("high"), -1.0_f64); + } else { + doc.append(cstr!("high"), high); + } + + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("adjustedClose"), close * 0.95); + + if bad_roll != 3 && bad_roll != 4 { + match i % 3 { + 0 => doc.append(cstr!("volume"), volume_i64), + 1 => doc.append(cstr!("volume"), (volume_i64 as i32).abs()), + _ => doc.append(cstr!("volume"), volume_i64 as f64), + } + } + // When bad_roll is 3 or 4, omit `volume` to exercise MissingField. + + doc.append(cstr!("created_at"), DateTime::from_millis(created_ms)); + doc.append(cstr!("updated_at"), DateTime::from_millis(updated_ms)); + + buffer.extend_from_slice(doc.as_bytes()); + } + + let bytes = buffer.len(); + let mut hash = 0u64; + + let start = Instant::now(); + let stats = decode_eod_price_buffer( + &buffer, + |bar| { + hash = mix_bytes(hash, bar.eod_search_code.as_bytes()); + hash = mix_u64(hash, bar.session_date as u64); + hash = mix_u64(hash, bar.open.to_bits()); + hash = mix_u64(hash, bar.high.to_bits()); + hash = mix_u64(hash, bar.low.to_bits()); + hash = mix_u64(hash, bar.close.to_bits()); + hash = mix_u64(hash, bar.adj_volume.to_bits()); + }, + |offset, _err| { + hash = mix_u64(hash, offset as u64 ^ 0xDEAD_BEEF_CAFE_BABEu64); + }, + ); + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + let (rows_per_sec, ns_per_row) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (bytes as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let checksum = black_box(hash); + + BsonEodPricesBenchReport { + rows, + bytes, + elapsed_ms, + rows_per_sec, + mb_per_sec, + ns_per_row, + checksum, + stats, + } +} + #[cfg(test)] mod tests { use super::*; @@ -4382,4 +4577,36 @@ mod tests { "error must report expected (255) and actual (250) row counts, got: {msg}" ); } + + #[test] + fn bson_eod_prices_benchmark_small_run_is_deterministic() { + let a = run_bson_eod_prices_benchmark(20_000); + let b = run_bson_eod_prices_benchmark(20_000); + + 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!(a.stats.decoded > 19_000); + assert!(a.stats.rejected_total() > 0); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0); + } + + #[test] + fn bson_eod_prices_benchmark_zero_rows_handles_cleanly() { + let report = run_bson_eod_prices_benchmark(0); + assert_eq!(report.rows, 0); + assert_eq!(report.bytes, 0); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stats, BsonEodDecodeStats::default()); + } } diff --git a/tools/curate-etl/src/bson_eod_prices.rs b/tools/curate-etl/src/bson_eod_prices.rs new file mode 100644 index 00000000..9af35faa --- /dev/null +++ b/tools/curate-etl/src/bson_eod_prices.rs @@ -0,0 +1,631 @@ +//! Zero-copy raw BSON decoder for MongoDB `eodPrices` documents (`M1.2o`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into +//! borrowed [`RawEodDailyBar`] views without allocating a `String` or `bson::Document` per row. +//! Callers convert borrowed views into [`crate::bars::EodDailyBar`] via a caller-supplied key +//! mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an interned +//! integer symbol ID), keeping the 846M-document path free of per-row `String` allocations. +//! +//! # Empirical Field Contract +//! +//! Field names and semantics are grounded in the repository's ingestion writer, pipeline reader, +//! and empirical data contract: +//! - `apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts:4-56` (`persistEodPrices` +//! writes `eodSearchCode`, `date`, `open`, `high`, `low`, `close`, `volume`, plus metadata fields +//! `symbol`, `exchange`, `providerExchange`, `source`, and optional `adjustedClose`) +//! - `apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts:105-157` (calls +//! `persistEodPrices` with `{ symbol, exchange, eodSearchCode }` and EODHD JSON OHLCV records) +//! - `apps/stock/data-pipeline/src/normalization/bar-spans.ts:12-18` (`eodPrices` keyed by +//! `eodSearchCode` and `date`) +//! - `design/DATA-CONTRACTS.md` §1 (line 13): `eodPrices` (~845.7M docs) stores **raw** +//! `open`/`high`/`low`/`close`, while `volume` is **retroactively split-adjusted** and therefore +//! maps directly to [`EodDailyBar::adj_volume`]. +//! +//! Accepted BSON field representations: +//! - `eodSearchCode`: BSON UTF-8 `String` (stored verbatim; empty or whitespace-only is rejected). +//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via +//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via +//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check). +//! - `open`, `high`, `low`, `close`, `volume`: BSON `Double`, `Int32`, or `Int64` (every numeric +//! representation MongoDB can store for a JS number); must be finite and `>= 0.0` (`-0.0` is +//! normalized to `+0.0`). +//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `providerExchange`, `source`, +//! `adjustedClose`, `adjusted_close`, `created_at`, `updated_at`, nested objects/arrays, etc.) +//! are skipped without decoding their values. + +use std::error::Error; +use std::fmt; + +use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; +use bson::spec::ElementType; + +use crate::bars::EodDailyBar; +use crate::split::ymd_to_epoch_days; + +const MILLIS_PER_DAY: i64 = 86_400_000; +const MIN_BSON_DOC_LEN: i32 = 5; + +/// Borrowed zero-copy view of a single decoded `eodPrices` BSON document. +/// +/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice. +/// Per `design/DATA-CONTRACTS.md` §1, `open`/`high`/`low`/`close` are raw and `adj_volume` holds +/// the retroactively split-adjusted `eodPrices.volume`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawEodDailyBar<'a> { + pub eod_search_code: &'a str, + /// Session date as days since `1970-01-01` (UTC Gregorian). + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + /// Retroactively split-adjusted `eodPrices.volume`. + pub adj_volume: f64, +} + +impl<'a> RawEodDailyBar<'a> { + /// Converts this borrowed view into an [`EodDailyBar`] using a caller-supplied key mapper. + /// + /// `map_key` receives `(eod_search_code, session_date)` so callers can resolve an integer + /// `listing_id` or interned key without allocating a per-row `String`. + #[inline] + pub fn into_eod_daily_bar(self, map_key: F) -> EodDailyBar + where + F: FnOnce(&'a str, i32) -> K, + { + EodDailyBar { + key: map_key(self.eod_search_code, self.session_date), + session_date: self.session_date, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + adj_volume: self.adj_volume, + } + } + + /// Fallible conversion into [`EodDailyBar`] using a caller-supplied key resolver + /// (for example `|code, date| mapping.resolve("eod", code, date)`). + #[inline] + pub fn try_into_eod_daily_bar(self, map_key: F) -> Option> + where + F: FnOnce(&'a str, i32) -> Option, + { + let key = map_key(self.eod_search_code, self.session_date)?; + Some(EodDailyBar { + key, + session_date: self.session_date, + open: self.open, + high: self.high, + low: self.low, + close: self.close, + adj_volume: self.adj_volume, + }) + } +} + +/// Typed errors returned while decoding raw `eodPrices` BSON documents or length-prefixed buffers. +/// +/// Every field-level error names the offending BSON field in both its structure and `Display` +/// output; no input path panics. +#[derive(Debug, Clone, PartialEq)] +pub enum BsonEodPriceError { + /// A required field was absent from the document. + MissingField { field: &'static str }, + /// A required string field was empty or contained only whitespace. + EmptyField { field: &'static str }, + /// A required field had an unexpected BSON element type. + WrongType { + field: &'static str, + actual: ElementType, + }, + /// `date` string was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime` + /// overflowed `i32` epoch days. + MalformedDate { field: &'static str }, + /// A numeric OHLC or `volume` field was non-finite (`NaN`, `±inf`) or `< 0.0`. + InvalidNumber { field: &'static str, value: f64 }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: usize, + remaining: usize, + declared_len: Option, + }, + /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single + /// document slice). + CorruptDocumentLength { offset: usize, declared_len: i32 }, + /// Underlying BSON framing or element bytes were malformed. + CorruptBson { offset: usize, detail: String }, +} + +impl fmt::Display for BsonEodPriceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MissingField { field } => { + write!(f, "eodPrices BSON missing required field '{field}'") + } + Self::EmptyField { field } => { + write!(f, "eodPrices BSON field '{field}' must not be empty or blank") + } + Self::WrongType { field, actual } => { + write!( + f, + "eodPrices BSON field '{field}' has unexpected BSON type {actual:?}" + ) + } + Self::MalformedDate { field } => { + write!( + f, + "eodPrices BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime" + ) + } + Self::InvalidNumber { field, value } => { + write!( + f, + "eodPrices BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" + ) + } + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => match declared_len { + Some(len) => write!( + f, + "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" + ), + None => write!( + f, + "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" + ), + }, + Self::CorruptDocumentLength { + offset, + declared_len, + } => write!( + f, + "corrupt BSON document length {declared_len} at byte offset {offset}" + ), + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonEodPriceError {} + +/// Per-batch decode and rejection accounting for [`decode_eod_price_buffer`]. +/// +/// Conservation invariant: `decoded + rejected_total() == docs_in`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonEodDecodeStats { + pub docs_in: usize, + pub decoded: usize, + pub rejected_missing_field: usize, + pub rejected_empty_field: usize, + pub rejected_wrong_type: usize, + pub rejected_malformed_date: usize, + pub rejected_invalid_number: usize, + pub rejected_corrupt_document: usize, +} + +impl BsonEodDecodeStats { + /// Total number of rejected documents across all error categories. + #[inline] + pub fn rejected_total(&self) -> usize { + self.rejected_missing_field + + self.rejected_empty_field + + self.rejected_wrong_type + + self.rejected_malformed_date + + self.rejected_invalid_number + + self.rejected_corrupt_document + } + + /// Increments the rejection counter corresponding to `err`. + #[inline] + pub fn record_error(&mut self, err: &BsonEodPriceError) { + match err { + BsonEodPriceError::MissingField { .. } => self.rejected_missing_field += 1, + BsonEodPriceError::EmptyField { .. } => self.rejected_empty_field += 1, + BsonEodPriceError::WrongType { .. } => self.rejected_wrong_type += 1, + BsonEodPriceError::MalformedDate { .. } => self.rejected_malformed_date += 1, + BsonEodPriceError::InvalidNumber { .. } => self.rejected_invalid_number += 1, + BsonEodPriceError::TruncatedDocument { .. } + | BsonEodPriceError::CorruptDocumentLength { .. } + | BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1, + } + } +} + +#[inline] +fn parse_ascii_digits_u32(bytes: &[u8]) -> Option { + let mut acc: u32 = 0; + for &b in bytes { + if !b.is_ascii_digit() { + return None; + } + acc = acc * 10 + u32::from(b - b'0'); + } + Some(acc) +} + +#[inline] +fn parse_ymd_strict(s: &str) -> Result { + let bytes = s.as_bytes(); + if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + } + let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else { + return Err(BsonEodPriceError::MalformedDate { field: "date" }); + }; + ymd_to_epoch_days(year_u32 as i32, month, day) + .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" }) +} + +#[inline] +fn decode_element_value<'a>( + elem: RawElement<'a>, + offset: usize, +) -> Result, BsonEodPriceError> { + elem.value().map_err(|err| BsonEodPriceError::CorruptBson { + offset, + detail: err.to_string(), + }) +} + +#[inline] +fn decode_non_negative_number( + field: &'static str, + val: RawBsonRef<'_>, +) -> Result { + match val { + RawBsonRef::Double(v) => { + if !v.is_finite() || v < 0.0 { + return Err(BsonEodPriceError::InvalidNumber { field, value: v }); + } + if v == 0.0 { + Ok(0.0) + } else { + Ok(v) + } + } + RawBsonRef::Int32(v) => { + if v < 0 { + return Err(BsonEodPriceError::InvalidNumber { + field, + value: f64::from(v), + }); + } + Ok(f64::from(v)) + } + RawBsonRef::Int64(v) => { + if v < 0 { + return Err(BsonEodPriceError::InvalidNumber { + field, + value: v as f64, + }); + } + Ok(v as f64) + } + other => Err(BsonEodPriceError::WrongType { + field, + actual: other.element_type(), + }), + } +} + +fn decode_eod_price_doc_at<'a>( + doc: &'a RawDocument, + offset: usize, +) -> Result, BsonEodPriceError> { + let mut eod_search_code: Option<&'a str> = None; + let mut session_date: Option = None; + let mut open: Option = None; + let mut high: Option = None; + let mut low: Option = None; + let mut close: Option = None; + let mut adj_volume: Option = None; + + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonEodPriceError::CorruptBson { + offset, + detail: err.to_string(), + })?; + let key = elem.key(); + + if key == cstr!("eodSearchCode") { + match decode_element_value(elem, offset)? { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + return Err(BsonEodPriceError::EmptyField { + field: "eodSearchCode", + }); + } + eod_search_code = Some(s); + } + other => { + return Err(BsonEodPriceError::WrongType { + field: "eodSearchCode", + actual: other.element_type(), + }); + } + } + } else if key == cstr!("date") { + match decode_element_value(elem, offset)? { + RawBsonRef::String(s) => { + session_date = Some(parse_ymd_strict(s)?); + } + RawBsonRef::DateTime(dt) => { + let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); + let day_i32 = i32::try_from(days) + .map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })?; + session_date = Some(day_i32); + } + other => { + return Err(BsonEodPriceError::WrongType { + field: "date", + actual: other.element_type(), + }); + } + } + } else if key == cstr!("open") { + let val = decode_element_value(elem, offset)?; + open = Some(decode_non_negative_number("open", val)?); + } else if key == cstr!("high") { + let val = decode_element_value(elem, offset)?; + high = Some(decode_non_negative_number("high", val)?); + } else if key == cstr!("low") { + let val = decode_element_value(elem, offset)?; + low = Some(decode_non_negative_number("low", val)?); + } else if key == cstr!("close") { + let val = decode_element_value(elem, offset)?; + close = Some(decode_non_negative_number("close", val)?); + } else if key == cstr!("volume") { + let val = decode_element_value(elem, offset)?; + adj_volume = Some(decode_non_negative_number("volume", val)?); + } + // Unknown extra fields are skipped without calling `elem.value()`. + } + + let Some(eod_search_code) = eod_search_code else { + return Err(BsonEodPriceError::MissingField { + field: "eodSearchCode", + }); + }; + let Some(session_date) = session_date else { + return Err(BsonEodPriceError::MissingField { field: "date" }); + }; + let Some(open) = open else { + return Err(BsonEodPriceError::MissingField { field: "open" }); + }; + let Some(high) = high else { + return Err(BsonEodPriceError::MissingField { field: "high" }); + }; + let Some(low) = low else { + return Err(BsonEodPriceError::MissingField { field: "low" }); + }; + let Some(close) = close else { + return Err(BsonEodPriceError::MissingField { field: "close" }); + }; + let Some(adj_volume) = adj_volume else { + return Err(BsonEodPriceError::MissingField { field: "volume" }); + }; + + Ok(RawEodDailyBar { + eod_search_code, + session_date, + open, + high, + low, + close, + adj_volume, + }) +} + +/// Decodes a single `&RawDocument` representing an `eodPrices` MongoDB document in one forward pass +/// without allocating a `String` or owned `bson::Document`. +#[inline] +pub fn decode_eod_price_doc<'a>( + doc: &'a RawDocument, +) -> Result, BsonEodPriceError> { + decode_eod_price_doc_at(doc, 0) +} + +/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed +/// [`RawEodDailyBar`]. +pub fn decode_eod_price_bytes<'a>( + bytes: &'a [u8], +) -> Result, BsonEodPriceError> { + if bytes.len() < 4 { + return Err(BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: bytes.len(), + declared_len: None, + }); + } + let declared_len = i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + if declared_len < MIN_BSON_DOC_LEN { + return Err(BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len, + }); + } + let len_usize = declared_len as usize; + if len_usize > bytes.len() { + return Err(BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: bytes.len(), + declared_len: Some(declared_len), + }); + } + if len_usize < bytes.len() { + return Err(BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len, + }); + } + let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson { + offset: 0, + detail: err.to_string(), + })?; + decode_eod_price_doc_at(doc, 0) +} + +/// Zero-copy iterator over concatenated length-prefixed BSON documents (wire / `mongodump` layout). +#[derive(Debug, Clone)] +pub struct RawBsonDocIter<'a> { + buf: &'a [u8], + offset: usize, + terminated: bool, +} + +impl<'a> RawBsonDocIter<'a> { + /// Creates a new iterator starting at byte offset `0`. + #[inline] + pub fn new(buf: &'a [u8]) -> Self { + Self { + buf, + offset: 0, + terminated: false, + } + } + + /// Returns the next framed `&RawDocument` along with its starting byte offset in the buffer. + /// + /// Unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) terminate the + /// iterator cleanly so iteration never loops infinitely or slices out of bounds. A validly + /// length-framed document with invalid BSON framing bytes returns `CorruptBson` and advances + /// past the framed document so subsequent documents can still be read. + pub fn next_with_offset( + &mut self, + ) -> Option> { + if self.terminated || self.offset >= self.buf.len() { + return None; + } + + let offset = self.offset; + let remaining = self.buf.len() - offset; + if remaining < 4 { + self.terminated = true; + return Some(Err(( + offset, + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len: None, + }, + ))); + } + + let declared_len = i32::from_le_bytes([ + self.buf[offset], + self.buf[offset + 1], + self.buf[offset + 2], + self.buf[offset + 3], + ]); + if declared_len < MIN_BSON_DOC_LEN { + self.terminated = true; + return Some(Err(( + offset, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + }, + ))); + } + + let doc_len = declared_len as usize; + if doc_len > remaining { + self.terminated = true; + return Some(Err(( + offset, + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len: Some(declared_len), + }, + ))); + } + + let slice = &self.buf[offset..offset + doc_len]; + self.offset += doc_len; + + match RawDocument::from_bytes(slice) { + Ok(doc) => Some(Ok((offset, doc))), + Err(err) => Some(Err(( + offset, + BsonEodPriceError::CorruptBson { + offset, + detail: err.to_string(), + }, + ))), + } + } +} + +impl<'a> Iterator for RawBsonDocIter<'a> { + type Item = Result<&'a RawDocument, BsonEodPriceError>; + + #[inline] + fn next(&mut self) -> Option { + self.next_with_offset() + .map(|res| res.map(|(_, doc)| doc).map_err(|(_, err)| err)) + } +} + +/// Walks a contiguous byte buffer of concatenated length-prefixed BSON documents, yielding +/// zero-copy `&RawDocument` slices. +#[inline] +pub fn iter_raw_bson_docs<'a>(buf: &'a [u8]) -> RawBsonDocIter<'a> { + RawBsonDocIter::new(buf) +} + +/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_price_doc`], invoking +/// `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected document +/// without aborting the stream on per-document errors. +/// +/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`. +pub fn decode_eod_price_buffer<'a, F, E>( + buf: &'a [u8], + mut on_bar: F, + mut on_error: E, +) -> BsonEodDecodeStats +where + F: FnMut(RawEodDailyBar<'a>), + E: FnMut(usize, BsonEodPriceError), +{ + let mut stats = BsonEodDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + + while let Some(item) = iter.next_with_offset() { + stats.docs_in += 1; + match item { + Ok((doc_offset, doc)) => match decode_eod_price_doc_at(doc, doc_offset) { + Ok(bar) => { + stats.decoded += 1; + on_bar(bar); + } + Err(err) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + }, + Err((doc_offset, err)) => { + stats.record_error(&err); + on_error(doc_offset, err); + } + } + } + + stats +} + +#[cfg(test)] +#[path = "bson_eod_prices_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_eod_prices_tests.rs b/tools/curate-etl/src/bson_eod_prices_tests.rs new file mode 100644 index 00000000..b0f5bc10 --- /dev/null +++ b/tools/curate-etl/src/bson_eod_prices_tests.rs @@ -0,0 +1,684 @@ +use bson::oid::ObjectId; +use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; +use bson::spec::ElementType; +use bson::DateTime; + +use super::*; +use crate::bars::{build_bars_1d, QmRawVolume}; +use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable}; +use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).unwrap() +} + +fn make_valid_doc( + code: &str, + date: &str, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawDocumentBuf { + 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"), volume); + doc +} + +fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(1.0); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); +} + +#[test] +fn decodes_realistic_eod_price_doc_and_ignores_extra_fields() { + let mut nested = RawDocumentBuf::new(); + nested.append(cstr!("provider"), "eodhd"); + nested.append(cstr!("version"), 2_i32); + + let mut tags = RawArrayBuf::new(); + tags.push("us"); + tags.push("equity"); + + let mut doc = RawDocumentBuf::new(); + doc.append( + cstr!("_id"), + ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), + ); + doc.append(cstr!("symbol"), "NVDA"); + doc.append(cstr!("exchange"), "NASDAQ"); + doc.append(cstr!("providerExchange"), "US"); + doc.append(cstr!("source"), "eod"); + doc.append(cstr!("eodSearchCode"), "NVDA.US"); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), 1197.70_f64); + doc.append(cstr!("high"), 1216.92_f64); + doc.append(cstr!("low"), 1180.22_f64); + doc.append(cstr!("close"), 1208.88_f64); + doc.append(cstr!("adjustedClose"), 120.888_f64); + doc.append(cstr!("adjusted_close"), 120.888_f64); + doc.append(cstr!("volume"), 412_390_000_i64); + doc.append(cstr!("created_at"), DateTime::from_millis(1_717_804_800_000)); + doc.append(cstr!("updated_at"), DateTime::from_millis(1_717_891_200_000)); + doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); + doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); + + let bar = decode_eod_price_doc(&doc).unwrap(); + assert_eq!(bar.eod_search_code, "NVDA.US"); + assert_eq!(bar.session_date, day(2024, 6, 7)); + assert_eq!(bar.open.to_bits(), 1197.70_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 1216.92_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 1180.22_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 1208.88_f64.to_bits()); + assert_eq!(bar.adj_volume.to_bits(), 412_390_000.0_f64.to_bits()); + + // Verify decode_eod_price_bytes matches decode_eod_price_doc bit-for-bit. + let from_bytes = decode_eod_price_bytes(doc.as_bytes()).unwrap(); + assert_eq!(from_bytes, bar); +} + +#[test] +fn decodes_double_int32_int64_numerics_and_zero_volume_normalization() { + // Mixed Int32, Int64, and Double across OHLC and volume. + let mut mixed = RawDocumentBuf::new(); + mixed.append(cstr!("eodSearchCode"), "SHOP.TO"); + mixed.append(cstr!("date"), "2024-02-29"); + mixed.append(cstr!("open"), 100_i32); + mixed.append(cstr!("high"), 105_i64); + mixed.append(cstr!("low"), 99.5_f64); + mixed.append(cstr!("close"), 104_i32); + mixed.append(cstr!("volume"), 5_000_000_000_i64); + + let bar = decode_eod_price_doc(&mixed).unwrap(); + assert_eq!(bar.eod_search_code, "SHOP.TO"); + assert_eq!(bar.session_date, day(2024, 2, 29)); + assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits()); + assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits()); + assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits()); + assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits()); + assert_eq!(bar.adj_volume.to_bits(), 5_000_000_000.0_f64.to_bits()); + + // Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) all normalize to +0.0. + let zero_cases: [RawBsonRef<'_>; 4] = [ + RawBsonRef::Double(0.0), + RawBsonRef::Double(-0.0), + RawBsonRef::Int32(0), + RawBsonRef::Int64(0), + ]; + for zero_val in zero_cases { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "ZERO.US"); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), -0.0_f64); + doc.append(cstr!("high"), 10_i32); + doc.append(cstr!("low"), 0_i64); + doc.append(cstr!("close"), 5.5_f64); + doc.append(cstr!("volume"), zero_val); + + let decoded = decode_eod_price_doc(&doc).unwrap(); + assert_eq!(decoded.open.to_bits(), 0.0_f64.to_bits()); + assert_eq!(decoded.low.to_bits(), 0.0_f64.to_bits()); + assert_eq!(decoded.adj_volume.to_bits(), 0.0_f64.to_bits()); + } +} + +#[test] +fn decodes_ymd_string_and_bson_datetime_to_identical_epoch_days() { + let cases = [ + ("1969-12-31", day(1969, 12, 31)), + ("1970-01-01", day(1970, 1, 1)), + ("2024-02-29", day(2024, 2, 29)), + ("2024-06-07", day(2024, 6, 7)), + ]; + + for (date_str, expected_day) in cases { + let str_doc = make_valid_doc("TEST.US", date_str, 10.0, 11.0, 9.5, 10.5, 1000.0); + let decoded_str = decode_eod_price_doc(&str_doc).unwrap(); + assert_eq!(decoded_str.session_date, expected_day); + + // Midnight UTC DateTime. + let midnight_ms = i64::from(expected_day) * MILLIS_PER_DAY; + let mut dt_mid = RawDocumentBuf::new(); + dt_mid.append(cstr!("eodSearchCode"), "TEST.US"); + dt_mid.append(cstr!("date"), DateTime::from_millis(midnight_ms)); + dt_mid.append(cstr!("open"), 10.0_f64); + dt_mid.append(cstr!("high"), 11.0_f64); + dt_mid.append(cstr!("low"), 9.5_f64); + dt_mid.append(cstr!("close"), 10.5_f64); + dt_mid.append(cstr!("volume"), 1000.0_f64); + assert_eq!( + decode_eod_price_doc(&dt_mid).unwrap().session_date, + expected_day + ); + + // Mid-day UTC DateTime (12:34:56.789 UTC) — critically tests pre-1970 Euclidean division + // (`1969-12-31T12:34:56.789Z` must be -1, NOT 0). + let midday_ms = midnight_ms + (12 * 3_600 + 34 * 60 + 56) * 1_000 + 789; + let mut dt_midday = RawDocumentBuf::new(); + dt_midday.append(cstr!("eodSearchCode"), "TEST.US"); + dt_midday.append(cstr!("date"), DateTime::from_millis(midday_ms)); + dt_midday.append(cstr!("open"), 10.0_f64); + dt_midday.append(cstr!("high"), 11.0_f64); + dt_midday.append(cstr!("low"), 9.5_f64); + dt_midday.append(cstr!("close"), 10.5_f64); + dt_midday.append(cstr!("volume"), 1000.0_f64); + assert_eq!( + decode_eod_price_doc(&dt_midday).unwrap().session_date, + expected_day + ); + } +} + +#[test] +fn missing_each_required_field_returns_typed_error_naming_field() { + let required = [ + "eodSearchCode", + "date", + "open", + "high", + "low", + "close", + "volume", + ]; + + for omit in required { + let mut doc = RawDocumentBuf::new(); + if omit != "eodSearchCode" { + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + } + if omit != "date" { + doc.append(cstr!("date"), "2024-06-07"); + } + if omit != "open" { + doc.append(cstr!("open"), 190.0_f64); + } + if omit != "high" { + doc.append(cstr!("high"), 195.0_f64); + } + if omit != "low" { + doc.append(cstr!("low"), 189.0_f64); + } + if omit != "close" { + doc.append(cstr!("close"), 194.5_f64); + } + if omit != "volume" { + doc.append(cstr!("volume"), 50_000_000_i64); + } + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!(err, BsonEodPriceError::MissingField { field: omit }); + assert!( + err.to_string().contains(omit), + "error message should name '{omit}', got: {err}" + ); + } +} + +#[test] +fn empty_or_whitespace_eod_search_code_returns_empty_field_error() { + for blank in ["", " ", "\t\n"] { + let doc = make_valid_doc(blank, "2024-06-07", 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::EmptyField { + field: "eodSearchCode" + } + ); + assert!(err.to_string().contains("eodSearchCode")); + } +} + +#[test] +fn wrong_bson_types_return_typed_error_naming_field() { + let oid = ObjectId::from_bytes([0xAA; 12]); + let mut arr = RawArrayBuf::new(); + arr.push(1_i32); + + // Wrong types for eodSearchCode. + for (bad_val, expected_ty) in [ + (RawBsonRef::Int32(42), ElementType::Int32), + (RawBsonRef::Boolean(true), ElementType::Boolean), + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::ObjectId(oid), ElementType::ObjectId), + (RawBsonRef::Array(arr.as_ref()), ElementType::Array), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), bad_val); + doc.append(cstr!("date"), "2024-06-07"); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::WrongType { + field: "eodSearchCode", + actual: expected_ty, + } + ); + assert!(err.to_string().contains("eodSearchCode")); + } + + // Wrong types for date. + for (bad_val, expected_ty) in [ + (RawBsonRef::Int64(20240607), ElementType::Int64), + (RawBsonRef::Boolean(false), ElementType::Boolean), + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::ObjectId(oid), ElementType::ObjectId), + (RawBsonRef::Array(arr.as_ref()), ElementType::Array), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + doc.append(cstr!("date"), bad_val); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::WrongType { + field: "date", + actual: expected_ty, + } + ); + assert!(err.to_string().contains("date")); + } + + // Wrong types for each numeric field (open, high, low, close, volume). + let numeric_fields = ["open", "high", "low", "close", "volume"]; + for target in numeric_fields { + for (bad_val, expected_ty) in [ + (RawBsonRef::String("10.5"), ElementType::String), + (RawBsonRef::Boolean(true), ElementType::Boolean), + (RawBsonRef::Null, ElementType::Null), + (RawBsonRef::ObjectId(oid), ElementType::ObjectId), + (RawBsonRef::Array(arr.as_ref()), ElementType::Array), + ] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "AAPL.US"); + doc.append(cstr!("date"), "2024-06-07"); + for &field in &numeric_fields { + let key = match field { + "open" => cstr!("open"), + "high" => cstr!("high"), + "low" => cstr!("low"), + "close" => cstr!("close"), + _ => cstr!("volume"), + }; + if field == target { + doc.append(key, bad_val); + } else { + doc.append(key, 10.0_f64); + } + } + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::WrongType { + field: target, + actual: expected_ty, + } + ); + assert!(err.to_string().contains(target)); + } + } +} + +#[test] +fn malformed_dates_and_out_of_range_datetimes_return_malformed_date_error() { + for bad_date in [ + "2023-02-29", + "1900-02-29", + "2024-6-7", + "2024-06-07T00:00:00Z", + "2024-13-01", + "2024-00-10", + "2024-04-31", + "", + " 2024-06-07", + "2024/06/07", + "abcd-ef-gh", + ] { + let doc = make_valid_doc("BAD.US", bad_date, 10.0, 11.0, 9.0, 10.5, 100.0); + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::MalformedDate { field: "date" }, + "expected MalformedDate for '{bad_date}'" + ); + assert!(err.to_string().contains("date")); + } + + for extreme_ms in [i64::MAX, i64::MIN] { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "BAD.US"); + doc.append(cstr!("date"), DateTime::from_millis(extreme_ms)); + doc.append(cstr!("open"), 10.0_f64); + doc.append(cstr!("high"), 11.0_f64); + doc.append(cstr!("low"), 9.0_f64); + doc.append(cstr!("close"), 10.5_f64); + doc.append(cstr!("volume"), 100_i32); + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert_eq!(err, BsonEodPriceError::MalformedDate { field: "date" }); + assert!(err.to_string().contains("date")); + } +} + +#[test] +fn non_finite_and_negative_prices_or_volume_return_invalid_number_error() { + let fields = ["open", "high", "low", "close", "volume"]; + let bad_values: [RawBsonRef<'_>; 6] = [ + RawBsonRef::Double(f64::NAN), + RawBsonRef::Double(f64::INFINITY), + RawBsonRef::Double(f64::NEG_INFINITY), + RawBsonRef::Double(-0.01), + RawBsonRef::Int32(-1), + RawBsonRef::Int64(-100), + ]; + + for target in fields { + for bad_val in bad_values { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), "NUM.US"); + doc.append(cstr!("date"), "2024-06-07"); + for &field in &fields { + let key = match field { + "open" => cstr!("open"), + "high" => cstr!("high"), + "low" => cstr!("low"), + "close" => cstr!("close"), + _ => cstr!("volume"), + }; + if field == target { + doc.append(key, bad_val); + } else { + doc.append(key, 10.0_f64); + } + } + + let err = decode_eod_price_doc(&doc).unwrap_err(); + assert!( + matches!(err, BsonEodPriceError::InvalidNumber { field, .. } if field == target), + "expected InvalidNumber for {target} with {bad_val:?}, got {err:?}" + ); + assert!(err.to_string().contains(target)); + } + } +} + +#[test] +fn truncated_and_corrupt_length_prefixed_buffers_return_typed_errors_without_panicking() { + // 1. Truncated header (< 4 bytes). + let err = decode_eod_price_bytes(&[0x05, 0x00, 0x00]).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: 3, + declared_len: None, + } + ); + + // 2. Declared length < 5 (0, 4, negative). + for bad_len in [0_i32, 4_i32, -12_i32] { + let mut buf = Vec::from(bad_len.to_le_bytes()); + buf.push(0); + let err = decode_eod_price_bytes(&buf).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::CorruptDocumentLength { + offset: 0, + declared_len: bad_len, + } + ); + } + + // 3. Truncated body (declared_len > remaining). + let valid = make_valid_doc("NVDA.US", "2024-06-07", 10.0, 11.0, 9.0, 10.5, 100.0); + let full_bytes = valid.as_bytes(); + let truncated = &full_bytes[..full_bytes.len() - 5]; + let err = decode_eod_price_bytes(truncated).unwrap_err(); + assert_eq!( + err, + BsonEodPriceError::TruncatedDocument { + offset: 0, + remaining: truncated.len(), + declared_len: Some(full_bytes.len() as i32), + } + ); + + // 4. Corrupt trailing terminator (last byte != 0x00). + let mut bad_term = full_bytes.to_vec(); + *bad_term.last_mut().unwrap() = 0xFF; + let err = decode_eod_price_bytes(&bad_term).unwrap_err(); + assert!( + matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }), + "expected CorruptBson for bad terminator, got {err:?}" + ); + + // 5. Corrupt element framing inside a length-valid document (bad element type byte 0x7F). + let mut bad_elem: Vec = Vec::new(); + let declared: i32 = 10; + bad_elem.extend_from_slice(&declared.to_le_bytes()); + bad_elem.extend_from_slice(&[0x7F, b'a', 0x00, 0x01, 0x02, 0x00]); + let err = decode_eod_price_bytes(&bad_elem).unwrap_err(); + assert!( + matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }), + "expected CorruptBson for corrupt element framing, got {err:?}" + ); + + // 6. Iterator terminates cleanly on framing errors without looping. + let mut iter = iter_raw_bson_docs(truncated); + assert!(matches!( + iter.next(), + Some(Err(BsonEodPriceError::TruncatedDocument { .. })) + )); + assert!(iter.next().is_none()); +} + +#[test] +fn multi_document_buffer_skips_bad_docs_and_reconciles_per_reason_stats() { + let good_1 = make_valid_doc("AAPL.US", "2024-06-05", 194.0, 196.9, 193.5, 195.87, 54_000_000.0); + + // Bad 1: missing field (`volume`). + let mut bad_missing = RawDocumentBuf::new(); + bad_missing.append(cstr!("eodSearchCode"), "MISS.US"); + bad_missing.append(cstr!("date"), "2024-06-05"); + bad_missing.append(cstr!("open"), 10.0_f64); + bad_missing.append(cstr!("high"), 11.0_f64); + bad_missing.append(cstr!("low"), 9.0_f64); + bad_missing.append(cstr!("close"), 10.5_f64); + + // Bad 2: empty `eodSearchCode`. + let bad_empty = make_valid_doc(" ", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0); + + // Bad 3: wrong BSON type (`open` is string). + let mut bad_type = RawDocumentBuf::new(); + bad_type.append(cstr!("eodSearchCode"), "TYPE.US"); + bad_type.append(cstr!("date"), "2024-06-05"); + bad_type.append(cstr!("open"), "not-a-number"); + bad_type.append(cstr!("high"), 11.0_f64); + bad_type.append(cstr!("low"), 9.0_f64); + bad_type.append(cstr!("close"), 10.5_f64); + bad_type.append(cstr!("volume"), 100_i32); + + // Bad 4: malformed date. + let bad_date = make_valid_doc("DATE.US", "2023-02-29", 10.0, 11.0, 9.0, 10.5, 100.0); + + // Bad 5: negative price. + let bad_price = make_valid_doc("NEG.US", "2024-06-05", -1.0, 11.0, 9.0, 10.5, 100.0); + + // Bad 6: NaN volume. + let bad_vol = make_valid_doc("NAN.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, f64::NAN); + + // Bad 7: length-valid document with corrupt trailing null byte (stream still continues past it). + let mut bad_corrupt = make_valid_doc("COR.US", "2024-06-05", 10.0, 11.0, 9.0, 10.5, 100.0) + .as_bytes() + .to_vec(); + *bad_corrupt.last_mut().unwrap() = 0xEE; + + let good_2 = make_valid_doc("MSFT.US", "2024-06-06", 423.0, 425.3, 420.5, 424.52, 14_800_000.0); + + let mut buffer = Vec::new(); + buffer.extend_from_slice(good_1.as_bytes()); + buffer.extend_from_slice(bad_missing.as_bytes()); + buffer.extend_from_slice(bad_empty.as_bytes()); + buffer.extend_from_slice(bad_type.as_bytes()); + buffer.extend_from_slice(bad_date.as_bytes()); + buffer.extend_from_slice(bad_price.as_bytes()); + buffer.extend_from_slice(bad_vol.as_bytes()); + buffer.extend_from_slice(&bad_corrupt); + buffer.extend_from_slice(good_2.as_bytes()); + + let mut decoded_codes: Vec = Vec::new(); + let mut errors: Vec<(usize, BsonEodPriceError)> = Vec::new(); + + let stats = decode_eod_price_buffer( + &buffer, + |bar| decoded_codes.push(bar.eod_search_code.to_string()), + |offset, err| errors.push((offset, err)), + ); + + assert_eq!(decoded_codes, vec!["AAPL.US", "MSFT.US"]); + assert_eq!(stats.docs_in, 9); + assert_eq!(stats.decoded, 2); + assert_eq!(stats.rejected_missing_field, 1); + assert_eq!(stats.rejected_empty_field, 1); + assert_eq!(stats.rejected_wrong_type, 1); + assert_eq!(stats.rejected_malformed_date, 1); + assert_eq!(stats.rejected_invalid_number, 2); + assert_eq!(stats.rejected_corrupt_document, 1); + assert_eq!(stats.rejected_total(), 7); + assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in); + assert_eq!(errors.len(), 7); +} + +#[test] +fn decoded_nvda_split_buffer_feeds_build_bars_1d_with_non_string_key_mapper() { + let pre_split = day(2024, 6, 7); + let ex_date = day(2024, 6, 10); + let post_split = day(2024, 6, 11); + const NVDA_LISTING_ID: i32 = 42; + + // Encode NVDA 10:1 split fixture with mixed Int64 / Int32 / Double volume representations. + let mut doc_pre = RawDocumentBuf::new(); + doc_pre.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_pre.append(cstr!("date"), "2024-06-07"); + doc_pre.append(cstr!("open"), 1197.70_f64); + doc_pre.append(cstr!("high"), 1216.92_f64); + doc_pre.append(cstr!("low"), 1180.22_f64); + doc_pre.append(cstr!("close"), 1208.88_f64); + doc_pre.append(cstr!("volume"), 412_390_000_i64); + + let mut doc_ex = RawDocumentBuf::new(); + doc_ex.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_ex.append(cstr!("date"), "2024-06-10"); + doc_ex.append(cstr!("open"), 120.37_f64); + doc_ex.append(cstr!("high"), 123.10_f64); + doc_ex.append(cstr!("low"), 117.01_f64); + doc_ex.append(cstr!("close"), 121.79_f64); + doc_ex.append(cstr!("volume"), 314_162_700_i32); + + let mut doc_post = RawDocumentBuf::new(); + doc_post.append(cstr!("eodSearchCode"), "NVDA.US"); + doc_post.append( + cstr!("date"), + DateTime::from_millis(i64::from(post_split) * MILLIS_PER_DAY), + ); + doc_post.append(cstr!("open"), 121.77_f64); + doc_post.append(cstr!("high"), 122.87_f64); + doc_post.append(cstr!("low"), 118.74_f64); + doc_post.append(cstr!("close"), 120.91_f64); + doc_post.append(cstr!("volume"), 222_551_200.0_f64); + + // Include an unmapped symbol to prove try_into_eod_daily_bar filters unmapped keys cleanly. + let doc_unmapped = make_valid_doc("UNKNOWN.US", "2024-06-10", 10.0, 11.0, 9.0, 10.5, 1_000.0); + + let mut buf = Vec::new(); + buf.extend_from_slice(doc_pre.as_bytes()); + buf.extend_from_slice(doc_ex.as_bytes()); + buf.extend_from_slice(doc_post.as_bytes()); + buf.extend_from_slice(doc_unmapped.as_bytes()); + + let mapping = ProviderMappingTable::from_rows([ProviderMappingRow { + source: "eod".to_string(), + source_id: "NVDA.US".to_string(), + valid_from: day(1999, 1, 22), + valid_to: None, + listing_id: NVDA_LISTING_ID, + }]) + .unwrap(); + + let mut bars: Vec> = Vec::new(); + let stats = decode_eod_price_buffer( + &buf, + |raw| { + if let Some(bar) = + raw.try_into_eod_daily_bar(|code, dt| mapping.resolve("eod", code, dt)) + { + bars.push(bar); + } + }, + |offset, err| panic!("unexpected decode error at offset {offset}: {err}"), + ); + + assert_eq!(stats.docs_in, 4); + assert_eq!(stats.decoded, 4); + assert_eq!(stats.rejected_total(), 0); + assert_eq!(bars.len(), 3); + + let splits: SplitTable = SplitTable::from_events([( + NVDA_LISTING_ID, + SplitEvent { + ex_date, + ratio: 10.0, + }, + )]) + .unwrap(); + + let built = + build_bars_1d(bars, &splits, std::iter::empty::>(), 0.01).unwrap(); + assert_eq!(built.rows.len(), 3); + + // Pre-split 2024-06-07: raw OHLC preserved bit-for-bit, volume un-adjusted by / 10. + let r0 = &built.rows[0]; + assert_eq!(r0.key, NVDA_LISTING_ID); + assert_eq!(r0.session_date, pre_split); + assert_eq!(r0.open.to_bits(), 1197.70_f64.to_bits()); + assert_eq!(r0.high.to_bits(), 1216.92_f64.to_bits()); + assert_eq!(r0.low.to_bits(), 1180.22_f64.to_bits()); + assert_eq!(r0.close.to_bits(), 1208.88_f64.to_bits()); + assert_rel_eq(r0.volume, 41_239_000.0, 1e-12); + + // Ex-date 2024-06-10: factor = 1.0, volume unchanged. + let r1 = &built.rows[1]; + assert_eq!(r1.session_date, ex_date); + assert_eq!(r1.close.to_bits(), 121.79_f64.to_bits()); + assert_eq!(r1.volume.to_bits(), 314_162_700.0_f64.to_bits()); + + // Post-split 2024-06-11: factor = 1.0, volume unchanged. + let r2 = &built.rows[2]; + assert_eq!(r2.session_date, post_split); + assert_eq!(r2.close.to_bits(), 120.91_f64.to_bits()); + assert_eq!(r2.volume.to_bits(), 222_551_200.0_f64.to_bits()); +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 6b27a228..a91a190d 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -5,11 +5,12 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, - DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, 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, + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + 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, }; /// Parsed CLI command to execute. @@ -31,6 +32,7 @@ pub enum CliAction { BenchParquetFx(usize), BenchParquetAdj(usize), BenchParquetCorporateActions(usize), + BenchBsonEodPrices(usize), } /// Formats full help text including binary name and version. @@ -54,7 +56,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-parquet-events [rows] Run fixed-seed events Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_EVENTS_BENCH_ROWS})\n\ {name} bench-parquet-fx [rows] Run fixed-seed fx_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_FX_BENCH_ROWS})\n\ {name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\ - {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})" + {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})" ) } @@ -77,7 +80,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-events [rows]\n\ {name} bench-parquet-fx [rows]\n\ {name} bench-parquet-adj [rows]\n\ - {name} bench-parquet-corporate-actions [rows]" + {name} bench-parquet-corporate-actions [rows]\n\ + {name} bench-bson-eod-prices [rows]" ) } @@ -230,6 +234,18 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-parquet-corporate-actions", _, ..] => { Err("too many arguments for bench-parquet-corporate-actions".to_string()) } + ["bench-bson-eod-prices"] => Ok(CliAction::BenchBsonEodPrices( + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, + )), + ["bench-bson-eod-prices", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchBsonEodPrices(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-bson-eod-prices", _, ..] => { + Err("too many arguments for bench-bson-eod-prices".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -499,6 +515,24 @@ mod tests { assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_bson_eod_prices_args() { + assert_eq!( + parse_args(&to_args(&["bench-bson-eod-prices"])), + Ok(CliAction::BenchBsonEodPrices( + DEFAULT_BSON_EOD_PRICES_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-bson-eod-prices", "250000"])), + Ok(CliAction::BenchBsonEodPrices(250_000)) + ); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -516,6 +550,7 @@ mod tests { assert!(full.contains("bench-parquet-fx")); assert!(full.contains("bench-parquet-adj")); assert!(full.contains("bench-parquet-corporate-actions")); + assert!(full.contains("bench-bson-eod-prices")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -532,5 +567,6 @@ mod tests { assert!(short.contains("bench-parquet-fx")); assert!(short.contains("bench-parquet-adj")); assert!(short.contains("bench-parquet-corporate-actions")); + assert!(short.contains("bench-bson-eod-prices")); } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 4b7ca850..a36cdcd1 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -3,6 +3,7 @@ pub mod adj; pub mod bars; pub mod bench; +pub mod bson_eod_prices; pub mod cli; pub mod corporate_actions; pub mod events; @@ -26,6 +27,10 @@ pub use bars::{ build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; +pub use bson_eod_prices::{ + decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, + BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar, +}; pub use 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 4c075bbe..c0128eef 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,11 +4,11 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_benchmark, run_corporate_actions_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_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, + run_corporate_actions_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}; @@ -477,6 +477,31 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchBsonEodPrices(rows)) => { + let report = run_bson_eod_prices_benchmark(rows); + println!("curate-etl bench-bson-eod-prices"); + println!(" input: rows={} bytes={}", report.rows, report.bytes); + println!( + " decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})", + 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 + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s latency={:.2} ns/row checksum=0x{:016x}", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.ns_per_row, + report.checksum + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME));