From 0d115cb66b03e4390827caf6a4ff4ec6aaf7a751 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 17:48:53 -0500 Subject: [PATCH 1/3] =?UTF-8?q?T-100:=20M1.2r=20=E2=80=94=20`tools/curate-?= =?UTF-8?q?etl`:=20pure=20`shorts`=20curation=20stage=20(source-keyed=20`c?= =?UTF-8?q?eoShorts`=20reports=20=E2=86=92=20`provider=5Fmapping`=20?= =?UTF-8?q?=E2=86=92=20`ShortsParquetRow`s=20=E2=86=92=20Zstd=20Parquet)?= =?UTF-8?q?=20with=20tests=20and=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 | 38 + tools/curate-etl/src/bench.rs | 613 +++++++++++++++ tools/curate-etl/src/cli.rs | 41 +- tools/curate-etl/src/curate_shorts.rs | 315 ++++++++ tools/curate-etl/src/curate_shorts_tests.rs | 782 ++++++++++++++++++++ tools/curate-etl/src/lib.rs | 6 + tools/curate-etl/src/main.rs | 59 ++ 7 files changed, 1851 insertions(+), 3 deletions(-) create mode 100644 tools/curate-etl/src/curate_shorts.rs create mode 100644 tools/curate-etl/src/curate_shorts_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 3a62a968..a77018d3 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -688,3 +688,41 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x098ac03b - Stage (in-memory): `elapsed=1181.40 ms`, `throughput=1692903 rows/s`, `latency=590.70 ns/row`, single-core 846M projection `499.7 s` (`8.33 min`), `checksum=0x098ac03b74d9899a` - Parquet write: `elapsed=708.69 ms`, `throughput=2748627 rows/s` - Combined (stage → Parquet): `elapsed=1890.09 ms`, `throughput=1058151 rows/s`, single-core 846M projection `799.5 s` (`13.33 min`, projected at batch=`2000000` and `97.40%` retention) + +## `shorts` Curation Stage (`M1.2r`) + +`curate_shorts` and `curate_and_write_shorts` (`src/curate_shorts.rs`) join `build_shorts`, `ProviderMappingTable`, and `write_shorts_dataset` into contract `ShortsParquetRow` records sorted and unique by `(listing_id, report_date)`. + +1. **Field rules:** + - Calls `build_shorts` unchanged (finite `>= 0.0` `shares_short` validation, non-finite optional `net_change`/`pct_float` sanitization to `None`, `-0.0` normalization, same-`(key, report_date)` deduplication, `+4` Canadian TSX business-day CIRO lag, and `known_at_micros = 17:00:00 America/Toronto` UTC microseconds). + - Resolves `(mapping_source, key, report_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by `(key, report_date)`). + - **Point-in-time mapping boundary:** `provider_mapping` is resolved strictly on `report_date` (the reporting period the short position describes), not on `known_at_date` (`+4` TSX business days later). + - Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO = "ceo_shorts"`) as `Cow::Borrowed`. +2. **Drop & collision policy (never panics or aborts on bad rows):** + - Rows whose `(mapping_source, key, report_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`. + - After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`, `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`) and drop the entire group when any of those fields differ (`listing_collision_dropped += g`). + - Exact conservation invariant in `CurateShortsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped`. + - Typed caller errors: `CurateShortsError` (`Shorts(ShortsError)`, `EmptyMappingSource`) and `CurateShortsWriteError` (`Curate(CurateShortsError)`, `Parquet(ParquetShortsError)`). A curate error in `curate_and_write_shorts` returns before invoking `write_shorts_dataset`, leaving `out_dir` untouched. + +### `bench-curate-shorts` + +Fixed-seed (`std`-only SplitMix64) benchmark over `2,000,000` source-keyed `ceoShorts` reports across `12,500` `String` keys per `1,000,000`-row block (`25,000` keys at `2,000,000` rows over the `218` semi-monthly dates `2017-04-15..=2026-04-30`, with per-key coprime-stride cursors guarded against exhaustion, date-ranged ticker reuse with an interior gap, unmapped keys, explicit builder duplicates, invalid `shares_short`/non-finite optional field slices, and identical/conflicting cross-key collisions), separately timing in-memory `curate_shorts` and Zstd Parquet `write_shorts_dataset` into a temp directory with footer row-count verification and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-shorts [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0xde3b3bd654c65ebe`): `cargo run --release -p curate-etl --offline -- bench-curate-shorts` + +- Input: `rows=2000000`, `keys=25000` +- Builder: `rows_out=1990174`, `invalid_shares=4005`, `nulled_net_change=1953`, `nulled_pct_float=1956`, `dup_collapsed=1937`, `dup_conflict_dropped=3884` +- Output: `rows_out=1936876` (`96.84%` retained), `listings_out=25000`, `files=1`, `row_groups=2`, `bytes=17721340`, `read_back_rows=1936876` +- Curation stats: `unmapped=43484`, `coll_collapsed=3410`, `coll_dropped=6404` +- Run 1: + - Stage (in-memory): `elapsed=1091.40 ms`, `throughput=1832514 rows/s`, `latency=545.70 ns/row`, `checksum=0xde3b3bd654c65ebe` + - Parquet write: `elapsed=224.75 ms`, `throughput=8617888 rows/s` + - Combined (stage → Parquet): `elapsed=1316.15 ms`, `throughput=1519586 rows/s` +- Run 2: + - Stage (in-memory): `elapsed=1002.51 ms`, `throughput=1994998 rows/s`, `latency=501.25 ns/row`, `checksum=0xde3b3bd654c65ebe` + - Parquet write: `elapsed=228.03 ms`, `throughput=8494083 rows/s` + - Combined (stage → Parquet): `elapsed=1230.53 ms`, `throughput=1625311 rows/s` diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 9681c77b..c7764bd1 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -4224,6 +4224,444 @@ pub fn run_curate_bars_benchmark(rows: usize) -> Result) -> std::fmt::Result { + match self { + Self::Write(err) => write!(f, "{err}"), + Self::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + capacity, + } => write!( + f, + "curate-shorts benchmark fixture exhausted unique semi-monthly date pool (capacity {capacity} dates/key) for key_idx={key_idx} while generating {rows} rows across {key_count} keys" + ), + } + } +} + +impl std::error::Error for CurateShortsBenchError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Write(err) => Some(err), + Self::FixtureDatePoolExhausted { .. } => None, + } + } +} + +impl From for CurateShortsBenchError { + fn from(err: crate::curate_shorts::CurateShortsWriteError) -> Self { + Self::Write(err) + } +} + +impl From for CurateShortsBenchError { + fn from(err: crate::curate_shorts::CurateShortsError) -> Self { + Self::Write(crate::curate_shorts::CurateShortsWriteError::from(err)) + } +} + +impl From for CurateShortsBenchError { + fn from(err: ParquetShortsError) -> Self { + Self::Write(crate::curate_shorts::CurateShortsWriteError::from(err)) + } +} + +/// Scales the benchmark key space in `12,500`-key blocks per `1,000,000` rows so larger batches +/// keep ordinary `(key, report_date)` pairs unique across the `218` semi-monthly dates +/// (`2017-04-15..=2026-04-30`) without exhausting the per-key date pool. +fn curate_shorts_bench_key_count(rows: usize) -> usize { + let blocks = rows.div_ceil(CURATE_SHORTS_BENCH_ROWS_PER_KEY_BLOCK).max(1); + CURATE_SHORTS_BENCH_KEY_COUNT.saturating_mul(blocks) +} + +/// Summary metrics produced by [`run_curate_shorts_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateShortsBenchReport { + pub rows: usize, + pub key_count: usize, + pub rows_out: usize, + pub listings_out: usize, + pub stage_elapsed_ms: f64, + pub stage_rows_per_sec: f64, + pub stage_ns_per_row: f64, + pub parquet_elapsed_ms: f64, + pub parquet_rows_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub checksum: u64, + pub stats: crate::curate_shorts::CurateShortsStats, +} + +struct CurateShortsBenchFixture { + reports: Vec>, + provider_mapping: ProviderMappingTable, + key_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_shorts_bench_fixture( + rows: usize, + key_count: usize, + date_pool_limit: Option, +) -> Result { + assert!( + key_count >= CURATE_SHORTS_BENCH_KEY_COUNT + && key_count % CURATE_SHORTS_BENCH_KEY_COUNT == 0, + "key_count ({key_count}) must be a positive multiple of {CURATE_SHORTS_BENCH_KEY_COUNT}" + ); + let scale = key_count / CURATE_SHORTS_BENCH_KEY_COUNT; + + let all_dates = semi_monthly_report_dates(); + let pool_len = date_pool_limit.map_or(all_dates.len(), |limit| limit.clamp(1, all_dates.len())); + let valid_from_start = ymd_to_epoch_days(2017, 1, 1).expect("valid start"); + let reuse_end = ymd_to_epoch_days(2021, 6, 30).expect("valid reuse end"); + let reuse_resume = ymd_to_epoch_days(2022, 1, 1).expect("valid reuse resume"); + + let single_range_end = 11_750 * scale; + let reuse_end_idx = 12_125 * scale; + let alias_end_idx = 12_250 * 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(100_000); + + let keys: Vec = (0..key_count).map(|i| format!("CEO{i:05}")).collect(); + + // Build provider_mapping (scaled proportionally per 12,500-key block): + // - 0..single_range_end: open-ended single range -> listing (i + 1) + // - single_range_end..reuse_end_idx: two ranges with H2-2021 gap -> listings (i + 1) and (i + reuse_lid_offset + 1) + // - reuse_end_idx..alias_end_idx: aliases of listings 1..=alias_count (cross-key collisions) + // - alias_end_idx..key_count: unmapped keys + let mut mapping_rows: Vec = + Vec::with_capacity(key_count + (reuse_end_idx - single_range_end) + 16); + for (i, key) in keys.iter().enumerate() { + if i < single_range_end { + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: None, + listing_id: (i + 1) as i32, + }); + } else if i < reuse_end_idx { + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: Some(reuse_end), + listing_id: (i + 1) as i32, + }); + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: reuse_resume, + valid_to: None, + listing_id: (i + reuse_lid_offset + 1) as i32, + }); + } else if i < alias_end_idx { + let alias_lid = (i - reuse_end_idx + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "ceo".to_string(), + source_id: key.clone(), + valid_from: valid_from_start, + valid_to: None, + listing_id: alias_lid, + }); + } + } + let provider_mapping = + ProviderMappingTable::from_rows(mapping_rows).expect("valid bench provider mapping"); + + let mut rng = SplitMix64::new(CURATE_SHORTS_BENCH_SEED); + let mut reports: Vec> = Vec::with_capacity(rows); + + // Per-key coprime-stride cursors with explicit usage guards guarantee unique + // (key, report_date) pairs across the 218 semi-monthly dates (53 is prime and coprime to + // 218 = 2 * 109) so all builder duplicates and cross-key collisions are injected explicitly. + const DATE_STRIDE: usize = 53; + let date_stride = if date_pool_limit.is_none() { + DATE_STRIDE + } else { + 1 + }; + let mut date_cursor: Vec = (0..key_count) + .map(|_| (rng.next_u64() as usize) % pool_len) + .collect(); + let mut date_used: Vec = vec![0; key_count]; + + let mut last_alias_pair: Option<(usize, CeoShortReport)> = None; + let mut last_ordinary_report: 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() { + prev.key = keys[reuse_end_idx + alias_idx].clone(); + if roll >= 2 { + prev.shares_short += 100.0; + injected_alias_conflict += 1; + } else { + injected_alias_identical += 1; + } + reports.push(prev); + continue; + } + } else if roll < 6 { + if let Some(mut prev) = last_ordinary_report.take() { + if roll == 5 { + prev.shares_short += 50.0; + injected_dup_conflict += 1; + } else { + injected_dup_identical += 1; + } + reports.push(prev); + continue; + } + } + + let key_idx = if roll < 12 { + (rng.next_u64() as usize) % alias_count + } else { + // Skip alias keys reuse_end_idx..alias_end_idx for ordinary reports 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 + } + }; + + if date_used[key_idx] >= pool_len { + return Err(CurateShortsBenchError::FixtureDatePoolExhausted { + rows, + key_count, + key_idx, + capacity: pool_len, + }); + } + date_used[key_idx] += 1; + let offset = date_cursor[key_idx]; + date_cursor[key_idx] = (offset + date_stride) % pool_len; + let report_date = all_dates[offset]; + + let is_invalid_shares = roll == 12 || roll == 13; + let shares_short = if roll == 12 { + -1.0 + } else if roll == 13 { + f64::NAN + } else { + ((rng.next_u64() % 5_000_000) + 100) as f64 + }; + let net_change = if roll == 14 { + Some(f64::NAN) + } else if rng.next_u64() % 5 == 0 { + None + } else { + Some(((rng.next_u64() % 200_001) as i64 - 100_000) as f64) + }; + let pct_float = if roll == 15 { + Some(f64::INFINITY) + } else if rng.next_u64() % 4 == 0 { + None + } else { + Some((rng.next_u64() % 3_500) as f64 * 0.01) + }; + + let rep = CeoShortReport { + key: keys[key_idx].clone(), + report_date, + shares_short, + net_change, + pct_float, + }; + if !is_invalid_shares { + if key_idx < alias_count { + last_alias_pair = Some((key_idx, rep.clone())); + } else if (alias_count..single_range_end).contains(&key_idx) { + last_ordinary_report = Some(rep.clone()); + } + } + reports.push(rep); + } + + Ok(CurateShortsBenchFixture { + reports, + provider_mapping, + key_count, + injected_dup_identical, + injected_dup_conflict, + injected_alias_identical, + injected_alias_conflict, + }) +} + +fn run_curate_shorts_benchmark_tracked( + rows: usize, +) -> Result<(CurateShortsBenchReport, PathBuf), CurateShortsBenchError> { + use crate::curate_shorts::{curate_shorts, CurateShortsStats, CurateShortsWriteError}; + + let temp = BenchTempDir::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-curate-shorts", + ) + .map_err(|(path, source)| { + CurateShortsBenchError::Write(CurateShortsWriteError::Parquet(ParquetShortsError::Io { + path, + source, + })) + })?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let mapping = ProviderMappingTable::default(); + let curated = curate_shorts( + std::iter::empty::>(), + "ceo", + &mapping, + )?; + let write_stats = + write_shorts_dataset(&temp.path, &curated.rows, ShortsWriteOptions::default())?; + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, 0)?; + drop(temp); + return Ok(( + CurateShortsBenchReport { + rows: 0, + key_count: CURATE_SHORTS_BENCH_KEY_COUNT, + rows_out: 0, + listings_out: 0, + stage_elapsed_ms: 0.0, + stage_rows_per_sec: 0.0, + stage_ns_per_row: 0.0, + parquet_elapsed_ms: 0.0, + parquet_rows_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum: 0, + stats: CurateShortsStats::default(), + }, + temp_path, + )); + } + + let key_count = curate_shorts_bench_key_count(rows); + let fixture = build_curate_shorts_bench_fixture(rows, key_count, None)?; + let fixture_key_count = fixture.key_count; + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping)?; + let stage_elapsed_secs = stage_start.elapsed().as_secs_f64(); + let stage_elapsed_ms = stage_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &curated.rows { + hash = mix_u64(hash, row.listing_id as u64); + hash = mix_u64(hash, row.report_date as u64); + hash = mix_u64(hash, row.known_at_micros as u64); + hash = mix_u64(hash, row.shares_short.to_bits()); + hash = match row.net_change { + Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), + None => mix_u64(hash, 0), + }; + hash = match row.pct_float { + Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), + None => mix_u64(hash, 0), + }; + hash = mix_str_u64(hash, row.source.as_ref()); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_shorts_dataset(&temp.path, &curated.rows, ShortsWriteOptions::default())?; + let parquet_elapsed_secs = parquet_start.elapsed().as_secs_f64(); + let parquet_elapsed_ms = parquet_elapsed_secs * 1_000.0; + + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, curated.rows.len())?; + + let (stage_rows_per_sec, stage_ns_per_row) = compute_rates(rows, stage_elapsed_secs); + let (parquet_rows_per_sec, _) = compute_rates(curated.rows.len(), parquet_elapsed_secs); + let total_elapsed_secs = stage_elapsed_secs + parquet_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + + let report = CurateShortsBenchReport { + rows, + key_count: fixture_key_count, + rows_out: curated.stats.rows_out, + listings_out: curated.stats.listings_out, + stage_elapsed_ms, + stage_rows_per_sec, + stage_ns_per_row, + parquet_elapsed_ms, + parquet_rows_per_sec, + total_elapsed_ms, + total_rows_per_sec, + files_written: write_stats.files_written, + row_groups_written: write_stats.row_groups_written, + bytes_written: write_stats.bytes_written, + read_back_rows, + checksum, + stats: curated.stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed `shorts` curation stage + Zstd Parquet write benchmark for `rows` +/// source-keyed `ceoShorts` reports across `12,500` `String` source keys per `1,000,000`-row block +/// (semi-monthly dates `2017-04-15..=2026-04-30`, with date-ranged ticker reuse, unmapped keys, +/// builder duplicates, invalid numeric slices, and cross-key collisions). +pub fn run_curate_shorts_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_shorts_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -5221,4 +5659,179 @@ mod tests { ); assert!(curated.stats.rows_out > 20_000 * 90 / 100); } + + #[test] + fn curate_shorts_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_curate_shorts_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_curate_shorts_benchmark_tracked(25_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, 25_000); + assert_eq!(a.stats.builder.rows_in, 25_000); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.read_back_rows, a.rows_out); + assert_eq!(a.listings_out, b.listings_out); + assert_eq!(a.files_written, 1); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.stage_rows_per_sec.is_finite() && a.stage_rows_per_sec >= 0.0); + assert!(a.parquet_rows_per_sec.is_finite() && a.parquet_rows_per_sec >= 0.0); + assert!(a.total_rows_per_sec.is_finite() && a.total_rows_per_sec >= 0.0); + assert!(a.stats.builder.dropped_invalid_shares_short > 0); + assert!(a.stats.builder.nulled_invalid_net_change > 0); + assert!(a.stats.builder.nulled_invalid_pct_float > 0); + assert!(a.stats.builder.duplicate_collapsed > 0); + assert!(a.stats.builder.duplicate_conflict_dropped > 0); + assert_eq!( + a.stats.builder.rows_in, + a.stats.builder.rows_out + + a.stats.builder.dropped_invalid_shares_short + + a.stats.builder.duplicate_collapsed + + a.stats.builder.duplicate_conflict_dropped + ); + assert_eq!(a.stats.rows_in, a.stats.builder.rows_out); + assert_eq!( + a.stats.rows_in, + a.stats.rows_out + + a.stats.dropped_unmapped + + a.stats.listing_collision_collapsed + + a.stats.listing_collision_dropped + ); + assert!(a.stats.dropped_unmapped > 0); + assert!(a.stats.listing_collision_collapsed > 0); + assert!(a.stats.listing_collision_dropped > 0); + assert!( + a.rows_out > a.rows * 90 / 100, + "expected >90% retention with unique ordinary pairs, got {}/{}", + a.rows_out, + a.rows + ); + } + + #[test] + fn curate_shorts_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_shorts_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listings_out, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.stage_rows_per_sec, 0.0); + assert_eq!(report.parquet_rows_per_sec, 0.0); + assert_eq!(report.total_rows_per_sec, 0.0); + } + + #[test] + fn curate_shorts_benchmark_distinguishes_deliberate_duplicates_from_cursor_exhaustion() { + use crate::curate_shorts::curate_shorts; + + // 1. Below cursor exhaustion: every builder duplicate and cross-key listing collision + // must match the explicitly injected counts with zero accidental cursor wraps. + let fixture = + build_curate_shorts_bench_fixture(10_000, CURATE_SHORTS_BENCH_KEY_COUNT, Some(8)) + .expect("10,000 rows across 12,500 keys fits within 8 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_shorts(fixture.reports, "ceo", &fixture.provider_mapping).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. + let err = match build_curate_shorts_bench_fixture( + 120_000, + CURATE_SHORTS_BENCH_KEY_COUNT, + Some(4), + ) { + Ok(_) => panic!("120,000 rows across 12,500 keys must exhaust a 4-date pool"), + Err(err) => err, + }; + assert!( + matches!( + err, + CurateShortsBenchError::FixtureDatePoolExhausted { + rows: 120_000, + key_count: CURATE_SHORTS_BENCH_KEY_COUNT, + capacity: 4, + .. + } + ), + "expected FixtureDatePoolExhausted, got {err:?}" + ); + let msg = err.to_string(); + assert!( + msg.contains("4") && msg.contains("120000") && msg.contains("12500"), + "error message should explain the fixture limit, got: {msg}" + ); + } + + #[test] + fn curate_shorts_benchmark_scales_key_space_for_large_batches() { + use crate::curate_shorts::curate_shorts; + + assert_eq!(curate_shorts_bench_key_count(0), 12_500); + assert_eq!(curate_shorts_bench_key_count(1_000_000), 12_500); + assert_eq!(curate_shorts_bench_key_count(1_000_001), 25_000); + assert_eq!(curate_shorts_bench_key_count(2_000_000), 25_000); + assert_eq!(curate_shorts_bench_key_count(5_000_000), 62_500); + + let scaled_keys = curate_shorts_bench_key_count(2_000_000); + let fixture = build_curate_shorts_bench_fixture(25_000, scaled_keys, None).unwrap(); + assert_eq!(fixture.key_count, 25_000); + + let curated = curate_shorts(fixture.reports, "ceo", &fixture.provider_mapping).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 > 25_000 * 90 / 100); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index e7d69fbb..bede9099 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -10,7 +10,7 @@ use crate::bench::{ 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_CURATE_BARS_BENCH_ROWS, + DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -33,6 +33,7 @@ pub enum CliAction { BenchParquetAdj(usize), BenchParquetCorporateActions(usize), BenchCurateBars(usize), + BenchCurateShorts(usize), } /// Formats full help text including binary name and version. @@ -57,7 +58,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {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})\n\ - {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})" + {name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\ + {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})" ) } @@ -81,7 +83,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-fx [rows]\n\ {name} bench-parquet-adj [rows]\n\ {name} bench-parquet-corporate-actions [rows]\n\ - {name} bench-curate-bars [rows]" + {name} bench-curate-bars [rows]\n\ + {name} bench-curate-shorts [rows]" ) } @@ -244,6 +247,18 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-bars", _, ..] => { Err("too many arguments for bench-curate-bars".to_string()) } + ["bench-curate-shorts"] => { + Ok(CliAction::BenchCurateShorts(DEFAULT_CURATE_SHORTS_BENCH_ROWS)) + } + ["bench-curate-shorts", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateShorts(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-shorts", _, ..] => { + Err("too many arguments for bench-curate-shorts".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -531,6 +546,7 @@ mod tests { assert!(full.contains("bench-parquet-adj")); assert!(full.contains("bench-parquet-corporate-actions")); assert!(full.contains("bench-curate-bars")); + assert!(full.contains("bench-curate-shorts")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -548,6 +564,7 @@ mod tests { assert!(short.contains("bench-parquet-adj")); assert!(short.contains("bench-parquet-corporate-actions")); assert!(short.contains("bench-curate-bars")); + assert!(short.contains("bench-curate-shorts")); } #[test] @@ -565,4 +582,22 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-bars", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-bars", "10", "20"])).is_err()); } + + #[test] + fn parses_and_validates_bench_curate_shorts_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-shorts"])), + Ok(CliAction::BenchCurateShorts( + DEFAULT_CURATE_SHORTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-shorts", "100000"])), + Ok(CliAction::BenchCurateShorts(100_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-shorts", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-shorts", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-shorts", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-shorts", "10", "20"])).is_err()); + } } diff --git a/tools/curate-etl/src/curate_shorts.rs b/tools/curate-etl/src/curate_shorts.rs new file mode 100644 index 00000000..d34e858f --- /dev/null +++ b/tools/curate-etl/src/curate_shorts.rs @@ -0,0 +1,315 @@ +//! Pure, in-memory `shorts` curation stage joining [`crate::shorts::build_shorts`], +//! [`crate::provider_mapping::ProviderMappingTable`], and +//! [`crate::parquet_shorts::write_shorts_dataset`] into contract [`ShortsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls [`build_shorts`] unchanged to validate `shares_short`, sanitize non-finite optional +//! fields, deduplicate same-`(key, report_date)` reports, apply the locked `+4` Canadian TSX +//! business-day CIRO lag, and stamp `known_at_utc_micros = 17:00:00 America/Toronto` plus +//! `source = SHORTS_SOURCE_CEO` (`"ceo_shorts"`). +//! - Resolves each output row's `(mapping_source, key, report_date)` to a permanent +//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`] +//! (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by +//! `(key, report_date)`). +//! - **Point-in-time mapping boundary (`report_date`, not `known_at_date`):** `provider_mapping` +//! is resolved strictly on `report_date` (the reporting period the short position describes), +//! not on `known_at_date` (when CIRO disseminates the report `+4` business days later). A ticker +//! that changes listing or delists between `report_date` and `known_at_date` still belongs to +//! the listing that was active on `report_date`. +//! - Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO` = `"ceo_shorts"`) +//! as `Cow::Borrowed`. +//! - Re-sorts mapped rows in place by `(listing_id, report_date)` and compacts cross-`key` +//! collisions on the same `(listing_id, report_date)`: bitwise-identical +//! `(known_at_micros, shares_short, net_change, pct_float)` collapses to one row +//! (`listing_collision_collapsed`), while any conflict drops the entire group +//! (`listing_collision_dropped`), mirroring `build_shorts`'s duplicate policy. + +use std::borrow::Cow; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::parquet_shorts::{ + write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, + ShortsWriteStats, +}; +use crate::provider_mapping::ProviderMappingTable; +use crate::shorts::{build_shorts, CeoShortReport, ShortsError, ShortsStats}; + +/// Accounting summary produced alongside [`CurateShortsOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.rows_out` +/// - `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped` +/// - `builder` independently satisfies all [`ShortsStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateShortsStats { + pub builder: ShortsStats, + pub rows_in: usize, + pub rows_out: usize, + pub listings_out: usize, + pub dropped_unmapped: usize, + pub listing_collision_collapsed: usize, + pub listing_collision_dropped: usize, +} + +/// Output of [`curate_shorts`]: contract Parquet rows sorted and unique by +/// `(listing_id, report_date)` and full stage + builder stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateShortsOutput { + pub rows: Vec, + pub stats: CurateShortsStats, +} + +/// Typed caller errors returned by [`curate_shorts`]. +/// +/// Bad single rows (unmapped dates and cross-`key` collisions) are dropped and counted in +/// [`CurateShortsStats`] rather than aborting the stage. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurateShortsError { + /// Error propagated from [`build_shorts`] (e.g., `report_date` outside `2008..=2030`). + Shorts(ShortsError), + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CurateShortsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::Shorts(err) => write!(f, "{err}"), + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CurateShortsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Shorts(err) => Some(err), + Self::EmptyMappingSource => None, + } + } +} + +impl From for CurateShortsError { + fn from(err: ShortsError) -> Self { + Self::Shorts(err) + } +} + +/// Combined stats returned by [`curate_and_write_shorts`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CurateShortsWriteReport { + pub curate_stats: CurateShortsStats, + pub write_stats: ShortsWriteStats, +} + +/// Typed error returned by [`curate_and_write_shorts`]. +#[derive(Debug)] +pub enum CurateShortsWriteError { + Curate(CurateShortsError), + Parquet(ParquetShortsError), +} + +impl fmt::Display for CurateShortsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "shorts curation failed: {err}"), + Self::Parquet(err) => write!(f, "shorts Parquet write failed: {err}"), + } + } +} + +impl Error for CurateShortsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateShortsWriteError { + fn from(err: CurateShortsError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateShortsWriteError { + fn from(err: ParquetShortsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn parquet_row_values_bit_eq(a: &ShortsParquetRow, b: &ShortsParquetRow) -> bool { + a.known_at_micros == b.known_at_micros + && a.shares_short.to_bits() == b.shares_short.to_bits() + && a.net_change.map(f64::to_bits) == b.net_change.map(f64::to_bits) + && a.pct_float.map(f64::to_bits) == b.pct_float.map(f64::to_bits) +} + +/// Pure `shorts` curation stage: validates, deduplicates, and point-in-time lags source-keyed +/// `ceoShorts` reports via [`build_shorts`], resolves `(mapping_source, key, report_date) -> +/// listing_id` through `provider_mapping`, and emits contract [`ShortsParquetRow`]s sorted and +/// unique by `(listing_id, report_date)`. +/// +/// Mapping lookup uses `report_date` (the reporting period the short position describes), not +/// `known_at_date`. Rows with no covering mapping range are dropped into `dropped_unmapped`. +/// +/// After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same +/// `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`, +/// `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`) +/// and drop the entire group when any of those fields differ (`listing_collision_dropped += g`). +pub fn curate_shorts( + reports: I, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> Result +where + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateShortsError::EmptyMappingSource); + } + + let built = build_shorts(reports)?; + + let mut stats = CurateShortsStats { + builder: built.stats, + rows_in: built.rows.len(), + ..CurateShortsStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(built.rows.len()); + let total_built = built.rows.len(); + let mut idx = 0usize; + + while idx < total_built { + let run_start = idx; + let run_key = &built.rows[run_start].key; + idx += 1; + while idx < total_built && built.rows[idx].key == *run_key { + idx += 1; + } + let run_end = idx; + + let mut cursor = mapping.cursor_for(mapping_source, run_key.as_ref()); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += run_end - run_start; + continue; + } + + for row in &built.rows[run_start..run_end] { + let Some(listing_id) = cursor.resolve(row.report_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + rows.push(ShortsParquetRow { + listing_id, + report_date: row.report_date, + known_at_micros: row.known_at_utc_micros, + shares_short: row.shares_short, + net_change: row.net_change, + pct_float: row.pct_float, + source: Cow::Borrowed(row.source), + }); + } + } + + // Free builder rows before sorting/compacting mapped contract rows to cut peak RAM. + drop(built.rows); + + rows.sort_unstable_by(|a, b| { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.report_date.cmp(&b.report_date)) + }); + + let mut write_idx = 0usize; + let mut read_idx = 0usize; + let total_mapped = rows.len(); + let mut last_listing_id: Option = None; + + while read_idx < total_mapped { + let listing_id = rows[read_idx].listing_id; + let report_date = rows[read_idx].report_date; + let mut group_end = read_idx + 1; + while group_end < total_mapped + && rows[group_end].listing_id == listing_id + && rows[group_end].report_date == report_date + { + group_end += 1; + } + let group_len = group_end - read_idx; + + if group_len == 1 { + if write_idx != read_idx { + rows.swap(write_idx, read_idx); + } + if last_listing_id != Some(listing_id) { + stats.listings_out += 1; + last_listing_id = Some(listing_id); + } + write_idx += 1; + } else { + let first = &rows[read_idx]; + let all_identical = rows[read_idx + 1..group_end] + .iter() + .all(|other| parquet_row_values_bit_eq(first, other)); + + if all_identical { + stats.listing_collision_collapsed += group_len - 1; + if write_idx != read_idx { + rows.swap(write_idx, read_idx); + } + if last_listing_id != Some(listing_id) { + stats.listings_out += 1; + last_listing_id = Some(listing_id); + } + write_idx += 1; + } else { + stats.listing_collision_dropped += group_len; + } + } + + read_idx = group_end; + } + rows.truncate(write_idx); + stats.rows_out = rows.len(); + + Ok(CurateShortsOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_shorts`] and publishing the resulting contract rows +/// via [`write_shorts_dataset`] to `/shorts/part.parquet`. +/// +/// Any [`CurateShortsError`] returns before [`write_shorts_dataset`] is invoked, leaving +/// `out_dir` untouched. +pub fn curate_and_write_shorts( + out_dir: P, + reports: I, + mapping_source: &str, + mapping: &ProviderMappingTable, + options: ShortsWriteOptions, +) -> Result +where + P: AsRef, + K: Ord + Clone + AsRef, + I: IntoIterator>, +{ + let curated = curate_shorts(reports, mapping_source, mapping)?; + let write_stats = write_shorts_dataset(out_dir, &curated.rows, options)?; + Ok(CurateShortsWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_shorts_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_shorts_tests.rs b/tools/curate-etl/src/curate_shorts_tests.rs new file mode 100644 index 00000000..f330f311 --- /dev/null +++ b/tools/curate-etl/src/curate_shorts_tests.rs @@ -0,0 +1,782 @@ +use std::borrow::Cow; +use std::error::Error; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::provider_mapping::ProviderMappingRow; +use crate::shorts::{build_shorts, SHORTS_SOURCE_CEO}; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-curate-shorts-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn report( + key: &str, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, +) -> CeoShortReport { + CeoShortReport { + key: key.to_string(), + report_date, + shares_short, + net_change, + pct_float, + } +} + +fn map_row( + source: &str, + source_id: &str, + valid_from: i32, + valid_to: Option, + listing_id: i32, +) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: source_id.to_string(), + valid_from, + valid_to, + listing_id, + } +} + +fn assert_conservation_and_order(out: &CurateShortsOutput) { + let s = &out.stats; + assert_eq!( + s.rows_in, s.builder.rows_out, + "rows_in != builder.rows_out: {s:?}" + ); + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_unmapped + + s.listing_collision_collapsed + + s.listing_collision_dropped, + "curate accounting conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.rows_in, + s.builder.rows_out + + s.builder.dropped_invalid_shares_short + + s.builder.duplicate_collapsed + + s.builder.duplicate_conflict_dropped, + "builder accounting conservation mismatch: {s:?}" + ); + + let mut distinct_listings = 0usize; + let mut prev_listing: Option = None; + for row in &out.rows { + assert_eq!(row.source.as_ref(), SHORTS_SOURCE_CEO); + if prev_listing != Some(row.listing_id) { + distinct_listings += 1; + prev_listing = Some(row.listing_id); + } + } + assert_eq!(s.listings_out, distinct_listings); + + for pair in out.rows.windows(2) { + assert!( + (pair[0].listing_id, pair[0].report_date) < (pair[1].listing_id, pair[1].report_date), + "output rows must be strictly sorted and unique by (listing_id, report_date): {:?} vs {:?}", + (pair[0].listing_id, pair[0].report_date), + (pair[1].listing_id, pair[1].report_date), + ); + } +} + +fn read_parquet_rows(path: &Path) -> (usize, Vec) { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let footer_rows = metadata.file_metadata().num_rows() as usize; + let mut out = Vec::with_capacity(footer_rows); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let report_date = read_i32_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let shares_short = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let net_change = read_opt_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let pct_float = read_opt_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(ShortsParquetRow { + listing_id: listing_id[i], + report_date: report_date[i], + known_at_micros: known_at_micros[i], + shares_short: shares_short[i], + net_change: net_change[i], + pct_float: pct_float[i], + source: Cow::Owned(source[i].clone()), + }); + } + } + (footer_rows, out) +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values +} + +fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec> { + let mut raw_values = Vec::with_capacity(expected); + let mut def_levels = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, levels) = r + .read_records(expected, Some(&mut def_levels), None, &mut raw_values) + .unwrap(); + assert_eq!(records, expected); + assert_eq!(levels, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + let mut out = Vec::with_capacity(expected); + let mut val_idx = 0usize; + for lvl in def_levels { + if lvl == 1 { + out.push(Some(raw_values[val_idx])); + val_idx += 1; + } else { + out.push(None); + } + } + assert_eq!(val_idx, raw_values.len()); + out +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +fn assert_row_bitwise_eq(actual: &ShortsParquetRow, expected: &ShortsParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source, expected.source); +} + +#[test] +fn happy_path_two_ceo_symbols_resort_by_listing_id_and_preserve_builder_known_at_and_source() { + // Assign RY (lexicographically after ABX) a smaller listing_id (10 vs 20) to prove + // post-mapping re-sorting by (listing_id, report_date). + let d_est = day(2024, 1, 15); // Winter (EST) + let d_edt = day(2024, 7, 15); // Summer (EDT) + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "ABX", day(2015, 1, 1), None, 20), + map_row("ceo", "RY", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + let input = vec![ + report("ABX", d_est, 12_500_000.0, Some(-250_000.0), Some(0.75)), + report("ABX", d_edt, 13_100_000.0, Some(600_000.0), None), + report("RY", d_est, 8_200_000.0, None, Some(0.60)), + report("RY", d_edt, 8_050_000.0, Some(-150_000.0), Some(0.58)), + ]; + + let built = build_shorts(input.clone()).unwrap(); + let out = curate_shorts(input, "ceo", &mapping).unwrap(); + + assert_conservation_and_order(&out); + assert_eq!(out.stats.builder, built.stats); + assert_eq!(out.stats.rows_in, 4); + assert_eq!(out.stats.rows_out, 4); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.stats.dropped_unmapped, 0); + assert_eq!(out.stats.listing_collision_collapsed, 0); + assert_eq!(out.stats.listing_collision_dropped, 0); + + // Listing 10 (RY) comes first despite "RY" > "ABX". + let ry_built: Vec<_> = built.rows.iter().filter(|r| r.key == "RY").collect(); + let abx_built: Vec<_> = built.rows.iter().filter(|r| r.key == "ABX").collect(); + assert_eq!(ry_built.len(), 2); + assert_eq!(abx_built.len(), 2); + + for (actual, expected) in out.rows[0..2].iter().zip(ry_built.iter()) { + assert_eq!(actual.listing_id, 10); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_utc_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source.as_ref(), SHORTS_SOURCE_CEO); + assert_eq!(actual.source.as_ref(), "ceo_shorts"); + } + + for (actual, expected) in out.rows[2..4].iter().zip(abx_built.iter()) { + assert_eq!(actual.listing_id, 20); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_utc_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source.as_ref(), SHORTS_SOURCE_CEO); + } +} + +#[test] +fn date_ranged_ticker_reuse_resolves_on_report_date_and_counts_unmapped_drops() { + // Ticker "REUSE": + // listing 100: 2020-01-01 ..= 2022-06-15 + // interior gap: 2022-06-16 ..= 2022-07-04 + // listing 200: 2022-07-05 ..= 2024-12-31 + // + // Boundary proofs (report_date vs known_at_date): + // - 2022-06-15 (report_date == valid_to): known_at_date is +4 TSX bdays later (2022-06-21), + // which falls in the gap -> MUST still resolve to listing 100 on report_date. + // - 2022-06-30 (report_date in gap): known_at_date is +4 TSX bdays later (2022-07-07, skipping + // Canada Day Jul 1), which falls inside listing 200's range -> MUST drop as unmapped. + let d_pre = day(2019, 12, 31); + let d_r1_start = day(2020, 1, 15); + let d_r1_end = day(2022, 6, 15); + let d_gap_straddling_r2 = day(2022, 6, 30); + let d_r2_start = day(2022, 7, 15); + let d_r2_end = day(2024, 12, 31); + let d_post = day(2025, 1, 15); + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "REUSE", day(2020, 1, 1), Some(d_r1_end), 100), + map_row("ceo", "REUSE", day(2022, 7, 5), Some(d_r2_end), 200), + // Different mapping_source must not match "ceo" + map_row("eod", "WRONGSRC", day(2015, 1, 1), None, 300), + ]) + .unwrap(); + + let input = vec![ + report("REUSE", d_pre, 1_000.0, None, None), // unmapped (before first range) + report("REUSE", d_r1_start, 2_000.0, Some(100.0), None), // -> 100 + report("REUSE", d_r1_end, 3_000.0, Some(1_000.0), None), // -> 100 (report_date == valid_to) + report("REUSE", d_gap_straddling_r2, 4_000.0, None, None), // unmapped (report_date in gap) + report("REUSE", d_r2_start, 5_000.0, Some(-200.0), None), // -> 200 + report("REUSE", d_r2_end, 6_000.0, Some(1_000.0), None), // -> 200 (report_date == valid_to) + report("REUSE", d_post, 7_000.0, None, None), // unmapped (after last range) + report("UNKNOWN", d_r2_start, 8_000.0, None, None), // unmapped (unknown key) + report("WRONGSRC", d_r2_start, 9_000.0, None, None), // unmapped (wrong mapping_source) + ]; + + let out = curate_shorts(input, "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert_eq!(out.stats.rows_in, 9); + assert_eq!(out.stats.rows_out, 4); + assert_eq!(out.stats.listings_out, 2); + assert_eq!(out.stats.dropped_unmapped, 5); + + let keys: Vec<(i32, i32)> = out.rows.iter().map(|r| (r.listing_id, r.report_date)).collect(); + assert_eq!( + keys, + vec![ + (100, d_r1_start), + (100, d_r1_end), + (200, d_r2_start), + (200, d_r2_end), + ] + ); +} + +#[test] +fn cross_key_collisions_collapse_bitwise_identical_and_drop_conflicting_groups() { + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 31); + let d3 = day(2024, 4, 15); + let d4 = day(2024, 4, 30); + let d5 = day(2024, 5, 15); + let d6 = day(2024, 5, 31); + let d7 = day(2024, 6, 15); + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "A", day(2020, 1, 1), None, 10), + map_row("ceo", "B", day(2020, 1, 1), None, 10), + map_row("ceo", "C", day(2020, 1, 1), None, 10), + map_row("ceo", "X", day(2020, 1, 1), None, 20), + map_row("ceo", "Y", day(2020, 1, 1), None, 20), + ]) + .unwrap(); + + let input = vec![ + // d1 on listing 10: 3-way identical (with Some optionals and -0.0 normalized to 0.0) -> collapse (+2) + report("A", d1, 0.0, Some(-0.0), Some(1.25)), + report("B", d1, -0.0, Some(0.0), Some(1.25)), + report("C", d1, 0.0, Some(0.0), Some(1.25)), + // d2 on listing 10: 2-way identical with None optionals -> collapse (+1) + report("A", d2, 50_000.0, None, None), + report("B", d2, 50_000.0, None, None), + // d3 on listing 10: differing shares_short -> drop entire group of 3 + report("A", d3, 10_000.0, Some(100.0), Some(0.5)), + report("B", d3, 10_000.0, Some(100.0), Some(0.5)), + report("C", d3, 10_001.0, Some(100.0), Some(0.5)), + // d4 on listing 10: differing net_change (Some vs Some) -> drop group of 2 + report("A", d4, 10_000.0, Some(100.0), Some(0.5)), + report("B", d4, 10_000.0, Some(101.0), Some(0.5)), + // d5 on listing 10: differing net_change (Some vs None) -> drop group of 2 + report("A", d5, 10_000.0, Some(100.0), Some(0.5)), + report("B", d5, 10_000.0, None, Some(0.5)), + // d6 on listing 10: differing pct_float (Some vs Some) -> drop group of 2 + report("A", d6, 10_000.0, Some(100.0), Some(0.5)), + report("B", d6, 10_000.0, Some(100.0), Some(0.6)), + // d7 on listing 10: differing pct_float (Some vs None) -> drop group of 2 + report("A", d7, 10_000.0, Some(100.0), Some(0.5)), + report("B", d7, 10_000.0, Some(100.0), None), + // d1 on listing 20: conflicting shares_short -> listing 20 loses all rows + report("X", d1, 5_000.0, None, None), + report("Y", d1, 5_001.0, None, None), + ]; + + let out = curate_shorts(input, "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert_eq!(out.stats.rows_in, 18); + assert_eq!(out.stats.rows_out, 2); + assert_eq!(out.stats.listings_out, 1); // listing 20 lost its only date + assert_eq!(out.stats.listing_collision_collapsed, 3); + assert_eq!(out.stats.listing_collision_dropped, 13); + + assert_eq!(out.rows[0].listing_id, 10); + assert_eq!(out.rows[0].report_date, d1); + assert_eq!(out.rows[0].shares_short.to_bits(), 0.0_f64.to_bits()); + assert_eq!(out.rows[0].net_change.map(f64::to_bits), Some(0.0_f64.to_bits())); + assert_eq!(out.rows[0].pct_float, Some(1.25)); + + assert_eq!(out.rows[1].listing_id, 10); + assert_eq!(out.rows[1].report_date, d2); + assert_eq!(out.rows[1].shares_short, 50_000.0); + assert_eq!(out.rows[1].net_change, None); + assert_eq!(out.rows[1].pct_float, None); +} + +#[test] +fn typed_caller_and_builder_errors_and_empty_input() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "RY", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + // Blank/whitespace mapping_source returns EmptyMappingSource (even when input has bad dates). + for blank in ["", " ", "\t\n"] { + let err = curate_shorts( + [report("RY", day(2007, 12, 31), 100.0, None, None)], + blank, + &mapping, + ) + .unwrap_err(); + assert_eq!(err, CurateShortsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + } + + // Builder DateOutOfRange propagates for pre-2008 and post-2030 rollover dates. + for bad_date in [day(2007, 12, 31), day(2030, 12, 30)] { + let err = curate_shorts( + [report("RY", bad_date, 100.0, None, None)], + "ceo", + &mapping, + ) + .unwrap_err(); + assert!(matches!( + err, + CurateShortsError::Shorts(ShortsError::DateOutOfRange { .. }) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("outside supported calendar range")); + } + + // Empty input returns empty rows and zeroed stats. + let empty = curate_shorts( + std::iter::empty::>(), + "ceo", + &mapping, + ) + .unwrap(); + assert_conservation_and_order(&empty); + assert_eq!(empty.stats, CurateShortsStats::default()); + assert!(empty.rows.is_empty()); +} + +#[test] +fn mixed_fixture_conservation_and_permutation_invariance() { + let d1 = day(2024, 2, 15); + let d2 = day(2024, 2, 29); + let d3 = day(2024, 3, 15); + + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "S1", day(2020, 1, 1), None, 5), + map_row("ceo", "S1_ALIAS", day(2020, 1, 1), None, 5), + ]) + .unwrap(); + + let reports = vec![ + // Builder identical duplicate on S1 d1 (collapses in builder) + identical cross-key alias (collapses in curate) + report("S1", d1, 100_000.0, Some(5_000.0), Some(1.5)), + report("S1", d1, 100_000.0, Some(5_000.0), Some(1.5)), + report("S1_ALIAS", d1, 100_000.0, Some(5_000.0), Some(1.5)), + // Cross-key conflicting collision on (5, d2) + report("S1", d2, 200_000.0, Some(10_000.0), None), + report("S1_ALIAS", d2, 200_000.0, Some(10_001.0), None), + // Builder invalid shares_short (dropped in builder before curate) + report("S1", d3, -10.0, None, None), + // Builder non-finite optional fields (sanitized to None in builder) + report("S1", d3, 50_000.0, Some(f64::NAN), Some(f64::INFINITY)), + // Unmapped key + report("GHOST", d3, 25_000.0, None, None), + ]; + + let raw_built = build_shorts(reports.clone()).unwrap(); + let curated = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.builder, raw_built.stats); + assert_eq!(curated.stats.builder.dropped_invalid_shares_short, 1); + assert_eq!(curated.stats.builder.nulled_invalid_net_change, 1); + assert_eq!(curated.stats.builder.nulled_invalid_pct_float, 1); + assert_eq!(curated.stats.builder.duplicate_collapsed, 1); + assert_eq!(curated.stats.rows_in, 6); + assert_eq!(curated.stats.dropped_unmapped, 1); + assert_eq!(curated.stats.listing_collision_collapsed, 1); + assert_eq!(curated.stats.listing_collision_dropped, 2); + assert_eq!(curated.stats.rows_out, 2); + assert_eq!(curated.stats.listings_out, 1); + + // Reversed input yields bitwise-identical rows and stats. + let mut reversed = reports; + reversed.reverse(); + let curated_rev = curate_shorts(reversed, "ceo", &mapping).unwrap(); + assert_eq!(curated_rev.stats, curated.stats); + assert_eq!(curated_rev.rows.len(), curated.rows.len()); + for (a, b) in curated_rev.rows.iter().zip(curated.rows.iter()) { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn fixed_seed_randomized_fixture_satisfies_conservation_and_parquet_writer_contract() { + struct SplitMix64(u64); + impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + } + + let dates: Vec = (2018..=2025) + .flat_map(|y| { + (1..=12).flat_map(move |m| { + let mid = day(y, m, 15); + let end = if m == 12 { + day(y + 1, 1, 1) - 1 + } else { + day(y, m + 1, 1) - 1 + }; + [mid, end] + }) + }) + .collect(); + + let mut mapping_rows = Vec::new(); + // 0..20: single range -> listing (i + 1) + for i in 0..20 { + mapping_rows.push(map_row("ceo", &format!("K{i:02}"), day(2018, 1, 1), None, i + 1)); + } + // 20..25: ticker reuse with interior gap -> listings 101..105 / 201..205 + for i in 0..5 { + let key = format!("K{:02}", 20 + i); + mapping_rows.push(map_row( + "ceo", + &key, + day(2018, 1, 1), + Some(day(2021, 6, 30)), + 101 + i, + )); + mapping_rows.push(map_row( + "ceo", + &key, + day(2022, 1, 1), + None, + 201 + i, + )); + } + // 25..30: aliases of listings 1..=5 + for i in 0..5 { + mapping_rows.push(map_row( + "ceo", + &format!("K{:02}", 25 + i), + day(2018, 1, 1), + None, + i + 1, + )); + } + // 30..35: unmapped keys + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + + let mut rng = SplitMix64(0x570C_4B07_5407_7E57); + let mut reports = Vec::with_capacity(2_500); + for _ in 0..2_500 { + let key_idx = (rng.next_u64() % 35) as usize; + let report_date = dates[(rng.next_u64() as usize) % dates.len()]; + let roll = rng.next_u64() % 100; + let shares_short = if roll == 0 { + -1.0 + } else if roll == 1 { + f64::NAN + } else { + // Small quantized values so collisions have both identical and conflicting cases + ((rng.next_u64() % 4) * 1_000) as f64 + }; + let net_change = match rng.next_u64() % 5 { + 0 => None, + 1 => Some(f64::NAN), + v => Some((v as f64 - 3.0) * 500.0), + }; + let pct_float = match rng.next_u64() % 5 { + 0 => None, + 1 => Some(f64::INFINITY), + v => Some(v as f64 * 0.25), + }; + reports.push(CeoShortReport { + key: format!("K{key_idx:02}"), + report_date, + shares_short, + net_change, + pct_float, + }); + } + + let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert!(out.stats.rows_out > 0); + assert!(out.stats.dropped_unmapped > 0); + assert!(out.stats.listing_collision_collapsed > 0); + assert!(out.stats.listing_collision_dropped > 0); + + // Stage output must always satisfy write_shorts_dataset's strict contract. + let tmp = TempDirGuard::new("rand-parquet"); + let write_stats = + write_shorts_dataset(tmp.path(), &out.rows, ShortsWriteOptions::default()).unwrap(); + assert_eq!(write_stats.rows_written, out.rows.len()); + assert_eq!(write_stats.files_written, 1); +} + +#[test] +fn curate_and_write_shorts_round_trips_parquet_and_protects_out_dir_on_error() { + let tmp = TempDirGuard::new("round-trip"); + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "ABX", day(2015, 1, 1), None, 20), + map_row("ceo", "RY", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + let reports = vec![ + report("ABX", day(2024, 1, 15), 12_500_000.0, Some(-250_000.0), Some(0.75)), + report("ABX", day(2024, 7, 15), 13_100_000.0, Some(600_000.0), None), + report("RY", day(2024, 1, 15), 8_200_000.0, None, Some(0.60)), + report("RY", day(2024, 7, 15), 8_050_000.0, Some(-150_000.0), Some(0.58)), + ]; + + let stage = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + let report_res = curate_and_write_shorts( + tmp.path(), + reports.clone(), + "ceo", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report_res.curate_stats, stage.stats); + assert_eq!(report_res.write_stats.rows_written, stage.rows.len()); + assert_eq!(report_res.write_stats.files_written, 1); + + let shorts_dir = tmp.path().join("shorts"); + let part_path = shorts_dir.join("part.parquet"); + assert!(part_path.exists(), "expected {}", part_path.display()); + + // No transient .write.lock, .tmp, or .bak files remain. + for entry in fs::read_dir(&shorts_dir).expect("read shorts dir") { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!( + name, "part.parquet", + "unexpected transient file '{name}' in {}", + shorts_dir.display() + ); + } + + let (footer_rows, read_back) = read_parquet_rows(&part_path); + assert_eq!(footer_rows, stage.stats.rows_out); + assert_eq!(read_back.len(), stage.rows.len()); + for (actual, expected) in read_back.iter().zip(stage.rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + + // Curate error with pre-existing part.parquet leaves the live file byte-for-byte intact. + let original_bytes = fs::read(&part_path).expect("read original part.parquet"); + let curate_err = curate_and_write_shorts( + tmp.path(), + reports, + " ", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + curate_err, + CurateShortsWriteError::Curate(CurateShortsError::EmptyMappingSource) + )); + assert!(curate_err.source().is_some()); + assert!(curate_err.to_string().contains("curation failed")); + assert_eq!(fs::read(&part_path).unwrap(), original_bytes); + + // Curate error on a fresh directory creates no shorts/ directory at all. + let fresh_tmp = TempDirGuard::new("curate-err-fresh"); + let date_err = curate_and_write_shorts( + fresh_tmp.path(), + [report("RY", day(2007, 12, 31), 100.0, None, None)], + "ceo", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + date_err, + CurateShortsWriteError::Curate(CurateShortsError::Shorts(ShortsError::DateOutOfRange { .. })) + )); + assert!(!fresh_tmp.path().join("shorts").exists()); + + // ParquetShortsError propagates cleanly. + let pq_err = curate_and_write_shorts( + fresh_tmp.path(), + std::iter::empty::>(), + "ceo", + &mapping, + ShortsWriteOptions { + row_group_rows: 0, + ..ShortsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + pq_err, + CurateShortsWriteError::Parquet(ParquetShortsError::InvalidRowGroupRows) + )); + assert!(pq_err.source().is_some()); + assert!(pq_err.to_string().contains("Parquet write failed")); + + // Empty input is a clean no-op without creating shorts/. + let empty_report = curate_and_write_shorts( + fresh_tmp.path(), + std::iter::empty::>(), + "ceo", + &mapping, + ShortsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_report.curate_stats, CurateShortsStats::default()); + assert_eq!(empty_report.write_stats, ShortsWriteStats::default()); + assert!(!fresh_tmp.path().join("shorts").exists()); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index db12225c..f190e914 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -97,3 +97,9 @@ pub use curate_bars::{ CurateBars1dWriteReport, CurateBarsError, CurateBarsWriteError, BARS_1D_SESSION_CLOSE_HOUR_ET, BARS_1D_SESSION_CLOSE_MINUTE_ET, BARS_1D_SESSION_CLOSE_SECOND_ET, BARS_1D_SOURCE_EOD, }; + +pub mod curate_shorts; +pub use curate_shorts::{ + curate_and_write_shorts, curate_shorts, CurateShortsError, CurateShortsOutput, + CurateShortsStats, CurateShortsWriteError, CurateShortsWriteReport, +}; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 7b2be7aa..407bc1d8 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -9,6 +9,7 @@ use curate_etl::bench::{ 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_curate_bars_benchmark, + run_curate_shorts_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -546,6 +547,64 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchCurateShorts(rows)) => { + let report = match run_curate_shorts_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-shorts benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-shorts"); + println!( + " input: rows={} keys={}", + report.rows, report.key_count + ); + println!( + " builder: rows_out={} invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict_dropped={}", + report.stats.builder.rows_out, + report.stats.builder.dropped_invalid_shares_short, + report.stats.builder.nulled_invalid_net_change, + report.stats.builder.nulled_invalid_pct_float, + report.stats.builder.duplicate_collapsed, + report.stats.builder.duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.listings_out, + report.stage_elapsed_ms, + report.stage_rows_per_sec, + report.stage_ns_per_row, + report.checksum + ); + println!( + " parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows, + report.parquet_elapsed_ms, + report.parquet_rows_per_sec + ); + println!( + " total: elapsed={:.2} ms throughput={:.0} rows/s", + report.total_elapsed_ms, report.total_rows_per_sec + ); + println!( + " curate: unmapped={} coll_collapsed={} coll_dropped={}", + report.stats.dropped_unmapped, + report.stats.listing_collision_collapsed, + report.stats.listing_collision_dropped + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); From c17e9471d402e1aa324895d3fbf42344280a2144 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 17:57:28 -0500 Subject: [PATCH 2/3] =?UTF-8?q?T-100:=20M1.2r=20=E2=80=94=20`tools/curate-?= =?UTF-8?q?etl`:=20pure=20`shorts`=20curation=20stage=20(source-keyed=20`c?= =?UTF-8?q?eoShorts`=20reports=20=E2=86=92=20`provider=5Fmapping`=20?= =?UTF-8?q?=E2=86=92=20`ShortsParquetRow`s=20=E2=86=92=20Zstd=20Parquet)?= =?UTF-8?q?=20with=20tests=20and=20local=20benchmark=20(no=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/curate_shorts_tests.rs | 283 ++++++++++++++++++++ 1 file changed, 283 insertions(+) diff --git a/tools/curate-etl/src/curate_shorts_tests.rs b/tools/curate-etl/src/curate_shorts_tests.rs index f330f311..8fe5a599 100644 --- a/tools/curate-etl/src/curate_shorts_tests.rs +++ b/tools/curate-etl/src/curate_shorts_tests.rs @@ -655,6 +655,31 @@ fn fixed_seed_randomized_fixture_satisfies_conservation_and_parquet_writer_contr assert!(out.stats.listing_collision_collapsed > 0); assert!(out.stats.listing_collision_dropped > 0); + // Permutation invariance on the larger randomized fixture (reversed + deterministic shuffles). + let mut reversed = reports.clone(); + reversed.reverse(); + let out_rev = curate_shorts(reversed, "ceo", &mapping).unwrap(); + assert_eq!(out_rev.stats, out.stats); + assert_eq!(out_rev.rows.len(), out.rows.len()); + for (a, b) in out_rev.rows.iter().zip(out.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + + for shuffle_seed in [0xA11C_E5ED_0000_0001u64, 0xB0B0_C0DE_0000_0002u64] { + let mut shuffled = reports.clone(); + let mut shuffle_rng = SplitMix64(shuffle_seed); + for i in (1..shuffled.len()).rev() { + let j = (shuffle_rng.next_u64() as usize) % (i + 1); + shuffled.swap(i, j); + } + let out_shuf = curate_shorts(shuffled, "ceo", &mapping).unwrap(); + assert_eq!(out_shuf.stats, out.stats); + assert_eq!(out_shuf.rows.len(), out.rows.len()); + for (a, b) in out_shuf.rows.iter().zip(out.rows.iter()) { + assert_row_bitwise_eq(a, b); + } + } + // Stage output must always satisfy write_shorts_dataset's strict contract. let tmp = TempDirGuard::new("rand-parquet"); let write_stats = @@ -780,3 +805,261 @@ fn curate_and_write_shorts_round_trips_parquet_and_protects_out_dir_on_error() { assert_eq!(empty_report.write_stats, ShortsWriteStats::default()); assert!(!fresh_tmp.path().join("shorts").exists()); } + +#[test] +fn curate_shorts_matches_reference_oracle_across_fixed_seeds() { + use std::collections::BTreeMap; + + struct SplitMix64(u64); + impl SplitMix64 { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + } + + let dates: Vec = (2018..=2025) + .flat_map(|y| { + (1..=12).flat_map(move |m| { + let mid = day(y, m, 15); + let end = if m == 12 { + day(y + 1, 1, 1) - 1 + } else { + day(y, m + 1, 1) - 1 + }; + [mid, end] + }) + }) + .collect(); + + let mut mapping_rows = Vec::new(); + for i in 0..15 { + mapping_rows.push(map_row("ceo", &format!("K{i:02}"), day(2018, 1, 1), None, i + 1)); + } + for i in 0..5 { + let key = format!("K{:02}", 15 + i); + mapping_rows.push(map_row( + "ceo", + &key, + day(2018, 1, 1), + Some(day(2021, 6, 30)), + 101 + i, + )); + mapping_rows.push(map_row( + "ceo", + &key, + day(2022, 1, 1), + None, + 201 + i, + )); + } + for i in 0..5 { + mapping_rows.push(map_row( + "ceo", + &format!("K{:02}", 20 + i), + day(2018, 1, 1), + None, + i + 1, + )); + } + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + + for seed in [ + 0x1111_2222_3333_4444u64, + 0x5555_6666_7777_8888u64, + 0x9999_AAAA_BBBB_CCCCu64, + ] { + let mut rng = SplitMix64(seed); + let mut reports = Vec::with_capacity(3_000); + for _ in 0..3_000 { + let key_idx = (rng.next_u64() % 30) as usize; + let report_date = dates[(rng.next_u64() as usize) % dates.len()]; + let shares_short = ((rng.next_u64() % 4) * 500) as f64; + let net_change = match rng.next_u64() % 4 { + 0 => None, + v => Some((v as f64 - 2.0) * 100.0), + }; + let pct_float = match rng.next_u64() % 4 { + 0 => None, + v => Some(v as f64 * 0.25), + }; + reports.push(CeoShortReport { + key: format!("K{key_idx:02}"), + report_date, + shares_short, + net_change, + pct_float, + }); + } + + let actual = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&actual); + + // Simple reference oracle using BTreeMap over build_shorts output. + let built = build_shorts(reports).unwrap(); + let mut groups: BTreeMap<(i32, i32), Vec> = BTreeMap::new(); + let mut expected_unmapped = 0usize; + for row in built.rows { + if let Some(listing_id) = mapping.resolve("ceo", &row.key, row.report_date) { + groups + .entry((listing_id, row.report_date)) + .or_default() + .push(ShortsParquetRow { + listing_id, + report_date: row.report_date, + known_at_micros: row.known_at_utc_micros, + shares_short: row.shares_short, + net_change: row.net_change, + pct_float: row.pct_float, + source: Cow::Borrowed(row.source), + }); + } else { + expected_unmapped += 1; + } + } + + let mut expected_rows = Vec::new(); + let mut expected_collapsed = 0usize; + let mut expected_dropped = 0usize; + for group in groups.into_values() { + if group.len() == 1 { + expected_rows.push(group.into_iter().next().unwrap()); + } else { + let first = &group[0]; + let all_same = group[1..].iter().all(|r| { + r.known_at_micros == first.known_at_micros + && r.shares_short.to_bits() == first.shares_short.to_bits() + && r.net_change.map(f64::to_bits) == first.net_change.map(f64::to_bits) + && r.pct_float.map(f64::to_bits) == first.pct_float.map(f64::to_bits) + }); + if all_same { + expected_collapsed += group.len() - 1; + expected_rows.push(group.into_iter().next().unwrap()); + } else { + expected_dropped += group.len(); + } + } + } + + assert_eq!(actual.stats.dropped_unmapped, expected_unmapped); + assert_eq!(actual.stats.listing_collision_collapsed, expected_collapsed); + assert_eq!(actual.stats.listing_collision_dropped, expected_dropped); + assert_eq!(actual.rows.len(), expected_rows.len()); + for (a, e) in actual.rows.iter().zip(expected_rows.iter()) { + assert_row_bitwise_eq(a, e); + } + } +} + +#[test] +fn curate_shorts_enforces_look_ahead_lag_and_temporal_stability() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "RY", day(2018, 1, 1), None, 10), + map_row("ceo", "RY_ALIAS", day(2018, 1, 1), None, 10), + map_row("ceo", "TD", day(2018, 1, 1), None, 20), + ]) + .unwrap(); + + let pre_2022 = vec![ + report("RY", day(2020, 1, 15), 5_000.0, Some(100.0), Some(0.5)), + report("RY", day(2021, 6, 30), 6_000.0, Some(200.0), Some(0.6)), + report("TD", day(2021, 12, 15), 7_000.0, None, Some(0.7)), + ]; + let baseline = curate_shorts(pre_2022.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&baseline); + + // Every emitted row must have known_at at least 4 calendar days after report_date. + const FOUR_DAYS_MICROS: i64 = 4 * 86_400 * 1_000_000; + for row in &baseline.rows { + let report_midnight_micros = i64::from(row.report_date) * 86_400 * 1_000_000; + assert!( + row.known_at_micros >= report_midnight_micros + FOUR_DAYS_MICROS, + "known_at_micros {} is not >= 4 days after report_date {}", + row.known_at_micros, + row.report_date + ); + } + + // Appending future 2026 reports (including conflicting cross-key collisions) must not + // alter any pre-2022 output row. + let mut with_future = pre_2022; + with_future.push(report("RY", day(2026, 1, 15), 99_999.0, Some(500.0), Some(9.9))); + with_future.push(report( + "RY_ALIAS", + day(2026, 1, 15), + 11_111.0, + Some(-500.0), + Some(1.1), + )); + with_future.push(report("TD", day(2026, 2, 15), 88_888.0, None, None)); + + let full = curate_shorts(with_future, "ceo", &mapping).unwrap(); + assert_conservation_and_order(&full); + + let cutoff = day(2022, 1, 1); + let prefix: Vec<&ShortsParquetRow> = full + .rows + .iter() + .filter(|r| r.report_date < cutoff) + .collect(); + assert_eq!(prefix.len(), baseline.rows.len()); + for (a, b) in prefix.iter().zip(baseline.rows.iter()) { + assert_row_bitwise_eq(a, b); + } +} + +#[test] +fn curate_shorts_handles_borrowed_str_keys_unknown_source_and_builder_conflict_isolation() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "SYM_A", day(2020, 1, 1), None, 10), + map_row("ceo", "SYM_B", day(2020, 1, 1), None, 10), + map_row("other", "SYM_A", day(2020, 1, 1), None, 99), + ]) + .unwrap(); + + // Borrowed &str keys work directly; SYM_A has a builder-level duplicate conflict (dropped by + // build_shorts), so SYM_B's lone valid copy for (listing_id=10, 2024-03-15) survives intact. + let d = day(2024, 3, 15); + let reports: Vec> = vec![ + CeoShortReport { + key: "SYM_A", + report_date: d, + shares_short: 1_000.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: "SYM_A", + report_date: d, + shares_short: 2_000.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: "SYM_B", + report_date: d, + shares_short: 3_000.0, + net_change: Some(50.0), + pct_float: Some(0.4), + }, + ]; + + let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_conservation_and_order(&out); + assert_eq!(out.stats.builder.duplicate_conflict_dropped, 2); + assert_eq!(out.stats.rows_in, 1); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.stats.listing_collision_dropped, 0); + assert_eq!(out.rows[0].listing_id, 10); + assert_eq!(out.rows[0].shares_short, 3_000.0); + + // Unknown mapping_source drops every builder-surviving row without error. + let unknown = curate_shorts(reports, "nonexistent_source", &mapping).unwrap(); + assert_conservation_and_order(&unknown); + assert_eq!(unknown.stats.rows_in, 1); + assert_eq!(unknown.stats.rows_out, 0); + assert_eq!(unknown.stats.dropped_unmapped, 1); +} From 5954321cbf00de1e527b9ea52d5f1ff77dcebe40 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 18:04:51 -0500 Subject: [PATCH 3/3] T-100: tests --- .../tests/curate_shorts_qa_contract.rs | 509 ++++++++++++++++++ 1 file changed, 509 insertions(+) create mode 100644 tools/curate-etl/tests/curate_shorts_qa_contract.rs diff --git a/tools/curate-etl/tests/curate_shorts_qa_contract.rs b/tools/curate-etl/tests/curate_shorts_qa_contract.rs new file mode 100644 index 00000000..4ab0dfa7 --- /dev/null +++ b/tools/curate-etl/tests/curate_shorts_qa_contract.rs @@ -0,0 +1,509 @@ +//! QA contract tests for the public `shorts` curation stage (T-100 / M1.2r). +//! +//! Covers gaps left by the in-crate `curate_shorts_tests.rs`, checking against independent +//! references rather than the stage's own logic: +//! - `known_at_micros` pinned to hand-computed `+4` TSX business-day `17:00 ET` instants across +//! holidays and both DST regimes; +//! - seeded differential test against a naive reference that resolves `provider_mapping` by +//! linear scan over the raw mapping rows on `report_date` (never through the table/cursor); +//! - truncation and poison look-ahead tests at several cutoffs with non-empty baselines; +//! - ticker change (two keys → one listing over disjoint ranges) kept without collisions; +//! - successful re-publish replaces a larger `part.parquet`, multi-row-group round trip; +//! - `bench-curate-shorts` binary run: deterministic checksum and `read_back_rows == rows_out`. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +use curate_etl::{ + curate_and_write_shorts, curate_shorts, CeoShortReport, CurateShortsOutput, + ProviderMappingRow, ProviderMappingTable, ShortsParquetRow, ShortsWriteOptions, + SHORTS_SOURCE_CEO, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 86_400_000_000; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-curate-shorts-qa-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// Deterministic SplitMix64 (fixed seed per test). +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +/// Independent civil-from-days (Howard Hinnant), not the crate's `ymd_to_epoch_days`. +fn day(y: i32, m: u32, d: u32) -> i32 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m as i32 + 9) % 12; + let doy = (153 * mp + 2) / 5 + d as i32 - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn report(key: &str, report_date: i32, shares: f64, net: Option, pct: Option) -> CeoShortReport { + CeoShortReport { + key: key.to_string(), + report_date, + shares_short: shares, + net_change: net, + pct_float: pct, + } +} + +fn map_row(source: &str, id: &str, from: i32, to: Option, listing_id: i32) -> ProviderMappingRow { + ProviderMappingRow { + source: source.to_string(), + source_id: id.to_string(), + valid_from: from, + valid_to: to, + listing_id, + } +} + +fn assert_rows_bitwise(actual: &[ShortsParquetRow], expected: &[ShortsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count mismatch"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!( + (a.listing_id, a.report_date, a.known_at_micros, a.shares_short.to_bits()), + (e.listing_id, e.report_date, e.known_at_micros, e.shares_short.to_bits()), + "row {i}" + ); + assert_eq!(a.net_change.map(f64::to_bits), e.net_change.map(f64::to_bits), "row {i}"); + assert_eq!(a.pct_float.map(f64::to_bits), e.pct_float.map(f64::to_bits), "row {i}"); + assert_eq!(a.source, e.source, "row {i}"); + } +} + +fn assert_invariants(out: &CurateShortsOutput) { + let s = out.stats; + assert_eq!(s.rows_in, s.builder.rows_out, "{s:?}"); + assert_eq!(s.rows_out, out.rows.len(), "{s:?}"); + assert_eq!( + s.rows_in, + s.rows_out + s.dropped_unmapped + s.listing_collision_collapsed + s.listing_collision_dropped, + "{s:?}" + ); + for w in out.rows.windows(2) { + assert!((w[0].listing_id, w[0].report_date) < (w[1].listing_id, w[1].report_date)); + } + let mut listings: Vec = out.rows.iter().map(|r| r.listing_id).collect(); + listings.dedup(); + assert_eq!(s.listings_out, listings.len()); +} + +#[test] +fn known_at_matches_hand_computed_tsx_plus_four_business_days_at_17_et() { + // (report_date, expected known_at date, UTC offset hours of 17:00 ET on that date) + let cases = [ + // Fri before Canada Day (Mon Jul 1): Jul 2,3,4,5 -> Fri Jul 5, EDT (21:00Z). + (day(2024, 6, 28), day(2024, 7, 5), 21), + // Tue Dec 31, New Year's Day Wed: Jan 2,3,6,7 -> Tue Jan 7 2025, EST (22:00Z). + (day(2024, 12, 31), day(2025, 1, 7), 22), + // Fri Dec 15 2023, ordinary: Dec 18..21 -> Thu Dec 21, EST. + (day(2023, 12, 15), day(2023, 12, 21), 22), + // Fri Dec 22 2023? not a report date; use Sun Dec 31 2023: Jan 1 holiday, Jan 2,3,4,5. + (day(2023, 12, 31), day(2024, 1, 5), 22), + // Fri Mar 15 2024 (DST began Mar 10): Mar 18..21, EDT. + (day(2024, 3, 15), day(2024, 3, 21), 21), + // Fri Mar 29 2024 is Good Friday; Sun Mar 31 report: Apr 1(open),2,3,4 -> Apr 4. + (day(2024, 3, 31), day(2024, 4, 4), 21), + // Thu Oct 31 2024 (DST ends Nov 3): Nov 1, 4, 5, 6 -> Wed Nov 6, EST. + (day(2024, 10, 31), day(2024, 11, 6), 22), + // Mon Nov 11 2024 Remembrance Day is a TSX trading day; Fri Nov 15: 18..21. + (day(2024, 11, 15), day(2024, 11, 21), 22), + // Thu Jul 31 2025: Aug 1, (Aug 4 Civic Holiday), 5, 6, 7 -> Thu Aug 7, EDT. + (day(2025, 7, 31), day(2025, 8, 7), 21), + ]; + let mapping = ProviderMappingTable::from_rows([map_row("ceo", "RY", day(2010, 1, 1), None, 7)]).unwrap(); + let reports: Vec<_> = cases.iter().map(|&(d, _, _)| report("RY", d, 1_000.0, None, None)).collect(); + + let out = curate_shorts(reports, "ceo", &mapping).unwrap(); + assert_invariants(&out); + assert_eq!(out.rows.len(), cases.len()); + + let mut sorted = cases; + sorted.sort_by_key(|c| c.0); + for (row, &(rd, known_day, utc_hour)) in out.rows.iter().zip(&sorted) { + assert_eq!(row.report_date, rd); + let expected = i64::from(known_day) * MICROS_PER_DAY + utc_hour * MICROS_PER_HOUR; + assert_eq!( + row.known_at_micros, expected, + "report_date {rd}: known_at off by {} h", + (row.known_at_micros - expected) / MICROS_PER_HOUR + ); + assert_eq!(row.source.as_ref(), SHORTS_SOURCE_CEO); + } +} + +/// Random universe: plain keys, ticker reuse with a gap, ticker change (two keys sharing one +/// listing over disjoint ranges), aliases (overlapping ranges -> collisions), unmapped keys, +/// plus decoy rows under a different mapping source. +fn random_universe() -> (Vec, Vec) { + let mut rows = Vec::new(); + let mut keys = Vec::new(); + for i in 0..8 { + let k = format!("P{i}"); + rows.push(map_row("ceo", &k, day(2018, 1, 1), None, 10 + i)); + rows.push(map_row("other", &k, day(2018, 1, 1), None, 900 + i)); + keys.push(k); + } + for i in 0..3 { + let k = format!("R{i}"); + rows.push(map_row("ceo", &k, day(2018, 1, 1), Some(day(2020, 6, 15)), 40 + i)); + rows.push(map_row("ceo", &k, day(2020, 9, 1), None, 50 + i)); + keys.push(k); + } + for i in 0..3 { + // Ticker change: OLD{i} until 2021-03-31, NEW{i} from 2021-04-01, same listing. + let (old, new) = (format!("OLD{i}"), format!("NEW{i}")); + rows.push(map_row("ceo", &old, day(2018, 1, 1), Some(day(2021, 3, 31)), 60 + i)); + rows.push(map_row("ceo", &new, day(2021, 4, 1), None, 60 + i)); + keys.push(old); + keys.push(new); + } + for i in 0..3 { + let k = format!("A{i}"); + rows.push(map_row("ceo", &k, day(2019, 1, 1), Some(day(2023, 12, 31)), 10 + i)); + keys.push(k); + } + for i in 0..3 { + keys.push(format!("U{i}")); + } + (rows, keys) +} + +fn report_dates() -> Vec { + let mut v = Vec::new(); + for y in 2017..=2025 { + for m in 1..=12u32 { + v.push(day(y, m, 15)); + let next = if m == 12 { day(y + 1, 1, 1) } else { day(y, m + 1, 1) }; + v.push(next - 1); + } + } + v +} + +fn random_reports(seed: u64, n: usize, keys: &[String], dates: &[i32]) -> Vec> { + let mut rng = Rng(seed); + let mut out: Vec> = Vec::with_capacity(n); + while out.len() < n { + // Echo the previous plain-key report under its alias key (`P{i}` -> `A{i}`), identical + // or conflicting, so cross-key collisions are hit deterministically. + let echo = rng.below(10); + if echo < 2 { + if let Some(prev) = out.last() { + if let Some(i) = prev.key.strip_prefix('P').filter(|i| ["0", "1", "2"].contains(i)) { + let mut copy = report(&format!("A{i}"), prev.report_date, prev.shares_short, prev.net_change, prev.pct_float); + if echo == 1 { + copy.shares_short += 1.0; + } + out.push(copy); + continue; + } + } + } + out.push({ + let key = &keys[rng.below(keys.len() as u64) as usize]; + let d = dates[rng.below(dates.len() as u64) as usize]; + let shares = match rng.below(50) { + 0 => -5.0, + 1 => f64::NAN, + _ => (rng.below(3) * 500) as f64, + }; + let net = match rng.below(4) { + 0 => None, + 1 => Some(f64::NEG_INFINITY), + v => Some(v as f64 * 10.0), + }; + let pct = match rng.below(3) { + 0 => None, + v => Some(v as f64 * 0.5), + }; + report(key, d, shares, net, pct) + }); + } + out +} + +/// Naive reference built directly from `build_shorts` output and the raw mapping rows. +fn reference( + reports: Vec>, + source: &str, + mapping_rows: &[ProviderMappingRow], +) -> (Vec, usize, usize, usize) { + let built = curate_etl::build_shorts(reports).unwrap(); + let mut groups: BTreeMap<(i32, i32), Vec> = BTreeMap::new(); + let mut unmapped = 0; + for r in built.rows { + let hit = mapping_rows.iter().find(|m| { + m.source == source + && m.source_id == r.key + && m.valid_from <= r.report_date + && m.valid_to.is_none_or(|to| r.report_date <= to) + }); + match hit { + Some(m) => groups.entry((m.listing_id, r.report_date)).or_default().push(ShortsParquetRow { + listing_id: m.listing_id, + report_date: r.report_date, + known_at_micros: r.known_at_utc_micros, + shares_short: r.shares_short, + net_change: r.net_change, + pct_float: r.pct_float, + source: Cow::Borrowed(r.source), + }), + None => unmapped += 1, + } + } + let key = |r: &ShortsParquetRow| { + (r.known_at_micros, r.shares_short.to_bits(), r.net_change.map(f64::to_bits), r.pct_float.map(f64::to_bits)) + }; + let (mut out, mut collapsed, mut dropped) = (Vec::new(), 0, 0); + for (_, g) in groups { + if g.iter().all(|r| key(r) == key(&g[0])) { + collapsed += g.len() - 1; + out.push(g.into_iter().next().unwrap()); + } else { + dropped += g.len(); + } + } + (out, unmapped, collapsed, dropped) +} + +#[test] +fn seeded_stage_matches_linear_scan_reference_resolving_on_report_date() { + let (mapping_rows, keys) = random_universe(); + let mapping = ProviderMappingTable::from_rows(mapping_rows.clone()).unwrap(); + let dates = report_dates(); + + for seed in [0xC0FF_EE00_0000_0001u64, 0xC0FF_EE00_0000_0002, 0xC0FF_EE00_0000_0003] { + let reports = random_reports(seed, 4_000, &keys, &dates); + let out = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + assert_invariants(&out); + let (exp, unmapped, collapsed, dropped) = reference(reports, "ceo", &mapping_rows); + assert_eq!(out.stats.dropped_unmapped, unmapped, "seed {seed:#x}"); + assert_eq!(out.stats.listing_collision_collapsed, collapsed, "seed {seed:#x}"); + assert_eq!(out.stats.listing_collision_dropped, dropped, "seed {seed:#x}"); + assert!(unmapped > 0 && collapsed > 0 && dropped > 0, "fixture must hit every path: {:?}", out.stats); + assert_rows_bitwise(&out.rows, &exp); + // No row may come from the decoy "other" source listings. + assert!(out.rows.iter().all(|r| r.listing_id < 900)); + } +} + +#[test] +fn ticker_change_keys_share_one_listing_without_collisions() { + let mapping = ProviderMappingTable::from_rows([ + map_row("ceo", "OLD", day(2018, 1, 1), Some(day(2021, 3, 31)), 60), + map_row("ceo", "NEW", day(2021, 4, 1), None, 60), + ]) + .unwrap(); + let reports = vec![ + report("OLD", day(2021, 2, 28), 100.0, None, None), + report("OLD", day(2021, 3, 31), 200.0, None, None), + report("NEW", day(2021, 4, 15), 300.0, None, None), + // Stale feed: OLD keeps reporting after the change -> unmapped, not a collision. + report("OLD", day(2021, 4, 15), 999.0, None, None), + // NEW backfilled before its range -> unmapped. + report("NEW", day(2021, 3, 15), 888.0, None, None), + ]; + let out = curate_shorts(reports, "ceo", &mapping).unwrap(); + assert_invariants(&out); + assert_eq!(out.stats.dropped_unmapped, 2); + assert_eq!(out.stats.listing_collision_collapsed + out.stats.listing_collision_dropped, 0); + assert_eq!(out.stats.listings_out, 1); + let got: Vec<(i32, f64)> = out.rows.iter().map(|r| (r.report_date, r.shares_short)).collect(); + assert_eq!(got, vec![(day(2021, 2, 28), 100.0), (day(2021, 3, 31), 200.0), (day(2021, 4, 15), 300.0)]); +} + +#[test] +fn truncation_and_poison_leave_earlier_rows_unchanged_at_every_cutoff() { + let (mapping_rows, keys) = random_universe(); + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + let dates = report_dates(); + let reports = random_reports(0x7E57_0000_1234_5678, 3_000, &keys, &dates); + let full = curate_shorts(reports.clone(), "ceo", &mapping).unwrap(); + + for cutoff in [day(2019, 1, 1), day(2020, 7, 1), day(2021, 4, 1), day(2023, 1, 1), day(2025, 6, 1)] { + let truncated: Vec<_> = reports.iter().filter(|r| r.report_date < cutoff).cloned().collect(); + let base = curate_shorts(truncated.clone(), "ceo", &mapping).unwrap(); + assert_invariants(&base); + assert!(base.rows.len() > 10, "cutoff {cutoff}: baseline must not be empty"); + + // Truncation: rebuilding from history alone equals the full run's history. + let prefix: Vec<_> = full.rows.iter().filter(|r| r.report_date < cutoff).cloned().collect(); + assert_rows_bitwise(&base.rows, &prefix); + + // Poison: absurd future reports on every key, conflicting aliases included. + let mut poisoned = truncated; + for (i, k) in keys.iter().enumerate() { + poisoned.push(report(k, day(2026, 1, 15), 1e12 + i as f64, Some(-1e9), Some(99.0))); + poisoned.push(report(k, cutoff, 7e11 + i as f64, None, Some(50.0))); + } + let pois = curate_shorts(poisoned, "ceo", &mapping).unwrap(); + assert_invariants(&pois); + let pois_prefix: Vec<_> = pois.rows.into_iter().filter(|r| r.report_date < cutoff).collect(); + assert_rows_bitwise(&pois_prefix, &base.rows); + + // Every row is published strictly after its report date ends (>= 4 days later). + for r in &base.rows { + assert!(r.known_at_micros >= (i64::from(r.report_date) + 4) * MICROS_PER_DAY); + } + } +} + +fn read_parquet(path: &Path) -> (usize, usize, Vec) { + let reader = SerializedFileReader::new(File::open(path).unwrap()).unwrap(); + let md = reader.metadata(); + let footer = md.file_metadata().num_rows() as usize; + let mut out = Vec::new(); + for g in 0..md.num_row_groups() { + let rg = reader.get_row_group(g).unwrap(); + let n = md.row_group(g).num_rows() as usize; + let mut lid = Vec::new(); + let mut rd = Vec::new(); + let mut ka = Vec::new(); + let mut ss = Vec::new(); + let mut src = Vec::new(); + if let ColumnReader::Int32ColumnReader(mut r) = rg.get_column_reader(0).unwrap() { + r.read_records(n, None, None, &mut lid).unwrap(); + } + if let ColumnReader::Int32ColumnReader(mut r) = rg.get_column_reader(1).unwrap() { + r.read_records(n, None, None, &mut rd).unwrap(); + } + if let ColumnReader::Int64ColumnReader(mut r) = rg.get_column_reader(2).unwrap() { + r.read_records(n, None, None, &mut ka).unwrap(); + } + if let ColumnReader::DoubleColumnReader(mut r) = rg.get_column_reader(3).unwrap() { + r.read_records(n, None, None, &mut ss).unwrap(); + } + let opt = |idx: usize| -> Vec> { + let (mut vals, mut defs) = (Vec::new(), Vec::new()); + if let ColumnReader::DoubleColumnReader(mut r) = rg.get_column_reader(idx).unwrap() { + r.read_records(n, Some(&mut defs), None, &mut vals).unwrap(); + } + let mut it = vals.into_iter(); + defs.into_iter().map(|d| if d == 1 { it.next() } else { None }).collect() + }; + let (net, pct) = (opt(4), opt(5)); + if let ColumnReader::ByteArrayColumnReader(mut r) = rg.get_column_reader(6).unwrap() { + r.read_records(n, None, None, &mut src).unwrap(); + } + assert_eq!((lid.len(), rd.len(), ka.len(), ss.len(), src.len()), (n, n, n, n, n)); + for i in 0..n { + out.push(ShortsParquetRow { + listing_id: lid[i], + report_date: rd[i], + known_at_micros: ka[i], + shares_short: ss[i], + net_change: net[i], + pct_float: pct[i], + source: Cow::Owned(String::from_utf8(src[i].data().to_vec()).unwrap()), + }); + } + } + (footer, md.num_row_groups(), out) +} + +#[test] +fn republish_replaces_larger_file_and_multi_row_group_round_trips() { + let (mapping_rows, keys) = random_universe(); + let mapping = ProviderMappingTable::from_rows(mapping_rows).unwrap(); + let dates = report_dates(); + let tmp = TempDir::new("republish"); + let part = tmp.0.join("shorts").join("part.parquet"); + let opts = ShortsWriteOptions { row_group_rows: 97, ..ShortsWriteOptions::default() }; + + let big = random_reports(0xB16_0000_0000_0001, 2_000, &keys, &dates); + let first = curate_and_write_shorts(&tmp.0, big.clone(), "ceo", &mapping, opts).unwrap(); + let expected_big = curate_shorts(big, "ceo", &mapping).unwrap(); + let (footer, groups, rows) = read_parquet(&part); + assert_eq!(footer, first.curate_stats.rows_out); + assert_eq!(groups, first.write_stats.row_groups_written); + assert_eq!(groups, footer.div_ceil(97)); + assert!(groups > 1); + assert_rows_bitwise(&rows, &expected_big.rows); + + let small = random_reports(0x5A1_0000_0000_0002, 50, &keys, &dates); + let second = curate_and_write_shorts(&tmp.0, small.clone(), "ceo", &mapping, opts).unwrap(); + assert!(second.curate_stats.rows_out > 0 && second.curate_stats.rows_out < first.curate_stats.rows_out); + let (footer, _, rows) = read_parquet(&part); + assert_eq!(footer, second.curate_stats.rows_out); + assert_rows_bitwise(&rows, &curate_shorts(small, "ceo", &mapping).unwrap().rows); + + let leftovers: Vec<_> = fs::read_dir(tmp.0.join("shorts")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(leftovers, vec!["part.parquet".to_string()]); +} + +fn field<'a>(text: &'a str, name: &str) -> &'a str { + text.split_whitespace() + .find_map(|t| t.strip_prefix(name)) + .unwrap_or_else(|| panic!("missing {name} in:\n{text}")) +} + +#[test] +fn bench_curate_shorts_cli_is_deterministic_and_reads_back_all_rows() { + let run = |args: &[&str]| Command::new(env!("CARGO_BIN_EXE_curate-etl")).args(args).output().unwrap(); + let a = run(&["bench-curate-shorts", "30000"]); + let b = run(&["bench-curate-shorts", "30000"]); + assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); + let (ta, tb) = (String::from_utf8_lossy(&a.stdout), String::from_utf8_lossy(&b.stdout)); + + assert!(ta.contains("curate-etl bench-curate-shorts"), "{ta}"); + assert!(ta.contains("rows=30000 keys=12500"), "{ta}"); + assert_eq!(field(&ta, "checksum="), field(&tb, "checksum=")); + assert_ne!(field(&ta, "checksum="), "0x0000000000000000"); + // The builder line also has `rows_out=`, so compare against the stage line's value. + let stage_line = ta.lines().find(|l| l.trim_start().starts_with("stage:")).unwrap(); + assert_eq!(field(stage_line, "rows_out="), field(&ta, "read_back_rows=")); + + for bad in [&["bench-curate-shorts", "0"][..], &["bench-curate-shorts", "x"], &["bench-curate-shorts", "1", "2"]] { + let o = run(bad); + assert!(!o.status.success(), "{bad:?} should fail"); + assert!(String::from_utf8_lossy(&o.stderr).contains("bench-curate-shorts"), "{bad:?}"); + } +}