From 4c8a621e48b2dbf6ae68b3ee876c77f4e2a3f742 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 15:39:38 -0500 Subject: [PATCH] =?UTF-8?q?T-47:=20M1.2a=20=E2=80=94=20Scaffold=20`tools/c?= =?UTF-8?q?urate-etl`=20Rust=20crate:=20split-factor=20table=20+=20un-adju?= =?UTF-8?q?stment=20core=20with=20local=20benchmark=20(no=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 2 +- tools/curate-etl/src/bench.rs | 59 +++++++++++++------ tools/curate-etl/src/main.rs | 108 +++++++++++++++++++++++++++------- tools/curate-etl/src/split.rs | 33 ++++++++++- 4 files changed, 161 insertions(+), 41 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index a0edafc4..3ae82aa7 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -12,7 +12,7 @@ Aligned with `design/DATA-CONTRACTS.md` (ยง1 `qmSplits`, `eodPrices`, `eodIntrad - No-op rows (`ratio == 1.0`) are dropped during `SplitTable::from_events`. - Duplicate events on the same `ex_date` are multiplied (and dropped if reciprocal pairs cancel to `1.0`). - Non-finite or `<= 0.0` ratios and compounding overflow/underflow return a typed `SplitError` rather than panicking. -- **Ex-date boundary (strict `>`):** `cum_factor_after(key, bar_date)` returns the product of all split ratios with `ex_date > bar_date`. A bar dated on the ex-date itself is already post-split (`factor = 1.0`). Unknown keys and post-split dates return `1.0`. +- **Ex-date boundary (strict `>`):** `cum_factor_after(key, bar_date)` returns the product of all split ratios with `ex_date > bar_date`. A bar dated on an ex-date excludes that day's split (it is already post-split for that event) while still including any later splits (for example, NVDA on its `2021-07-20` 4:1 ex-date still has `factor = 10.0` from the later `2024-06-10` 10:1 split). Unknown keys and dates with no later splits return `1.0`. - **`eodPrices` (daily bars):** OHLC is raw and only volume is retroactively split-adjusted: - `raw_volume = unadjust_volume(adj_volume, factor) = adj_volume / factor` - **`eodIntraday1M` (1m bars, reused in M2):** both OHLC and volume are retroactively split-adjusted: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 6e23be51..a2764b13 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -3,7 +3,7 @@ use std::hint::black_box; use std::time::Instant; -use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitEvent, SplitTable}; +use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable}; pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; pub const BENCH_KEY_COUNT: usize = 20_000; @@ -48,14 +48,23 @@ pub struct BenchReport { pub checksum: f64, } +#[inline] +fn compute_rates(rows: usize, elapsed_secs: f64) -> (f64, f64) { + if rows == 0 || elapsed_secs <= 0.0 || !elapsed_secs.is_finite() { + (0.0, 0.0) + } else { + (rows as f64 / elapsed_secs, elapsed_secs * 1e9 / rows as f64) + } +} + /// Runs the fixed-seed split lookup + `unadjust_volume` benchmark for `rows` bars. /// /// Builds a [`SplitTable`] with `20_000` symbol keys and `19_000` deterministic forward /// and reverse splits spanning `1990-01-01..=2025-12-31`, then executes `rows` zero-allocation /// lookups and volume un-adjustments. -pub fn run_split_benchmark(rows: usize) -> BenchReport { - let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305); - let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); +pub fn run_split_benchmark(rows: usize) -> Result { + let min_date = ymd_to_epoch_days(1990, 1, 1)?; + let max_date = ymd_to_epoch_days(2025, 12, 31)?; let date_span = (max_date - min_date + 1) as u64; let keys: Vec = (0..BENCH_KEY_COUNT) @@ -72,7 +81,7 @@ pub fn run_split_benchmark(rows: usize) -> BenchReport { } let build_start = Instant::now(); - let table = SplitTable::from_events(events).unwrap_or_default(); + let table = SplitTable::from_events(events)?; let build_elapsed_ms = build_start.elapsed().as_secs_f64() * 1_000.0; let key_count = keys.len(); @@ -93,13 +102,9 @@ pub fn run_split_benchmark(rows: usize) -> BenchReport { let elapsed_secs = elapsed.as_secs_f64(); let elapsed_ms = elapsed_secs * 1_000.0; - let (rows_per_sec, ns_per_row) = if rows == 0 || elapsed_secs == 0.0 { - (0.0, 0.0) - } else { - (rows as f64 / elapsed_secs, elapsed_secs * 1e9 / rows as f64) - }; + let (rows_per_sec, ns_per_row) = compute_rates(rows, elapsed_secs); - BenchReport { + Ok(BenchReport { rows, key_count, table_keys_with_splits: table.len(), @@ -109,35 +114,53 @@ pub fn run_split_benchmark(rows: usize) -> BenchReport { rows_per_sec, ns_per_row, checksum, - } + }) } #[cfg(test)] mod tests { use super::*; + const EXPECTED_KEYS_WITH_SPLITS: usize = 12_153; + const EXPECTED_EVENT_COUNT: usize = 18_999; + #[test] fn benchmark_small_run_is_deterministic() { - let a = run_split_benchmark(1_000); - let b = run_split_benchmark(1_000); + let a = run_split_benchmark(1_000).unwrap(); + let b = run_split_benchmark(1_000).unwrap(); assert_eq!(a.rows, 1_000); assert_eq!(a.key_count, BENCH_KEY_COUNT); + assert_eq!(a.table_keys_with_splits, EXPECTED_KEYS_WITH_SPLITS); + assert_eq!(a.table_event_count, EXPECTED_EVENT_COUNT); assert_eq!(a.table_keys_with_splits, b.table_keys_with_splits); assert_eq!(a.table_event_count, b.table_event_count); assert_eq!(a.checksum.to_bits(), b.checksum.to_bits()); assert!(a.checksum.is_finite() && a.checksum > 0.0); - assert!(a.rows_per_sec > 0.0); - assert!(a.ns_per_row > 0.0); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0); + } + + #[test] + fn compute_rates_uses_fixed_duration() { + let (rows_per_sec, ns_per_row) = compute_rates(1_000, 0.5); + assert_eq!(rows_per_sec, 2_000.0); + assert_eq!(ns_per_row, 500_000.0); + + assert_eq!(compute_rates(0, 0.5), (0.0, 0.0)); + assert_eq!(compute_rates(1_000, 0.0), (0.0, 0.0)); + assert_eq!(compute_rates(1_000, -1.0), (0.0, 0.0)); } #[test] fn benchmark_zero_rows_handles_cleanly() { - let report = run_split_benchmark(0); + let report = run_split_benchmark(0).unwrap(); assert_eq!(report.rows, 0); + assert_eq!(report.key_count, BENCH_KEY_COUNT); + assert_eq!(report.table_keys_with_splits, EXPECTED_KEYS_WITH_SPLITS); + assert_eq!(report.table_event_count, EXPECTED_EVENT_COUNT); assert_eq!(report.checksum, 0.0); assert_eq!(report.rows_per_sec, 0.0); assert_eq!(report.ns_per_row, 0.0); - assert!(report.table_keys_with_splits > 0); } } diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index de1ed52a..bf4e0396 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -28,37 +28,53 @@ fn print_usage_stderr() { ); } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CliAction { + Help, + Version, + BenchSplit(usize), +} + +fn parse_args(args: &[String]) -> Result { + let slices: Vec<&str> = args.iter().map(String::as_str).collect(); + match slices.as_slice() { + [] | ["--help"] | ["-h"] => Ok(CliAction::Help), + ["--version"] | ["-V"] => Ok(CliAction::Version), + [flag @ ("--help" | "-h" | "--version" | "-V"), extra, ..] => { + Err(format!("unexpected argument '{extra}' after '{flag}'")) + } + ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), + ["bench-split", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-split", _, ..] => Err("too many arguments for bench-split".to_string()), + [other, ..] => Err(format!("unknown argument '{other}'")), + } +} + fn main() -> ExitCode { let args: Vec = env::args().skip(1).collect(); - match args.first().map(String::as_str) { - None | Some("--help") | Some("-h") => { + match parse_args(&args) { + Ok(CliAction::Help) => { print_usage(); ExitCode::SUCCESS } - Some("--version") | Some("-V") => { + Ok(CliAction::Version) => { println!("{NAME} {VERSION}"); ExitCode::SUCCESS } - Some("bench-split") => { - let rows = match args.get(1) { - None => DEFAULT_BENCH_ROWS, - Some(raw) if args.len() == 2 => match raw.parse::() { - Ok(n) if n > 0 => n, - _ => { - eprintln!("error: invalid row count '{raw}' (expected a positive integer)"); - print_usage_stderr(); - return ExitCode::FAILURE; - } - }, - Some(_) => { - eprintln!("error: too many arguments for bench-split"); - print_usage_stderr(); + Ok(CliAction::BenchSplit(rows)) => { + let report = match run_split_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: benchmark fixture failed: {err}"); return ExitCode::FAILURE; } }; - - let report = run_split_benchmark(rows); println!("curate-etl bench-split"); println!( " table: keys={} keys_with_splits={} events={} build={:.2} ms", @@ -77,10 +93,60 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } - Some(other) => { - eprintln!("error: unknown argument '{other}'"); + Err(msg) => { + eprintln!("error: {msg}"); print_usage_stderr(); ExitCode::FAILURE } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn to_args(items: &[&str]) -> Vec { + items.iter().map(|s| (*s).to_string()).collect() + } + + #[test] + fn parses_standalone_help_and_version_flags() { + assert_eq!(parse_args(&to_args(&[])), Ok(CliAction::Help)); + assert_eq!(parse_args(&to_args(&["--help"])), Ok(CliAction::Help)); + assert_eq!(parse_args(&to_args(&["-h"])), Ok(CliAction::Help)); + assert_eq!(parse_args(&to_args(&["--version"])), Ok(CliAction::Version)); + assert_eq!(parse_args(&to_args(&["-V"])), Ok(CliAction::Version)); + } + + #[test] + fn rejects_trailing_arguments_after_help_or_version() { + for invalid in [ + &["--help", "--unknown"][..], + &["-h", "extra"][..], + &["--version", "--offine"][..], + &["-V", "bench-split"][..], + ] { + let err = parse_args(&to_args(invalid)).unwrap_err(); + assert!( + err.contains("unexpected argument"), + "expected unexpected argument error for {invalid:?}, got: {err}" + ); + } + } + + #[test] + fn parses_and_validates_bench_split_and_unknown_args() { + assert_eq!( + parse_args(&to_args(&["bench-split"])), + Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-split", "100000"])), + Ok(CliAction::BenchSplit(100_000)) + ); + assert!(parse_args(&to_args(&["bench-split", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-split", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-split", "10", "20"])).is_err()); + assert!(parse_args(&to_args(&["--unknown"])).is_err()); + } +} diff --git a/tools/curate-etl/src/split.rs b/tools/curate-etl/src/split.rs index 57aef753..8fd10067 100644 --- a/tools/curate-etl/src/split.rs +++ b/tools/curate-etl/src/split.rs @@ -184,7 +184,11 @@ where let mut coalesced: Vec<(i32, f64)> = Vec::new(); for (key, mut key_events) in grouped { - key_events.sort_unstable_by_key(|ev| ev.ex_date); + key_events.sort_unstable_by(|a, b| { + a.ex_date + .cmp(&b.ex_date) + .then_with(|| a.ratio.total_cmp(&b.ratio)) + }); coalesced.clear(); for ev in key_events { @@ -573,6 +577,33 @@ mod tests { assert_eq!(table.cum_factor_after("DUP", d1), 1.0); } + #[test] + fn same_date_events_produce_bitwise_identical_factors_across_permutations() { + let d1 = ymd_to_epoch_days(2023, 3, 15).unwrap(); + let permutations = [[10.0, 0.1, 0.1], [0.1, 10.0, 0.1], [0.1, 0.1, 10.0]]; + + let mut baseline_bits: Option = None; + for ratios in permutations { + let table = SplitTable::from_events( + ratios + .into_iter() + .map(|ratio| ("PERM".to_string(), SplitEvent { ex_date: d1, ratio })), + ) + .unwrap(); + + let factor = table.cum_factor_after("PERM", d1 - 1); + assert_rel_eq(factor, 0.1, 1e-12); + match baseline_bits { + None => baseline_bits = Some(factor.to_bits()), + Some(expected) => assert_eq!( + factor.to_bits(), + expected, + "same-date ratio permutation changed factor bits" + ), + } + } + } + #[test] fn generic_i32_listing_id_keys_and_date_boundaries() { let table: SplitTable = SplitTable::from_events([