From 16c218c04fe596b9b02d444a6a9ee41974bc60ba Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 17:09:14 -0500 Subject: [PATCH] =?UTF-8?q?T-98:=20M1.2p=20=E2=80=94=20`tools/curate-etl`:?= =?UTF-8?q?=20pure=20`bars=5F1d`=20curation=20stage=20(source-keyed=20`eod?= =?UTF-8?q?Prices`=20bars=20=E2=86=92=20`provider=5Fmapping`=20=E2=86=92?= =?UTF-8?q?=20un-adjusted=20`Bars1dParquetRow`s=20=E2=86=92=20Zstd=20Parqu?= =?UTF-8?q?et)=20with=20tests=20and=20local=20benchmark=20(no=20new=20crat?= =?UTF-8?q?es)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 14 +- tools/curate-etl/src/bench.rs | 742 +++++++++++++++++++++++----------- 2 files changed, 521 insertions(+), 235 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 16b03a43..8929ac57 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -663,7 +663,7 @@ This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so al ### `bench-curate-bars` -Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `eodPrices` bars across `2,000` `String` keys (`2008..=2025` with unique per-key coprime-stride `(source_id, session_date)` pairs for ordinary bars, plus explicitly injected builder duplicates, pre-2008, date-ranged ticker-reuse/unmapped, missing-currency, and cross-`source_id` collision slices, `2,000` splits, and ~50% `qmPrices` partners), separately timing in-memory `curate_bars_1d` and Zstd Parquet `write_bars_1d_dataset` into a temp directory with footer row-count verification and cleanup: +Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `eodPrices` bars across `2,000` `String` keys per `2,000,000`-row block (`2008..=2025` with unique per-key coprime-stride `(source_id, session_date)` pairs guarded against cursor wrap, plus explicitly injected builder duplicates, pre-2008, date-ranged ticker-reuse/unmapped, missing-currency, and cross-`source_id` collision slices, `2,000` splits per block, and ~50% `qmPrices` partners), separately timing in-memory `curate_bars_1d` and Zstd Parquet `write_bars_1d_dataset` into a temp directory with footer row-count verification and cleanup: ```bash cargo run --release -p curate-etl --offline -- bench-curate-bars [rows] @@ -677,10 +677,10 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x883cab90 - Curation stats: `unmapped=17929`, `missing_curr=15152`, `ts_oor=3950`, `coll_collapsed=3083`, `coll_dropped=6094`, `mismatch_samples=100` - Note: 846M-row single-core figures below are linear projections from the measured `2,000,000`-row batch at `97.39%` retention. - Run 1: - - Stage (in-memory): `elapsed=1174.93 ms`, `throughput=1702227 rows/s`, `latency=587.47 ns/row`, single-core 846M projection `497.0 s` (`8.28 min`), `checksum=0x883cab901cdb0ebb` - - Parquet write: `elapsed=600.34 ms`, `throughput=3244486 rows/s` - - Combined (stage → Parquet): `elapsed=1775.27 ms`, `throughput=1126587 rows/s`, single-core 846M projection `750.9 s` (`12.52 min`, projected at batch=`2000000` and `97.39%` retention) + - Stage (in-memory): `elapsed=1225.30 ms`, `throughput=1632248 rows/s`, `latency=612.65 ns/row`, single-core 846M projection `518.3 s` (`8.64 min`), `checksum=0x883cab901cdb0ebb` + - Parquet write: `elapsed=609.48 ms`, `throughput=3195857 rows/s` + - Combined (stage → Parquet): `elapsed=1834.78 ms`, `throughput=1090048 rows/s`, single-core 846M projection `776.1 s` (`12.94 min`, projected at batch=`2000000` and `97.39%` retention) - Run 2: - - Stage (in-memory): `elapsed=1206.77 ms`, `throughput=1657322 rows/s`, `latency=603.38 ns/row`, single-core 846M projection `510.5 s` (`8.51 min`), `checksum=0x883cab901cdb0ebb` - - Parquet write: `elapsed=597.13 ms`, `throughput=3261920 rows/s` - - Combined (stage → Parquet): `elapsed=1803.90 ms`, `throughput=1108709 rows/s`, single-core 846M projection `763.0 s` (`12.72 min`, projected at batch=`2000000` and `97.39%` retention) + - Stage (in-memory): `elapsed=1207.46 ms`, `throughput=1656374 rows/s`, `latency=603.73 ns/row`, single-core 846M projection `510.8 s` (`8.51 min`), `checksum=0x883cab901cdb0ebb` + - Parquet write: `elapsed=602.41 ms`, `throughput=3233345 rows/s` + - Combined (stage → Parquet): `elapsed=1809.87 ms`, `throughput=1105053 rows/s`, single-core 846M projection `765.6 s` (`12.76 min`, projected at batch=`2000000` and `97.39%` retention) diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 609a029d..350cdf72 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -3593,8 +3593,77 @@ pub const DEFAULT_CURATE_BARS_BENCH_ROWS: usize = 2_000_000; pub const EOD_PRICES_FULL_ROW_COUNT: f64 = 846_000_000.0; const CURATE_BARS_BENCH_SEED: u64 = 0x570C_4B07_C04A_BA45; const CURATE_BARS_BENCH_KEY_COUNT: usize = 2_000; +const CURATE_BARS_BENCH_ROWS_PER_KEY_BLOCK: usize = 2_000_000; const CURATE_BARS_BENCH_SPLIT_COUNT: usize = 2_000; +/// Errors returned by [`run_curate_bars_benchmark`]. +#[derive(Debug)] +pub enum CurateBarsBenchError { + /// Curation stage or Parquet write error. + Write(crate::curate_bars::CurateBarsWriteError), + /// Fixture exhausted the unique date pool for a key before generating all requested rows. + FixtureDatePoolExhausted { + rows: usize, + key_count: usize, + key_idx: usize, + pool: &'static str, + capacity: u64, + }, +} + +impl std::fmt::Display for CurateBarsBenchError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Write(err) => write!(f, "{err}"), + Self::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool, + capacity, + } => write!( + f, + "curate-bars benchmark fixture exhausted unique {pool} date pool (capacity {capacity} dates/key) for key_idx={key_idx} while generating {rows} rows across {key_count} keys" + ), + } + } +} + +impl std::error::Error for CurateBarsBenchError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Write(err) => Some(err), + Self::FixtureDatePoolExhausted { .. } => None, + } + } +} + +impl From for CurateBarsBenchError { + fn from(err: crate::curate_bars::CurateBarsWriteError) -> Self { + Self::Write(err) + } +} + +impl From for CurateBarsBenchError { + fn from(err: crate::curate_bars::CurateBarsError) -> Self { + Self::Write(crate::curate_bars::CurateBarsWriteError::from(err)) + } +} + +impl From for CurateBarsBenchError { + fn from(err: ParquetBarsError) -> Self { + Self::Write(crate::curate_bars::CurateBarsWriteError::from(err)) + } +} + +/// Scales the benchmark key space in `2,000`-key blocks per `2,000,000` rows so larger batches +/// keep ordinary `(source_id, session_date)` pairs unique without exhausting the 2008..=2025 +/// date pool. +fn curate_bars_bench_key_count(rows: usize) -> usize { + let blocks = rows.div_ceil(CURATE_BARS_BENCH_ROWS_PER_KEY_BLOCK).max(1); + CURATE_BARS_BENCH_KEY_COUNT.saturating_mul(blocks) +} + /// Summary metrics produced by [`run_curate_bars_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct CurateBarsBenchReport { @@ -3634,9 +3703,315 @@ fn mix_str_u64(mut hash: u64, s: &str) -> u64 { hash } +struct CurateBarsBenchFixture { + bars: Vec>, + qm_volumes: Vec>, + splits: SplitTable, + provider_mapping: ProviderMappingTable, + listing_currencies: std::collections::HashMap>, + key_count: usize, + split_event_count: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_dup_identical: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_dup_conflict: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_alias_identical: usize, + #[cfg_attr(not(test), allow(dead_code))] + injected_alias_conflict: usize, +} + +fn build_curate_bars_bench_fixture( + rows: usize, + key_count: usize, + date_span_limit: Option, +) -> Result { + use std::collections::HashMap; + + assert!( + key_count >= CURATE_BARS_BENCH_KEY_COUNT && key_count % CURATE_BARS_BENCH_KEY_COUNT == 0, + "key_count ({key_count}) must be a positive multiple of {CURATE_BARS_BENCH_KEY_COUNT}" + ); + let scale = key_count / CURATE_BARS_BENCH_KEY_COUNT; + + let min_date = ymd_to_epoch_days(2008, 1, 2).expect("valid start date"); + let max_date = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); + let full_date_span = (max_date - min_date + 1) as u64; + let date_span = date_span_limit.map_or(full_date_span, |limit| limit.clamp(1, full_date_span)); + let pre_2008_start = ymd_to_epoch_days(2006, 1, 2).expect("valid pre-2008 start"); + let pre_2008_span = (min_date - pre_2008_start) as u64; + let reuse_end = ymd_to_epoch_days(2016, 12, 31).expect("valid reuse end"); + let reuse_resume = ymd_to_epoch_days(2018, 1, 1).expect("valid reuse resume"); + + let single_range_end = 1_900 * scale; + let reuse_end_idx = 1_950 * scale; + let alias_end_idx = 1_970 * scale; + let missing_curr_end_idx = 1_985 * scale; + let alias_count = alias_end_idx - reuse_end_idx; + let ordinary_key_count = key_count - alias_count; + let reuse_lid_offset = key_count.max(10_000); + let split_count = CURATE_BARS_BENCH_SPLIT_COUNT * scale; + + let keys: Vec = (0..key_count) + .map(|i| { + if i % 5 == 0 { + format!("SYM{i:04}.TO") + } else { + format!("SYM{i:04}.US") + } + }) + .collect(); + + // Build provider_mapping and listing_currencies (scaled proportionally per 2,000-key block): + // - 0..single_range_end: open-ended single range -> listing (i + 1) + // - single_range_end..reuse_end_idx: two ranges with 2017 gap -> listings (i + 1) and (i + reuse_lid_offset + 1) + // - reuse_end_idx..alias_end_idx: aliases of listings 1..=alias_count (cross-source_id collisions) + // - alias_end_idx..missing_curr_end_idx: mapped to listing (i + 1) but omitted from currencies + // - missing_curr_end_idx..key_count: unmapped keys + let mut mapping_rows: Vec = + Vec::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + let mut listing_currencies: HashMap> = + HashMap::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + + for (i, key) in keys.iter().enumerate() { + let curr = if i % 5 == 0 { + Cow::Borrowed("CAD") + } else { + Cow::Borrowed("USD") + }; + if i < single_range_end { + let lid = (i + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_2008_start, + valid_to: None, + listing_id: lid, + }); + listing_currencies.insert(lid, curr); + } else if i < reuse_end_idx { + let lid1 = (i + 1) as i32; + let lid2 = (i + reuse_lid_offset + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_2008_start, + valid_to: Some(reuse_end), + listing_id: lid1, + }); + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: reuse_resume, + valid_to: None, + listing_id: lid2, + }); + listing_currencies.insert(lid1, curr.clone()); + listing_currencies.insert(lid2, curr); + } else if i < alias_end_idx { + let alias_lid = (i - reuse_end_idx + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_2008_start, + valid_to: None, + listing_id: alias_lid, + }); + } else if i < missing_curr_end_idx { + let lid = (i + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "eod".to_string(), + source_id: key.clone(), + valid_from: pre_2008_start, + valid_to: None, + listing_id: lid, + }); + // Deliberately omit from listing_currencies to exercise dropped_missing_currency. + } + } + let provider_mapping = + ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); + + let mut rng = SplitMix64::new(CURATE_BARS_BENCH_SEED); + + let mut split_events = Vec::with_capacity(split_count); + for _ in 0..split_count { + let key_idx = (rng.next_u64() as usize) % reuse_end_idx; + let ex_date = min_date + (rng.next_u64() % date_span) as i32; + let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]; + split_events.push((keys[key_idx].clone(), SplitEvent { ex_date, ratio })); + } + let splits = SplitTable::from_events(split_events).unwrap_or_default(); + let split_event_count = splits.event_count(); + + let mut bars: Vec> = Vec::with_capacity(rows); + let mut qm_volumes: Vec> = Vec::with_capacity(rows / 2 + 64); + + // Per-key coprime-stride cursors with explicit usage guards guarantee unique + // (source_id, session_date) pairs for ordinary bars (up to 6,574 dates per key in + // 2008..=2025, 730 in 2006..2008) so all builder duplicates and cross-source_id collisions + // are injected explicitly and a cursor can never wrap silently. + const DATE_STRIDE: u64 = 1_571; // prime, coprime to 6,574 = 2 * 19 * 173 + const PRE_2008_STRIDE: u64 = 197; // prime, coprime to 730 = 2 * 5 * 73 + let date_stride = if date_span_limit.is_none() { + DATE_STRIDE + } else { + 1 + }; + let mut date_cursor: Vec = (0..key_count).map(|_| rng.next_u64() % date_span).collect(); + let mut pre_date_cursor: Vec = (0..key_count) + .map(|_| rng.next_u64() % pre_2008_span) + .collect(); + let mut date_used: Vec = vec![0; key_count]; + let mut pre_date_used: Vec = vec![0; key_count]; + + let mut last_alias_pair: Option<(usize, EodDailyBar)> = None; + let mut last_ordinary_bar: Option> = None; + let mut injected_dup_identical = 0usize; + let mut injected_dup_conflict = 0usize; + let mut injected_alias_identical = 0usize; + let mut injected_alias_conflict = 0usize; + + for _ in 0..rows { + let roll = rng.next_u64() % 1_000; + if roll < 4 { + if let Some((alias_idx, mut prev)) = last_alias_pair.take() { + let orig_close_bits = prev.close.to_bits(); + prev.key = keys[reuse_end_idx + alias_idx].clone(); + if roll >= 2 { + // Conflicting cross-source_id collision on the same (listing_id, session_date). + prev.close = (prev.close + 0.05).min(prev.high); + if prev.close.to_bits() == orig_close_bits { + prev.adj_volume += 1.0; + } + injected_alias_conflict += 1; + } else { + injected_alias_identical += 1; + } + bars.push(prev); + continue; + } + } else if roll < 6 { + if let Some(mut prev) = last_ordinary_bar.take() { + if roll == 5 { + // Conflicting same-source_id duplicate dropped in build_bars_1d. + let orig_close_bits = prev.close.to_bits(); + prev.close = (prev.close + 0.05).min(prev.high); + if prev.close.to_bits() == orig_close_bits { + prev.adj_volume += 1.0; + } + injected_dup_conflict += 1; + } else { + injected_dup_identical += 1; + } + bars.push(prev); + continue; + } + } + + let key_idx = if roll < 10 { + (rng.next_u64() as usize) % alias_count + } else { + // Skip alias keys reuse_end_idx..alias_end_idx for ordinary bars so alias collisions + // are purely explicit. + let slot = (rng.next_u64() as usize) % ordinary_key_count; + if slot < reuse_end_idx { + slot + } else { + slot + alias_count + } + }; + let session_date = if roll == 10 || roll == 11 { + if pre_date_used[key_idx] >= pre_2008_span { + return Err(CurateBarsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool: "pre-2008", + capacity: pre_2008_span, + }); + } + pre_date_used[key_idx] += 1; + let offset = pre_date_cursor[key_idx]; + pre_date_cursor[key_idx] = (offset + PRE_2008_STRIDE) % pre_2008_span; + pre_2008_start + offset as i32 + } else { + if date_used[key_idx] >= date_span { + return Err(CurateBarsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + pool: "2008..=2025", + capacity: date_span, + }); + } + date_used[key_idx] += 1; + let offset = date_cursor[key_idx]; + date_cursor[key_idx] = (offset + date_stride) % date_span; + min_date + offset as i32 + }; + + let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; + let spread = ((rng.next_u64() % 500) + 10) as f64 * 0.01; + let high = low + spread; + let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let adj_volume = ((rng.next_u64() % 10_000_000) + 100) as f64; + + let b = EodDailyBar { + key: keys[key_idx].clone(), + session_date, + open, + high, + low, + close, + adj_volume, + }; + if key_idx < alias_count && session_date >= min_date { + // Only record alias template when no later split differentiates the two keys. + if splits.cum_factor_after(&b.key, session_date).to_bits() == 1.0_f64.to_bits() { + last_alias_pair = Some((key_idx, b.clone())); + } + } else if (alias_count..single_range_end).contains(&key_idx) && session_date >= min_date { + last_ordinary_bar = Some(b.clone()); + } + if rng.next_u64() & 1 == 0 { + let factor = splits.cum_factor_after(&b.key, session_date); + let raw = unadjust_volume(adj_volume, factor); + let mismatch_roll = rng.next_u64() % 100; + let share_volume = if mismatch_roll == 0 { + raw * 1.15 + } else { + let jitter_bp = (rng.next_u64() % 101) as f64 - 50.0; + raw * (1.0 + jitter_bp * 0.0001) + }; + qm_volumes.push(QmRawVolume { + key: b.key.clone(), + session_date, + share_volume, + }); + } + bars.push(b); + } + + Ok(CurateBarsBenchFixture { + bars, + qm_volumes, + splits, + provider_mapping, + listing_currencies, + key_count, + split_event_count, + injected_dup_identical, + injected_dup_conflict, + injected_alias_identical, + injected_alias_conflict, + }) +} + fn run_curate_bars_benchmark_tracked( rows: usize, -) -> Result<(CurateBarsBenchReport, PathBuf), crate::curate_bars::CurateBarsWriteError> { +) -> Result<(CurateBarsBenchReport, PathBuf), CurateBarsBenchError> { use std::collections::HashMap; use crate::curate_bars::{curate_bars_1d, CurateBars1dStats, CurateBarsWriteError}; @@ -3645,7 +4020,12 @@ fn run_curate_bars_benchmark_tracked( &std::env::temp_dir(), "curate-etl-bench-curate-bars", ) - .map_err(|(path, source)| CurateBarsWriteError::Parquet(ParquetBarsError::Io { path, source }))?; + .map_err(|(path, source)| { + CurateBarsBenchError::Write(CurateBarsWriteError::Parquet(ParquetBarsError::Io { + path, + source, + })) + })?; let temp_path = temp.path.clone(); if rows == 0 { @@ -3698,232 +4078,22 @@ fn run_curate_bars_benchmark_tracked( )); } - let min_date = ymd_to_epoch_days(2008, 1, 2).expect("valid start date"); - let max_date = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); - let date_span = (max_date - min_date + 1) as u64; - let pre_2008_start = ymd_to_epoch_days(2006, 1, 2).expect("valid pre-2008 start"); - let pre_2008_span = (min_date - pre_2008_start) as u64; - let reuse_end = ymd_to_epoch_days(2016, 12, 31).expect("valid reuse end"); - let reuse_resume = ymd_to_epoch_days(2018, 1, 1).expect("valid reuse resume"); - - let keys: Vec = (0..CURATE_BARS_BENCH_KEY_COUNT) - .map(|i| { - if i % 5 == 0 { - format!("SYM{i:04}.TO") - } else { - format!("SYM{i:04}.US") - } - }) - .collect(); - - // Build provider_mapping and listing_currencies: - // - 0..1900: open-ended single range -> listing (i + 1) - // - 1900..1950: two ranges with 2017 gap -> listings (i + 1) and (i + 10_001) - // - 1950..1970: aliases of listings 1..=20 (cross-source_id collisions) - // - 1970..1985: mapped to listing (i + 1) but omitted from currencies - // - 1985..2000: unmapped keys - let mut mapping_rows: Vec = - Vec::with_capacity(CURATE_BARS_BENCH_KEY_COUNT + 64); - let mut listing_currencies: HashMap> = - HashMap::with_capacity(CURATE_BARS_BENCH_KEY_COUNT + 64); - - for (i, key) in keys.iter().enumerate() { - let curr = if i % 5 == 0 { - Cow::Borrowed("CAD") - } else { - Cow::Borrowed("USD") - }; - if i < 1_900 { - let lid = (i + 1) as i32; - mapping_rows.push(ProviderMappingRow { - source: "eod".to_string(), - source_id: key.clone(), - valid_from: pre_2008_start, - valid_to: None, - listing_id: lid, - }); - listing_currencies.insert(lid, curr); - } else if i < 1_950 { - let lid1 = (i + 1) as i32; - let lid2 = (i + 10_001) as i32; - mapping_rows.push(ProviderMappingRow { - source: "eod".to_string(), - source_id: key.clone(), - valid_from: pre_2008_start, - valid_to: Some(reuse_end), - listing_id: lid1, - }); - mapping_rows.push(ProviderMappingRow { - source: "eod".to_string(), - source_id: key.clone(), - valid_from: reuse_resume, - valid_to: None, - listing_id: lid2, - }); - listing_currencies.insert(lid1, curr.clone()); - listing_currencies.insert(lid2, curr); - } else if i < 1_970 { - let alias_lid = (i - 1_950 + 1) as i32; - mapping_rows.push(ProviderMappingRow { - source: "eod".to_string(), - source_id: key.clone(), - valid_from: pre_2008_start, - valid_to: None, - listing_id: alias_lid, - }); - } else if i < 1_985 { - let lid = (i + 1) as i32; - mapping_rows.push(ProviderMappingRow { - source: "eod".to_string(), - source_id: key.clone(), - valid_from: pre_2008_start, - valid_to: None, - listing_id: lid, - }); - // Deliberately omit from listing_currencies to exercise dropped_missing_currency. - } - } - let provider_mapping = - ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); - - let mut rng = SplitMix64::new(CURATE_BARS_BENCH_SEED); - - let mut split_events = Vec::with_capacity(CURATE_BARS_BENCH_SPLIT_COUNT); - for _ in 0..CURATE_BARS_BENCH_SPLIT_COUNT { - let key_idx = (rng.next_u64() as usize) % 1_950; - let ex_date = min_date + (rng.next_u64() % date_span) as i32; - let ratio = SAMPLE_RATIOS[(rng.next_u64() as usize) % SAMPLE_RATIOS.len()]; - split_events.push((keys[key_idx].clone(), SplitEvent { ex_date, ratio })); - } - let splits = SplitTable::from_events(split_events).unwrap_or_default(); - let split_event_count = splits.event_count(); - - let mut bars: Vec> = Vec::with_capacity(rows); - let mut qm_volumes: Vec> = Vec::with_capacity(rows / 2 + 64); - - // Per-key coprime-stride cursors guarantee unique (source_id, session_date) pairs for - // ordinary bars (up to 6,574 dates per key in 2008..=2025, 730 in 2006..2008) so all - // builder duplicates and cross-source_id collisions are injected explicitly. - const DATE_STRIDE: u64 = 1_571; // prime, coprime to 6,574 = 2 * 19 * 173 - const PRE_2008_STRIDE: u64 = 197; // prime, coprime to 730 = 2 * 5 * 73 - const ORDINARY_KEY_COUNT: usize = CURATE_BARS_BENCH_KEY_COUNT - 20; - let mut date_cursor: Vec = (0..CURATE_BARS_BENCH_KEY_COUNT) - .map(|_| rng.next_u64() % date_span) - .collect(); - let mut pre_date_cursor: Vec = (0..CURATE_BARS_BENCH_KEY_COUNT) - .map(|_| rng.next_u64() % pre_2008_span) - .collect(); - - let mut last_alias_pair: Option<(usize, EodDailyBar)> = None; - let mut last_ordinary_bar: Option> = None; - - for _ in 0..rows { - let roll = rng.next_u64() % 1_000; - if roll < 4 { - if let Some((alias_idx, mut prev)) = last_alias_pair.take() { - let orig_close_bits = prev.close.to_bits(); - prev.key = keys[1_950 + alias_idx].clone(); - if roll >= 2 { - // Conflicting cross-source_id collision on the same (listing_id, session_date). - prev.close = (prev.close + 0.05).min(prev.high); - if prev.close.to_bits() == orig_close_bits { - prev.adj_volume += 1.0; - } - } - bars.push(prev); - continue; - } - } else if roll < 6 { - if let Some(mut prev) = last_ordinary_bar.take() { - if roll == 5 { - // Conflicting same-source_id duplicate dropped in build_bars_1d. - let orig_close_bits = prev.close.to_bits(); - prev.close = (prev.close + 0.05).min(prev.high); - if prev.close.to_bits() == orig_close_bits { - prev.adj_volume += 1.0; - } - } - bars.push(prev); - continue; - } - } - - let key_idx = if roll < 10 { - (rng.next_u64() as usize) % 20 - } else { - // Skip alias keys 1950..1970 for ordinary bars so alias collisions are purely explicit. - let slot = (rng.next_u64() as usize) % ORDINARY_KEY_COUNT; - if slot < 1_950 { - slot - } else { - slot + 20 - } - }; - let session_date = if roll == 10 || roll == 11 { - let offset = pre_date_cursor[key_idx]; - pre_date_cursor[key_idx] = (offset + PRE_2008_STRIDE) % pre_2008_span; - pre_2008_start + offset as i32 - } else { - let offset = date_cursor[key_idx]; - date_cursor[key_idx] = (offset + DATE_STRIDE) % date_span; - min_date + offset as i32 - }; - - let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; - let spread = ((rng.next_u64() % 500) + 10) as f64 * 0.01; - let high = low + spread; - let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let adj_volume = ((rng.next_u64() % 10_000_000) + 100) as f64; - - let b = EodDailyBar { - key: keys[key_idx].clone(), - session_date, - open, - high, - low, - close, - adj_volume, - }; - if key_idx < 20 && session_date >= min_date { - // Only record alias template when no later split differentiates the two keys. - if splits.cum_factor_after(&b.key, session_date).to_bits() == 1.0_f64.to_bits() { - last_alias_pair = Some((key_idx, b.clone())); - } - } else if (20..1_900).contains(&key_idx) && session_date >= min_date { - last_ordinary_bar = Some(b.clone()); - } - if rng.next_u64() & 1 == 0 { - let factor = splits.cum_factor_after(&b.key, session_date); - let raw = unadjust_volume(adj_volume, factor); - let mismatch_roll = rng.next_u64() % 100; - let share_volume = if mismatch_roll == 0 { - raw * 1.15 - } else { - let jitter_bp = (rng.next_u64() % 101) as f64 - 50.0; - raw * (1.0 + jitter_bp * 0.0001) - }; - qm_volumes.push(QmRawVolume { - key: b.key.clone(), - session_date, - share_volume, - }); - } - bars.push(b); - } - - let qm_rows_in = qm_volumes.len(); + let key_count = curate_bars_bench_key_count(rows); + let fixture = build_curate_bars_bench_fixture(rows, key_count, None)?; + let qm_rows_in = fixture.qm_volumes.len(); + let split_event_count = fixture.split_event_count; + let fixture_key_count = fixture.key_count; // 1. Time pure in-memory curation stage. let stage_start = Instant::now(); let curated = curate_bars_1d( - bars, - &splits, - qm_volumes, + fixture.bars, + &fixture.splits, + fixture.qm_volumes, 0.01, - &provider_mapping, + &fixture.provider_mapping, "eod", - &listing_currencies, + &fixture.listing_currencies, )?; let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; @@ -3982,7 +4152,7 @@ fn run_curate_bars_benchmark_tracked( let report = CurateBarsBenchReport { rows, - key_count: CURATE_BARS_BENCH_KEY_COUNT, + key_count: fixture_key_count, split_event_count, qm_rows_in, rows_out: curated.stats.rows_out, @@ -4010,11 +4180,10 @@ fn run_curate_bars_benchmark_tracked( } /// Runs the fixed-seed `bars_1d` curation stage + Zstd Parquet write benchmark for `rows` -/// source-keyed `eodPrices` bars across `2,000` `String` source keys (`2008..=2025` plus small -/// pre-2008, unmapped, missing-currency, and cross-`source_id` collision slices). -pub fn run_curate_bars_benchmark( - rows: usize, -) -> Result { +/// source-keyed `eodPrices` bars across `2,000` `String` source keys per `2,000,000`-row block +/// (`2008..=2025` plus small pre-2008, unmapped, missing-currency, and cross-`source_id` +/// collision slices). +pub fn run_curate_bars_benchmark(rows: usize) -> Result { let (report, _) = run_curate_bars_benchmark_tracked(rows)?; Ok(report) } @@ -4896,4 +5065,121 @@ mod tests { assert_eq!(report.total_rows_per_sec, 0.0); assert_eq!(report.total_extrap_846m_secs, 0.0); } + + #[test] + fn curate_bars_benchmark_distinguishes_deliberate_duplicates_from_cursor_exhaustion() { + use crate::curate_bars::curate_bars_1d; + + // 1. Below cursor exhaustion: every builder duplicate and listing collision must match + // the explicitly injected counts with zero accidental cursor-wrap conflicts. + let fixture = + build_curate_bars_bench_fixture(5_000, CURATE_BARS_BENCH_KEY_COUNT, Some(12)) + .expect("5,000 rows across 2,000 keys fits within 12 dates/key"); + assert!(fixture.injected_dup_identical > 0); + assert!(fixture.injected_dup_conflict > 0); + assert!(fixture.injected_alias_identical > 0); + assert!(fixture.injected_alias_conflict > 0); + + let curated = curate_bars_1d( + fixture.bars, + &fixture.splits, + fixture.qm_volumes, + 0.01, + &fixture.provider_mapping, + "eod", + &fixture.listing_currencies, + ) + .unwrap(); + assert_eq!( + curated.stats.builder.duplicate_collapsed, + fixture.injected_dup_identical, + "builder identical duplicates must match explicit injections only" + ); + assert_eq!( + curated.stats.builder.duplicate_conflict_dropped, + fixture.injected_dup_conflict * 2, + "builder conflicting duplicates must match explicit injections only (2 rows per pair)" + ); + assert_eq!( + curated.stats.listing_collision_collapsed, + fixture.injected_alias_identical, + "listing identical collisions must match explicit injections only" + ); + assert_eq!( + curated.stats.listing_collision_dropped, + fixture.injected_alias_conflict * 2, + "listing conflicting collisions must match explicit injections only (2 rows per pair)" + ); + + // 2. Past cursor exhaustion: the fixture must reject the run with a clear error rather + // than silently wrapping and turning ordinary bars into accidental conflicts. + let err = match build_curate_bars_bench_fixture(40_000, CURATE_BARS_BENCH_KEY_COUNT, Some(12)) + { + Ok(_) => panic!("40,000 rows across 2,000 keys must exhaust a 12-date pool"), + Err(err) => err, + }; + assert!( + matches!( + err, + CurateBarsBenchError::FixtureDatePoolExhausted { + rows: 40_000, + key_count: CURATE_BARS_BENCH_KEY_COUNT, + pool: "2008..=2025", + capacity: 12, + .. + } + ), + "expected FixtureDatePoolExhausted, got {err:?}" + ); + let msg = err.to_string(); + assert!( + msg.contains("2008..=2025") + && msg.contains("12") + && msg.contains("40000") + && msg.contains("2000"), + "error message should explain the fixture limit, got: {msg}" + ); + } + + #[test] + fn curate_bars_benchmark_scales_key_space_for_large_batches() { + use crate::curate_bars::curate_bars_1d; + + assert_eq!(curate_bars_bench_key_count(0), 2_000); + assert_eq!(curate_bars_bench_key_count(2_000_000), 2_000); + assert_eq!(curate_bars_bench_key_count(2_000_001), 4_000); + assert_eq!(curate_bars_bench_key_count(20_000_000), 20_000); + + let scaled_keys = curate_bars_bench_key_count(20_000_000); + let fixture = build_curate_bars_bench_fixture(20_000, scaled_keys, None).unwrap(); + assert_eq!(fixture.key_count, 20_000); + + let curated = curate_bars_1d( + fixture.bars, + &fixture.splits, + fixture.qm_volumes, + 0.01, + &fixture.provider_mapping, + "eod", + &fixture.listing_currencies, + ) + .unwrap(); + assert_eq!( + curated.stats.builder.duplicate_collapsed, + fixture.injected_dup_identical + ); + assert_eq!( + curated.stats.builder.duplicate_conflict_dropped, + fixture.injected_dup_conflict * 2 + ); + assert_eq!( + curated.stats.listing_collision_collapsed, + fixture.injected_alias_identical + ); + assert_eq!( + curated.stats.listing_collision_dropped, + fixture.injected_alias_conflict * 2 + ); + assert!(curated.stats.rows_out > 20_000 * 90 / 100); + } }