diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 9fa5f802..2e491b96 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -764,3 +764,41 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0xde3b3bd6 - 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` + +## `events` Curation Stage (`M1.2s`) + +`curate_events` and `curate_and_write_events` (`src/curate_events.rs`) join `build_events`, `ProviderMappingTable`, and `write_events_dataset` into contract `EventsParquetRow` records strictly ascending in the 7-field writer sort key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`. + +1. **Field & Point-in-Time rules:** + - Runs `build_events` unchanged on source keys so same-day earnings↔filing linking (`8-K` / `News release`), form classification, timestamp parsing, conservative `16:05 ET` fallback, and per-key deduplication happen before `provider_mapping` resolution. + - Internally uses the crate-private `build_events_with_dates` helper (zero overhead on public `build_events`, unchanged `EventsParquetRow` schema) to carry each row's already-parsed Eastern local calendar date (`ParsedFilingTime::et_date` for filings; `QmEarning::report_date` for earnings) alongside the row. + - Resolves `(mapping_source, key, event_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) strictly on that Eastern local calendar date—covering pre-2008 historical filings and late-evening EST/EDT filings whose UTC date has rolled over—never on UTC date or `known_at` date. + - Moves `subtype` and `payload_json` without cloning, keeps `known_at_source` and `kind` as `Cow::Borrowed`, and frees builder rows before re-sorting. +2. **Drop & collapse policy (never panics or aborts on bad rows):** + - Rows whose `(mapping_source, key, event_date)` is not covered by any `provider_mapping` range are dropped into `dropped_unmapped`. + - After re-sorting in place by the 7-field writer key, cross-`key` rows mapping to the same `listing_id` that are identical on all seven fields collapse to one row (`listing_duplicate_collapsed`), while rows differing in any single field are all kept. + - Exact conservation invariants in `CurateEventsStats`: `rows_in == builder.rows_out`, `rows_in == rows_out + dropped_unmapped + listing_duplicate_collapsed`, and `rows_out == filings_out + earnings_out`. + - Typed caller errors: `CurateEventsError::EmptyMappingSource` and `CurateEventsWriteError` (`Curate(CurateEventsError)`, `Parquet(ParquetEventsError)`). A curate error in `curate_and_write_events` returns before invoking `write_events_dataset`, leaving `out_dir` untouched. + +### `bench-curate-events` + +Fixed-seed (`std`-only SplitMix64) benchmark over `500,000` source-keyed rows (~98.5% `qmFilings`, ~1.5% `qmEarnings`) across `20,000` `String` source keys (`2003-01-01..=2026-04-30`, covering single-range keys, multi-range ticker reuse with an H2-2021 gap, alias keys for cross-key duplicates, unmapped keys, pre-2008 filings, late-evening ET rollovers, linked/unlinked earnings, and builder skips/duplicates), separately timing in-memory `curate_events` and Zstd Parquet `write_events_dataset` into a temp directory with footer row-count verification across all year partitions and cleanup: + +```bash +cargo run --release -p curate-etl --offline -- bench-curate-events [rows] +``` + +Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0a1b7ace6344e408`): `cargo run --release -p curate-etl --offline -- bench-curate-events` + +- Input: `rows=500000`, `filings=492500`, `earnings=7500`, `keys=20000` +- Builder: `rows_out=493755`, `filings_out=487053`, `earnings_out=6702`, `malformed_ts=1011`, `unknown_zone=960`, `invalid_dt=1466`, `filing_dup=2010`, `linked=2556`, `lagged_1605=4146`, `earnings_oor=38`, `earnings_dup=102`, `earnings_conflict=658` +- Output: `rows_out=484402` (`96.88%` retained), `filings_out=477818`, `earnings_out=6584`, `listings_out=19997`, `files=24`, `row_groups=24`, `bytes=16057718`, `read_back_rows=484402` +- Curation stats: `unmapped=7713`, `dup_collapsed=1640` +- Run 1: + - Stage (in-memory): `elapsed=551.10 ms`, `throughput=907273 rows/s`, `latency=1102.20 ns/row`, `checksum=0x0a1b7ace6344e408` + - Parquet write: `elapsed=752.90 ms`, `throughput=643382 rows/s` + - Combined (stage → Parquet): `elapsed=1304.00 ms`, `throughput=383435 rows/s` +- Run 2: + - Stage (in-memory): `elapsed=589.24 ms`, `throughput=848550 rows/s`, `latency=1178.48 ns/row`, `checksum=0x0a1b7ace6344e408` + - Parquet write: `elapsed=682.82 ms`, `throughput=709419 rows/s` + - Combined (stage → Parquet): `elapsed=1272.06 ms`, `throughput=393065 rows/s` diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 9a656118..e23c70d5 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -4858,6 +4858,387 @@ pub fn run_curate_shorts_benchmark( Ok(report) } +pub const DEFAULT_CURATE_EVENTS_BENCH_ROWS: usize = 500_000; +const CURATE_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_C04A_E7E4; +const CURATE_EVENTS_BENCH_KEY_COUNT: usize = 20_000; + +/// Summary metrics produced by [`run_curate_events_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateEventsBenchReport { + pub rows: usize, + pub filings_in: usize, + pub earnings_in: 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_events::CurateEventsStats, +} + +fn run_curate_events_benchmark_tracked( + rows: usize, +) -> Result<(CurateEventsBenchReport, PathBuf), crate::curate_events::CurateEventsWriteError> { + use crate::curate_events::{curate_events, CurateEventsStats, CurateEventsWriteError}; + + let temp = BenchTempDir::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-curate-events", + ) + .map_err(|(path, source)| { + CurateEventsWriteError::Parquet(ParquetEventsError::Io { path, source }) + })?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let mapping = ProviderMappingTable::default(); + let curated = curate_events( + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + )?; + let write_stats = + write_events_dataset(&temp.path, &curated.rows, EventsWriteOptions::default())?; + let read_back_rows = + verify_parquet_events_row_count(&temp.path, write_stats.rows_by_year.keys().copied(), 0)?; + drop(temp); + return Ok(( + CurateEventsBenchReport { + rows: 0, + filings_in: 0, + earnings_in: 0, + key_count: CURATE_EVENTS_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: CurateEventsStats::default(), + }, + temp_path, + )); + } + + let valid_from_start = ymd_to_epoch_days(2003, 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 key_count = CURATE_EVENTS_BENCH_KEY_COUNT; + let single_range_end = 18_800usize; + let reuse_end_idx = 19_400usize; + let alias_end_idx = 19_700usize; + let alias_count = alias_end_idx - reuse_end_idx; + let ordinary_key_count = key_count - alias_count; + + let keys: Vec = (0..key_count).map(|i| format!("QM{i:05}")).collect(); + + // Build provider_mapping: + // - 0..18_800: single open-ended range from 2003-01-01 -> listing (i + 1) + // - 18_800..19_400: two ranges with H2-2021 gap -> listings (i + 1) and (i + 100_001) + // - 19_400..19_700: alias keys for listings 1..=300 (cross-key duplicates) + // - 19_700..20_000: 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: "qm".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: "qm".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: "qm".to_string(), + source_id: key.clone(), + valid_from: reuse_resume, + valid_to: None, + listing_id: (i + 100_001) as i32, + }); + } else if i < alias_end_idx { + let alias_lid = (i - reuse_end_idx + 1) as i32; + mapping_rows.push(ProviderMappingRow { + source: "qm".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 min_filing_date = valid_from_start; + let max_filing_date = ymd_to_epoch_days(2026, 4, 30).expect("valid max filing date"); + let filing_span = (max_filing_date - min_filing_date + 1) as u64; + + let min_earning_date = ymd_to_epoch_days(2008, 1, 1).expect("valid min earning date"); + let max_earning_date = max_filing_date; + let earning_span = (max_earning_date - min_earning_date + 1) as u64; + + let earnings_target = (rows * 15) / 1_000; + let filings_target = rows - earnings_target; + + let mut rng = SplitMix64::new(CURATE_EVENTS_BENCH_SEED); + let mut filings: Vec> = Vec::with_capacity(filings_target); + let mut link_pool: Vec<(usize, i32)> = Vec::with_capacity(earnings_target.min(16_384)); + let mut last_valid_filing: Option> = None; + let mut last_alias_filing: Option<(usize, QmFiling)> = None; + + for idx in 0..filings_target { + let roll = rng.next_u64() % 1_000; + if roll < 4 { + if let Some(prev) = last_valid_filing.clone() { + filings.push(prev); + continue; + } + } else if roll < 8 { + if let Some((alias_idx, mut prev)) = last_alias_filing.take() { + prev.key = keys[reuse_end_idx + alias_idx].clone(); + filings.push(prev); + continue; + } + } + + let key_idx = if roll < 20 { + (rng.next_u64() as usize) % alias_count + } else { + let slot = (rng.next_u64() as usize) % ordinary_key_count; + if slot < reuse_end_idx { + slot + } else { + slot + alias_count + } + }; + + let epoch_day = min_filing_date + (rng.next_u64() % filing_span) as i32; + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let form_idx = (rng.next_u64() as usize) % BENCH_FORM_TYPES.len(); + let form_type = BENCH_FORM_TYPES[form_idx].to_string(); + let filing_id = if rng.next_u64() % 10 == 0 { + None + } else { + Some(format!("F{idx:08}")) + }; + let url = if rng.next_u64() % 4 == 0 { + None + } else { + Some(format!("https://filings.example/{key_idx}/{idx}")) + }; + + let timefiled = match roll { + 8..=9 => "bad-timestamp".to_string(), + 10..=11 => format!("{y:04}-{m:02}-{d:02}T12:00:00 PST"), + 12..=13 => format!("{y:04}-02-30T12:00:00 EST"), + 14 => format!("{y:04}-{m:02}-{d:02}T25:00:00 EST"), + _ => { + // Mix morning, midday, and late-evening ET (crossing into next UTC day). + let hour = if roll < 65 { + 21 + (rng.next_u64() % 3) as u32 + } else { + 6 + (rng.next_u64() % 13) as u32 + }; + let minute = (rng.next_u64() % 60) as u32; + let second = (rng.next_u64() % 60) as u32; + let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" }; + let ts = format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}"); + if matches!(form_idx, 0 | 1 | 15) && link_pool.len() < 16_384 { + link_pool.push((key_idx, epoch_day)); + } + ts + } + }; + + let row = QmFiling { + key: keys[key_idx].clone(), + timefiled, + form_type, + filing_id, + url, + }; + if roll >= 15 { + if key_idx < alias_count { + last_alias_filing = Some((key_idx, row.clone())); + } + last_valid_filing = Some(row.clone()); + } + filings.push(row); + } + + let mut earnings: Vec> = Vec::with_capacity(earnings_target); + let mut last_valid_earning: Option> = None; + + for _ in 0..earnings_target { + let roll = rng.next_u64() % 1_000; + if roll < 15 { + if let Some(prev) = last_valid_earning.clone() { + earnings.push(prev); + continue; + } + } else if roll < 25 { + if let Some(mut prev) = last_valid_earning.clone() { + prev.actual_eps = Some(prev.actual_eps.unwrap_or(0.0) + 0.10); + earnings.push(prev); + continue; + } + } + + let (key_idx, report_date) = if roll < 30 && !link_pool.is_empty() { + let slot = (rng.next_u64() as usize) % ordinary_key_count; + let k = if slot < reuse_end_idx { + slot + } else { + slot + alias_count + }; + let d = ymd_to_epoch_days(2005, 6, 15).expect("valid pre-2008 date"); + (k, d) + } else if roll < 450 && !link_pool.is_empty() { + let pick = (rng.next_u64() as usize) % link_pool.len(); + link_pool[pick] + } else { + let slot = (rng.next_u64() as usize) % ordinary_key_count; + let k = if slot < reuse_end_idx { + slot + } else { + slot + alias_count + }; + let d = min_earning_date + (rng.next_u64() % earning_span) as i32; + (k, d) + }; + + let announce_time = + BENCH_ANNOUNCE_TIMES[(rng.next_u64() as usize) % BENCH_ANNOUNCE_TIMES.len()] + .to_string(); + let actual_eps = if roll % 50 == 0 { + Some(f64::NAN) + } else { + Some((((rng.next_u64() % 1_000) as f64) - 200.0) * 0.01) + }; + let revenue = Some(((rng.next_u64() % 5_000_000) + 10_000) as f64); + + let row = QmEarning { + key: keys[key_idx].clone(), + report_date, + announce_time, + fiscal_period_end: Some(report_date - 35), + actual_eps, + revenue, + }; + if roll >= 30 { + last_valid_earning = Some(row.clone()); + } + earnings.push(row); + } + + shuffle_slice(&mut filings, &mut rng); + shuffle_slice(&mut earnings, &mut rng); + + let filings_in = filings.len(); + let earnings_in = earnings.len(); + + // 1. Time pure in-memory curation stage. + let stage_start = Instant::now(); + let curated = curate_events(filings, earnings, "qm", &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.ts_micros as u64); + hash = mix_u64(hash, row.known_at_micros as u64); + hash = mix_bytes(hash, row.known_at_source.as_bytes()); + hash = mix_bytes(hash, row.kind.as_bytes()); + hash = mix_bytes(hash, row.subtype.as_bytes()); + hash = mix_bytes(hash, row.payload_json.as_bytes()); + } + let checksum = black_box(hash); + + // 2. Separately time Parquet write to temp dir. + let parquet_start = Instant::now(); + let write_stats = + write_events_dataset(&temp.path, &curated.rows, EventsWriteOptions::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_events_row_count( + &temp.path, + write_stats.rows_by_year.keys().copied(), + 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 = CurateEventsBenchReport { + rows, + filings_in, + earnings_in, + 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 `events` curation stage + Zstd Parquet write benchmark for `rows` +/// source-keyed `qmFilings` (~98.5%) and `qmEarnings` (~1.5%) rows across `20,000` `String` +/// source keys (single-range, ticker-reuse with gap, alias duplicates, unmapped keys, pre-2008 +/// filings, late-evening ET, linked/unlinked earnings, and builder skips/duplicates). +pub fn run_curate_events_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_events_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -6062,4 +6443,70 @@ mod tests { ); assert!(curated.stats.rows_out > 25_000 * 90 / 100); } + + #[test] + fn curate_events_benchmark_small_runs_are_deterministic_and_clean_up() { + for &n in &[20_000usize, 1_000usize] { + let (a, dir_a) = run_curate_events_benchmark_tracked(n).unwrap(); + let (b, dir_b) = run_curate_events_benchmark_tracked(n).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, n); + assert_eq!(a.filings_in + a.earnings_in, n); + 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, b.files_written); + assert!(a.files_written >= 2); + 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_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_duplicate_collapsed + ); + assert_eq!(a.stats.rows_out, a.stats.filings_out + a.stats.earnings_out); + if n >= 20_000 { + assert!(a.stats.filings_out > 0); + assert!(a.stats.earnings_out > 0); + assert!(a.stats.dropped_unmapped > 0); + assert!(a.stats.listing_duplicate_collapsed > 0); + } + } + } + + #[test] + fn curate_events_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_events_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.filings_in, 0); + assert_eq!(report.earnings_in, 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); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 36937be0..3dc48169 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -6,7 +6,8 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, - DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, + DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, + DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, @@ -35,6 +36,7 @@ pub enum CliAction { BenchBsonEodPrices(usize), BenchCurateBars(usize), BenchCurateShorts(usize), + BenchCurateEvents(usize), } /// Formats full help text including binary name and version. @@ -61,7 +63,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\ {name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\ {name} bench-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})" + {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ + {name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})" ) } @@ -87,7 +90,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-corporate-actions [rows]\n\ {name} bench-bson-eod-prices [rows]\n\ {name} bench-curate-bars [rows]\n\ - {name} bench-curate-shorts [rows]" + {name} bench-curate-shorts [rows]\n\ + {name} bench-curate-events [rows]" ) } @@ -274,6 +278,18 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-shorts", _, ..] => { Err("too many arguments for bench-curate-shorts".to_string()) } + ["bench-curate-events"] => { + Ok(CliAction::BenchCurateEvents(DEFAULT_CURATE_EVENTS_BENCH_ROWS)) + } + ["bench-curate-events", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateEvents(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-events", _, ..] => { + Err("too many arguments for bench-curate-events".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -581,6 +597,7 @@ mod tests { assert!(full.contains("bench-bson-eod-prices")); assert!(full.contains("bench-curate-bars")); assert!(full.contains("bench-curate-shorts")); + assert!(full.contains("bench-curate-events")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -600,6 +617,7 @@ mod tests { assert!(short.contains("bench-bson-eod-prices")); assert!(short.contains("bench-curate-bars")); assert!(short.contains("bench-curate-shorts")); + assert!(short.contains("bench-curate-events")); } #[test] @@ -635,4 +653,22 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-shorts", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-shorts", "10", "20"])).is_err()); } + + #[test] + fn parses_and_validates_bench_curate_events_args() { + assert_eq!( + parse_args(&to_args(&["bench-curate-events"])), + Ok(CliAction::BenchCurateEvents( + DEFAULT_CURATE_EVENTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-events", "1000"])), + Ok(CliAction::BenchCurateEvents(1_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-events", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events", "10", "20"])).is_err()); + } } diff --git a/tools/curate-etl/src/curate_events.rs b/tools/curate-etl/src/curate_events.rs new file mode 100644 index 00000000..84a074d6 --- /dev/null +++ b/tools/curate-etl/src/curate_events.rs @@ -0,0 +1,273 @@ +//! Pure, in-memory `events` curation stage joining [`crate::events::build_events`], +//! [`crate::provider_mapping::ProviderMappingTable`], and +//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s. +//! +//! # Contract & Point-in-Time Rules +//! - Calls the [`crate::events::build_events`] pipeline unchanged on source keys so same-day +//! earnings↔filing linking (`8-K` / `News release`), form classification, timestamp parsing, +//! conservative `16:05 ET` fallback, and per-key deduplication run before `provider_mapping` +//! resolution. +//! - **Exact Eastern local `event_date` mechanism:** Internally uses the crate-private +//! [`crate::events::build_events_with_dates`] helper (zero overhead on public `build_events`, +//! unchanged `EventsParquetRow` schema) to carry each row's already-parsed Eastern local +//! calendar date (`ParsedFilingTime::et_date` for filings; `QmEarning::report_date` for +//! earnings) alongside the row. This guarantees exact Eastern-date `provider_mapping` lookup +//! across all supported years—including pre-2008 historical filings and late-evening EST/EDT +//! filings whose UTC date has already rolled over to the next day—never using UTC date or +//! `known_at` date. +//! - Resolves each row's `(mapping_source, key, event_date)` to a permanent `listing_id: i32` via +//! [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`] (opening one cursor +//! per contiguous `key` run, since `build_events_with_dates` emits rows sorted by `key` then +//! `ts_micros`). Rows with no covering mapping range are dropped into `dropped_unmapped`. +//! - Moves `subtype` and `payload_json` without cloning, keeps `known_at_source` and `kind` as +//! `Cow::Borrowed`, and frees builder rows before re-sorting in place by the exact 7-field +//! writer key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, +//! known_at_source)`. +//! - Cross-`key` rows mapping to the same `listing_id` that are equal on all seven fields collapse +//! to one row (`listing_duplicate_collapsed`); rows differing in any single field are all kept +//! (events are not unique per `(listing_id, ts)`). + +use std::borrow::Cow; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::events::{ + build_events_with_dates, EventRowWithDate, EventsStats, QmEarning, QmFiling, + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, +}; +use crate::parquet_events::{ + write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, + ParquetEventsError, +}; +use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable}; + +/// Accounting summary produced alongside [`CurateEventsOutput::rows`]. +/// +/// Conservation invariants: +/// - `rows_in == builder.rows_out` +/// - `rows_in == rows_out + dropped_unmapped + listing_duplicate_collapsed` +/// - `rows_out == filings_out + earnings_out` +/// - `builder` independently satisfies all [`EventsStats`] conservation invariants. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateEventsStats { + pub builder: EventsStats, + pub rows_in: usize, + pub rows_out: usize, + pub listings_out: usize, + pub filings_out: usize, + pub earnings_out: usize, + pub dropped_unmapped: usize, + pub listing_duplicate_collapsed: usize, +} + +/// Output of [`curate_events`]: contract Parquet rows strictly ascending in the 7-field writer +/// sort key and full stage + builder stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateEventsOutput { + pub rows: Vec, + pub stats: CurateEventsStats, +} + +/// Typed caller errors returned by [`curate_events`]. +/// +/// Bad or unmapped single rows are skipped/dropped and counted in [`CurateEventsStats`] rather +/// than aborting the stage. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CurateEventsError { + /// Caller-supplied `mapping_source` was empty or contained only whitespace. + EmptyMappingSource, +} + +impl fmt::Display for CurateEventsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::EmptyMappingSource => { + write!(f, "mapping_source must not be empty or blank") + } + } + } +} + +impl Error for CurateEventsError {} + +/// Combined stats returned by [`curate_and_write_events`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateEventsWriteReport { + pub curate_stats: CurateEventsStats, + pub write_stats: EventsWriteStats, +} + +/// Typed error returned by [`curate_and_write_events`]. +#[derive(Debug)] +pub enum CurateEventsWriteError { + Curate(CurateEventsError), + Parquet(ParquetEventsError), +} + +impl fmt::Display for CurateEventsWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => write!(f, "events curation failed: {err}"), + Self::Parquet(err) => write!(f, "events Parquet write failed: {err}"), + } + } +} + +impl Error for CurateEventsWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateEventsWriteError { + fn from(err: CurateEventsError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateEventsWriteError { + fn from(err: ParquetEventsError) -> Self { + Self::Parquet(err) + } +} + +#[inline] +fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.as_ref().cmp(b.kind.as_ref())) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref())) +} + +/// Pure `events` curation stage: builds point-in-time `qmFilings` + `qmEarnings` rows on source +/// keys, resolves `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern +/// local calendar date via `provider_mapping`, and emits contract [`EventsParquetRow`]s strictly +/// ascending in the 7-field writer key. +/// +/// `event_date` is the filing's `timefiled` Eastern local calendar date for filings and +/// `report_date` for earnings—never the UTC date and never the `known_at` date. Rows with no +/// covering mapping range are dropped into `dropped_unmapped`. Cross-`key` rows that map to the +/// same `listing_id` and match on all seven fields collapse to one row +/// (`listing_duplicate_collapsed`); rows differing in any field are all kept. +pub fn curate_events( + filings: IF, + earnings: IE, + mapping_source: &str, + mapping: &ProviderMappingTable, +) -> Result +where + K: Ord + Clone + AsRef, + IF: IntoIterator>, + IE: IntoIterator>, +{ + if mapping_source.trim().is_empty() { + return Err(CurateEventsError::EmptyMappingSource); + } + + let (built_rows, builder_stats) = build_events_with_dates(filings, earnings); + + let mut stats = CurateEventsStats { + builder: builder_stats, + rows_in: built_rows.len(), + ..CurateEventsStats::default() + }; + + let mut rows: Vec = Vec::with_capacity(built_rows.len()); + let mut current_key: Option = None; + let mut current_cursor: Option> = None; + + for EventRowWithDate { row, event_date } in built_rows { + if current_key.as_ref() != Some(&row.key) { + current_cursor = Some(mapping.cursor_for(mapping_source, row.key.as_ref())); + current_key = Some(row.key); + } + + let cursor = current_cursor + .as_mut() + .expect("cursor initialized for current key run"); + if cursor.ranges().is_empty() { + stats.dropped_unmapped += 1; + continue; + } + + let Some(listing_id) = cursor.resolve(event_date) else { + stats.dropped_unmapped += 1; + continue; + }; + + rows.push(EventsParquetRow { + listing_id, + ts_micros: row.ts_micros, + known_at_micros: row.known_at_micros, + known_at_source: Cow::Borrowed(row.known_at_source), + kind: Cow::Borrowed(row.kind), + subtype: row.subtype, + payload_json: row.payload_json, + }); + } + + // `built_rows` has been consumed by value; drop key state before re-sorting. + drop(current_key); + + rows.sort_unstable_by(compare_event_rows); + + let mapped_len = rows.len(); + rows.dedup(); + stats.listing_duplicate_collapsed = mapped_len - rows.len(); + + let mut last_listing_id: Option = None; + for row in &rows { + if last_listing_id != Some(row.listing_id) { + stats.listings_out += 1; + last_listing_id = Some(row.listing_id); + } + match row.kind.as_ref() { + EVENT_KIND_FILING => stats.filings_out += 1, + EVENT_KIND_EARNINGS => stats.earnings_out += 1, + other => unreachable!("unexpected event kind from build_events: {other:?}"), + } + } + stats.rows_out = rows.len(); + + Ok(CurateEventsOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_events`] and publishing the resulting contract rows +/// via [`write_events_dataset`] to `/events/year=YYYY/part.parquet`. +/// +/// Any [`CurateEventsError`] returns before [`write_events_dataset`] is invoked, leaving +/// `out_dir` untouched. +pub fn curate_and_write_events( + out_dir: P, + filings: IF, + earnings: IE, + mapping_source: &str, + mapping: &ProviderMappingTable, + options: EventsWriteOptions, +) -> Result +where + P: AsRef, + K: Ord + Clone + AsRef, + IF: IntoIterator>, + IE: IntoIterator>, +{ + let curated = curate_events(filings, earnings, mapping_source, mapping)?; + let write_stats = write_events_dataset(out_dir, &curated.rows, options)?; + Ok(CurateEventsWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_events_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_events_tests.rs b/tools/curate-etl/src/curate_events_tests.rs new file mode 100644 index 00000000..d680c87e --- /dev/null +++ b/tools/curate-etl/src/curate_events_tests.rs @@ -0,0 +1,891 @@ +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::BTreeMap; +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::events::{ + build_events, partition_year_utc, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::provider_mapping::ProviderMappingRow; +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-events-{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 filing( + key: &str, + timefiled: &str, + form_type: &str, + filing_id: Option<&str>, + url: Option<&str>, +) -> QmFiling { + QmFiling { + key: key.to_string(), + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: filing_id.map(str::to_string), + url: url.map(str::to_string), + } +} + +fn earning( + key: &str, + report_date: i32, + announce_time: &str, + fiscal_period_end: Option, + actual_eps: Option, + revenue: Option, +) -> QmEarning { + QmEarning { + key: key.to_string(), + report_date, + announce_time: announce_time.to_string(), + fiscal_period_end, + actual_eps, + revenue, + } +} + +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: &CurateEventsOutput) { + 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_duplicate_collapsed, + "curate accounting conservation mismatch: {s:?}" + ); + assert_eq!( + s.rows_out, + s.filings_out + s.earnings_out, + "rows_out != filings_out + earnings_out: {s:?}" + ); + assert_eq!( + s.builder.filings_in, + s.builder.filings_out + + s.builder.filings_skipped_malformed_timestamp + + s.builder.filings_skipped_unknown_zone + + s.builder.filings_skipped_invalid_date_time + + s.builder.filings_duplicate_collapsed, + "builder filings conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.earnings_in, + s.builder.earnings_out + + s.builder.earnings_skipped_out_of_range + + s.builder.earnings_duplicate_collapsed + + s.builder.earnings_duplicate_conflict_dropped, + "builder earnings conservation mismatch: {s:?}" + ); + assert_eq!( + s.builder.rows_out, + s.builder.filings_out + s.builder.earnings_out + ); + + let mut distinct_listings = 0usize; + let mut prev_listing: Option = None; + let mut filings_count = 0usize; + let mut earnings_count = 0usize; + for row in &out.rows { + if prev_listing != Some(row.listing_id) { + distinct_listings += 1; + prev_listing = Some(row.listing_id); + } + match row.kind.as_ref() { + EVENT_KIND_FILING => filings_count += 1, + EVENT_KIND_EARNINGS => earnings_count += 1, + other => panic!("unexpected event kind: {other:?}"), + } + } + assert_eq!(s.listings_out, distinct_listings); + assert_eq!(s.filings_out, filings_count); + assert_eq!(s.earnings_out, earnings_count); + + for pair in out.rows.windows(2) { + assert_eq!( + compare_event_rows(&pair[0], &pair[1]), + Ordering::Less, + "output rows must be strictly ascending in 7-field writer key:\n left: {:?}\n right: {:?}", + pair[0], + pair[1] + ); + } +} + +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_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 read_events_parquet_file(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 ts_micros = read_i64_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 known_at_source = read_str_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let kind = read_str_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let subtype = read_str_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let payload_json = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(EventsParquetRow { + listing_id: listing_id[i], + ts_micros: ts_micros[i], + known_at_micros: known_at_micros[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + (footer_rows, out) +} + +fn read_all_events_partitions(out_dir: &Path) -> (BTreeMap>, Vec) { + let events_dir = out_dir.join("events"); + let mut by_year: BTreeMap> = BTreeMap::new(); + let mut all_rows: Vec = Vec::new(); + + for entry in fs::read_dir(&events_dir).expect("read events dir") { + let entry = entry.unwrap(); + let name = entry.file_name().to_string_lossy().into_owned(); + let year_str = name + .strip_prefix("year=") + .unwrap_or_else(|| panic!("unexpected entry '{name}' in {}", events_dir.display())); + let year: i32 = year_str + .parse() + .unwrap_or_else(|_| panic!("invalid year dir '{name}'")); + let year_dir = entry.path(); + + let mut saw_part = false; + for file_entry in fs::read_dir(&year_dir).expect("read year dir") { + let fname = file_entry.unwrap().file_name().to_string_lossy().into_owned(); + assert_eq!( + fname, + "part.parquet", + "unexpected transient file '{fname}' in {}", + year_dir.display() + ); + saw_part = true; + } + assert!(saw_part, "missing part.parquet in {}", year_dir.display()); + + let (footer_rows, rows) = read_events_parquet_file(&year_dir.join("part.parquet")); + assert_eq!(footer_rows, rows.len()); + all_rows.extend(rows.iter().cloned()); + by_year.insert(year, rows); + } + + all_rows.sort_unstable_by(compare_event_rows); + (by_year, all_rows) +} + +#[test] +fn happy_path_mixed_filings_and_earnings_multi_key_multi_year_round_trips_parquet() { + // Assign "QM_B" a smaller listing_id (10) than "QM_A" (20) to verify re-sorting by listing_id. + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "QM_A", day(2015, 1, 1), None, 20), + map_row("qm", "QM_B", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + let filings = vec![ + filing( + "QM_A", + "2023-11-02T16:30:00 EDT", + "8-K", + Some("ACC-A-2023"), + Some("https://sec.example/a-2023"), + ), + filing( + "QM_A", + "2024-02-28T07:15:00 EST", + "10-K", + Some("ACC-A-2024"), + None, + ), + filing( + "QM_B", + "2024-05-01T17:05:00 EDT", + "News release", + Some("NR-B-2024"), + Some("https://sedar.example/b-2024"), + ), + filing( + "QM_B", + "2025-03-10T08:00:00 EDT", + "Annual financial statements", + Some("AFS-B-2025"), + None, + ), + ]; + + let earnings = vec![ + // Linked to QM_A's 2023-11-02 8-K + earning( + "QM_A", + day(2023, 11, 2), + "AMC", + Some(day(2023, 9, 30)), + Some(1.42), + Some(500_000_000.0), + ), + // Unlinked on 2024-08-01 -> 16:05 EDT statutory lag + earning( + "QM_A", + day(2024, 8, 1), + "BTO", + Some(day(2024, 6, 30)), + Some(1.55), + Some(520_000_000.0), + ), + // Linked to QM_B's 2024-05-01 News release + earning( + "QM_B", + day(2024, 5, 1), + "N/A", + Some(day(2024, 3, 31)), + Some(0.38), + None, + ), + ]; + + let raw_built = build_events(filings.clone(), earnings.clone()); + let curated = curate_events(filings.clone(), earnings.clone(), "qm", &mapping).unwrap(); + + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.builder, raw_built.stats); + assert_eq!(curated.stats.rows_in, 7); + assert_eq!(curated.stats.rows_out, 7); + assert_eq!(curated.stats.listings_out, 2); + assert_eq!(curated.stats.filings_out, 4); + assert_eq!(curated.stats.earnings_out, 3); + assert_eq!(curated.stats.dropped_unmapped, 0); + assert_eq!(curated.stats.listing_duplicate_collapsed, 0); + + // Listing 10 (QM_B: 2 filings + 1 earnings = 3 rows) precedes Listing 20 (QM_A: 4 rows). + assert_eq!( + curated.rows.iter().map(|r| r.listing_id).collect::>(), + vec![10, 10, 10, 20, 20, 20, 20] + ); + + // Round-trip through curate_and_write_events and read back every year partition. + let tmp = TempDirGuard::new("happy-roundtrip"); + let report = curate_and_write_events( + tmp.path(), + filings, + earnings, + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + + assert_eq!(report.curate_stats, curated.stats); + assert_eq!(report.write_stats.rows_written, curated.rows.len()); + assert_eq!(report.write_stats.files_written, 3); // 2023, 2024, 2025 + + let (by_year, read_back_all) = read_all_events_partitions(tmp.path()); + assert_eq!(by_year.keys().copied().collect::>(), vec![2023, 2024, 2025]); + assert_eq!(read_back_all, curated.rows); + + // Verify each year partition contains exactly the rows whose UTC partition year matches. + for (year, year_rows) in &by_year { + let expected_for_year: Vec = curated + .rows + .iter() + .filter(|r| partition_year_utc(r.ts_micros) == *year) + .cloned() + .collect(); + assert_eq!(year_rows, &expected_for_year); + } +} + +#[test] +fn point_in_time_et_date_mapping_boundaries_late_evening_year_end_pre_2008_and_linked_earnings() { + // Ticker "SWITCH" changes listing on 2003-07-16 (pre-2008) and D = 2024-06-15: + // listing 90: 2000-01-01 ..= 2003-07-15 + // listing 100: 2003-07-16 ..= 2024-06-14 (D - 1) + // listing 200: 2024-06-15 ..= 2024-12-31 + // listing 300: 2025-01-01 .. (open-ended) + let d_pre2008_before = day(2003, 7, 15); + let d_pre2008_switch = day(2003, 7, 16); + let d_switch = day(2024, 6, 15); + let d_before = day(2024, 6, 14); + + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "SWITCH", day(2000, 1, 1), Some(d_pre2008_before), 90), + map_row("qm", "SWITCH", d_pre2008_switch, Some(d_before), 100), + map_row("qm", "SWITCH", d_switch, Some(day(2024, 12, 31)), 200), + map_row("qm", "SWITCH", day(2025, 1, 1), None, 300), + ]) + .unwrap(); + + let filings = vec![ + // (c) Pre-2008 afternoon filing (2003-07-15 EDT) -> listing 90 + filing( + "SWITCH", + "2003-07-15T14:30:00 EDT", + "10-Q", + Some("PRE-2008"), + None, + ), + // (c2) Pre-2008 late-evening filing (2003-07-15T22:30:00 EDT -> UTC 2003-07-16T02:30:00Z). + // Crosses the 2003-07-16 listing switch in UTC; must map on ET date 2003-07-15 -> OLD listing 90! + filing( + "SWITCH", + "2003-07-15T22:30:00 EDT", + "8-K", + Some("PRE-2008-LATE-EVE"), + None, + ), + // (a) Before switch date D -> listing 100 + filing( + "SWITCH", + "2024-06-14T10:00:00 EDT", + "10-Q", + Some("BEFORE-D"), + None, + ), + // (b) 23:30:00 EST on D-1 (2024-06-14) whose UTC timestamp is 2024-06-15T04:30:00Z (UTC date = D). + // Must resolve on ET date 2024-06-14 -> OLD listing 100, NOT listing 200! + // Also serves as the qualifying 8-K for (d) same-day linked earnings on report_date = D-1. + filing( + "SWITCH", + "2024-06-14T23:30:00 EST", + "8-K", + Some("LATE-EVE-D-MINUS-1"), + None, + ), + // (a) On switch date D -> NEW listing 200 + filing( + "SWITCH", + "2024-06-15T09:00:00 EDT", + "10-K", + Some("ON-D"), + None, + ), + // Dec 31 21:30:00 EST (UTC = 2025-01-01T02:30:00Z): + // Must resolve provider_mapping on ET date 2024-12-31 -> listing 200 (NOT listing 300), + // while partitioning into Parquet year=2025! + filing( + "SWITCH", + "2024-12-31T21:30:00 EST", + "8-K", + Some("DEC31-ROLLOVER"), + None, + ), + // On 2025-01-01 -> listing 300 + filing( + "SWITCH", + "2025-01-01T08:00:00 EST", + "10-K", + Some("NEW-YEAR-2025"), + None, + ), + ]; + + let earnings = vec![ + // (d) Linked to the late-evening 2024-06-14T23:30:00 EST 8-K (UTC date = 2024-06-15 = D). + // Must map on report_date = 2024-06-14 -> OLD listing 100! + earning( + "SWITCH", + d_before, + "AMC", + Some(day(2024, 3, 31)), + Some(0.75), + Some(10_000_000.0), + ), + ]; + + let curated = curate_events(filings.clone(), earnings.clone(), "qm", &mapping).unwrap(); + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.rows_out, 8); + assert_eq!(curated.stats.listings_out, 4); + assert_eq!(curated.stats.dropped_unmapped, 0); + + let listing_of = |needle: &str| -> i32 { + curated + .rows + .iter() + .find(|r| r.payload_json.contains(needle)) + .unwrap_or_else(|| panic!("missing row containing {needle}")) + .listing_id + }; + + assert_eq!(listing_of("PRE-2008"), 90); + assert_eq!(listing_of("PRE-2008-LATE-EVE"), 90); + assert_eq!(listing_of("BEFORE-D"), 100); + assert_eq!(listing_of("LATE-EVE-D-MINUS-1"), 100); + assert_eq!(listing_of("ON-D"), 200); + assert_eq!(listing_of("DEC31-ROLLOVER"), 200); + assert_eq!(listing_of("NEW-YEAR-2025"), 300); + + // Check the linked earnings row specifically. + let earn_row = curated + .rows + .iter() + .find(|r| r.kind.as_ref() == EVENT_KIND_EARNINGS) + .expect("earnings row present"); + assert_eq!(earn_row.listing_id, 100); + assert_eq!(earn_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(earn_row.payload_json.contains("LATE-EVE-D-MINUS-1")); + + // Verify Dec 31 21:30 EST row lands in year=2025/part.parquet with listing_id=200. + let tmp = TempDirGuard::new("year-end-rollover"); + let report = curate_and_write_events( + tmp.path(), + filings, + earnings, + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(report.write_stats.rows_written, 8); + + let (by_year, _) = read_all_events_partitions(tmp.path()); + assert_eq!(by_year.keys().copied().collect::>(), vec![2003, 2024, 2025]); + let y2025 = &by_year[&2025]; + assert_eq!(y2025.len(), 2); + let dec31_row = y2025 + .iter() + .find(|r| r.payload_json.contains("DEC31-ROLLOVER")) + .expect("DEC31-ROLLOVER in year=2025"); + assert_eq!(dec31_row.listing_id, 200); +} + +#[test] +fn drops_unmapped_keys_wrong_source_and_out_of_range_dates() { + // Ticker "GAPPED": + // listing 10: 2020-01-01 ..= 2021-12-31 + // gap: 2022-01-01 ..= 2022-12-31 + // listing 20: 2023-01-01 ..= 2024-12-31 + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "GAPPED", day(2020, 1, 1), Some(day(2021, 12, 31)), 10), + map_row("qm", "GAPPED", day(2023, 1, 1), Some(day(2024, 12, 31)), 20), + map_row("eod", "WRONGSRC", day(2015, 1, 1), None, 30), + ]) + .unwrap(); + + let filings = vec![ + filing("GAPPED", "2019-12-31T16:00:00 EST", "10-K", Some("PRE"), None), // pre-range + filing("GAPPED", "2020-01-01T09:00:00 EST", "10-K", Some("IN1"), None), // -> 10 + filing("GAPPED", "2022-06-15T12:00:00 EDT", "10-Q", Some("GAP"), None), // interior gap + filing("GAPPED", "2023-06-15T12:00:00 EDT", "10-Q", Some("IN2"), None), // -> 20 + filing("GAPPED", "2025-01-01T09:00:00 EST", "10-K", Some("POST"), None), // post-range + filing("UNKNOWN", "2023-06-15T12:00:00 EDT", "8-K", Some("UNK"), None), // unknown key + filing("WRONGSRC", "2023-06-15T12:00:00 EDT", "8-K", Some("WS"), None), // wrong source + ]; + + let earnings = vec![ + earning("GAPPED", day(2022, 5, 1), "AMC", None, Some(1.0), None), // interior gap + earning("GAPPED", day(2024, 5, 1), "AMC", None, Some(2.0), None), // -> 20 + ]; + + let curated = curate_events(filings, earnings, "qm", &mapping).unwrap(); + assert_conservation_and_order(&curated); + assert_eq!(curated.stats.rows_in, 9); + assert_eq!(curated.stats.rows_out, 3); + assert_eq!(curated.stats.listings_out, 2); + assert_eq!(curated.stats.filings_out, 2); + assert_eq!(curated.stats.earnings_out, 1); + assert_eq!(curated.stats.dropped_unmapped, 6); + assert_eq!(curated.stats.listing_duplicate_collapsed, 0); +} + +#[test] +fn cross_key_identical_seven_field_rows_collapse_while_any_single_field_difference_is_kept() { + // Keys "ALIAS_1" and "ALIAS_2" both map to listing_id 50. + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "ALIAS_1", day(2020, 1, 1), None, 50), + map_row("qm", "ALIAS_2", day(2020, 1, 1), None, 50), + ]) + .unwrap(); + + let d_earn = day(2024, 4, 15); + + let filings = vec![ + // 1. Exact 7-field duplicate across ALIAS_1 and ALIAS_2 -> collapses to 1 (+1 collapsed) + filing( + "ALIAS_1", + "2024-03-01T10:00:00 EST", + "10-K", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + filing( + "ALIAS_2", + "2024-03-01T10:00:00 EST", + "10-K", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + // 2. Differing only in ts_micros (and known_at_micros) -> both kept + filing( + "ALIAS_2", + "2024-03-01T10:00:01 EST", + "10-K", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + // 3. Differing in subtype (10-Q vs 10-K) at exact same timestamp -> kept + filing( + "ALIAS_2", + "2024-03-01T10:00:00 EST", + "10-Q", + Some("DUP-ID"), + Some("https://sec.example/dup"), + ), + // 4. Differing only in payload_json (different filing_id) at same timestamp + subtype -> kept + filing( + "ALIAS_2", + "2024-03-01T10:00:00 EST", + "10-K", + Some("DIFF-ID"), + Some("https://sec.example/dup"), + ), + // 5. Same timestamp as an earnings row, differing in kind ("filing" vs "earnings"), + // AND also creates a linked earnings row on ALIAS_1 at 16:05:00 EDT with + // filing_id = None, so ALIAS_1's earnings has known_at_source = "filing_timestamp" + // while ALIAS_2's unlinked earnings on the same report_date has the EXACT same + // ts_micros, known_at_micros, kind, subtype, payload_json, differing ONLY in + // known_at_source ("statutory_lag_estimate")! + filing("ALIAS_1", "2024-04-15T16:05:00 EDT", "8-K", None, None), + ]; + + let earnings = vec![ + // Linked on ALIAS_1 (16:05:00 EDT, filing_timestamp, linked_filing_id = null) + earning("ALIAS_1", d_earn, "AMC", Some(day(2024, 3, 31)), Some(1.0), Some(100.0)), + // Unlinked on ALIAS_2 (16:05:00 EDT, statutory_lag_estimate, linked_filing_id = null) + earning("ALIAS_2", d_earn, "AMC", Some(day(2024, 3, 31)), Some(1.0), Some(100.0)), + // Exact 7-field duplicate earnings across ALIAS_1 and ALIAS_2 on a different unlinked date -> collapses (+1) + earning("ALIAS_1", day(2024, 7, 15), "BTO", None, Some(2.0), None), + earning("ALIAS_2", day(2024, 7, 15), "BTO", None, Some(2.0), None), + ]; + + let curated = curate_events(filings, earnings, "qm", &mapping).unwrap(); + assert_conservation_and_order(&curated); + + // 6 filings in -> 6 out of builder; 4 earnings in -> 4 out of builder; total rows_in = 10. + // 2 exact 7-field duplicates collapse (1 filing + 1 earnings) -> 8 rows out. + assert_eq!(curated.stats.rows_in, 10); + assert_eq!(curated.stats.listing_duplicate_collapsed, 2); + assert_eq!(curated.stats.rows_out, 8); + assert_eq!(curated.stats.filings_out, 5); + assert_eq!(curated.stats.earnings_out, 3); + assert_eq!(curated.stats.listings_out, 1); + + // Confirm the two d_earn earnings rows differ ONLY in known_at_source and both survived. + let d_earn_rows: Vec<&EventsParquetRow> = curated + .rows + .iter() + .filter(|r| r.kind.as_ref() == EVENT_KIND_EARNINGS && r.payload_json.contains("2024-04-15")) + .collect(); + assert_eq!(d_earn_rows.len(), 2); + assert_eq!(d_earn_rows[0].listing_id, d_earn_rows[1].listing_id); + assert_eq!(d_earn_rows[0].ts_micros, d_earn_rows[1].ts_micros); + assert_eq!(d_earn_rows[0].known_at_micros, d_earn_rows[1].known_at_micros); + assert_eq!(d_earn_rows[0].kind, d_earn_rows[1].kind); + assert_eq!(d_earn_rows[0].subtype, d_earn_rows[1].subtype); + assert_eq!(d_earn_rows[0].payload_json, d_earn_rows[1].payload_json); + assert_eq!(d_earn_rows[0].known_at_source.as_ref(), KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(d_earn_rows[1].known_at_source.as_ref(), KNOWN_AT_SOURCE_STATUTORY_LAG); + + // Must be accepted cleanly by write_events_dataset without UnsortedInput or DuplicateRow. + let tmp = TempDirGuard::new("collapse-write"); + let write_stats = + write_events_dataset(tmp.path(), &curated.rows, EventsWriteOptions::default()).unwrap(); + assert_eq!(write_stats.rows_written, 8); +} + +#[test] +fn failure_modes_empty_inputs_and_out_dir_protection() { + let mapping = ProviderMappingTable::from_rows([ + map_row("qm", "QM_A", day(2015, 1, 1), None, 10), + ]) + .unwrap(); + + // 1. Blank and whitespace-only mapping_source return EmptyMappingSource. + for blank in ["", " ", "\t\n"] { + let err = curate_events( + [filing("QM_A", "2024-05-01T10:00:00 EDT", "10-Q", None, None)], + std::iter::empty::>(), + blank, + &mapping, + ) + .unwrap_err(); + assert_eq!(err, CurateEventsError::EmptyMappingSource); + assert!(err.source().is_none()); + assert!(err.to_string().contains("mapping_source")); + } + + // 2. Empty inputs return empty rows, zero stats, and create no events/ directory. + let empty = curate_events( + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + ) + .unwrap(); + assert_conservation_and_order(&empty); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, CurateEventsStats::default()); + + let fresh_tmp = TempDirGuard::new("empty-and-err"); + let empty_report = curate_and_write_events( + fresh_tmp.path(), + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_report.curate_stats, CurateEventsStats::default()); + assert_eq!(empty_report.write_stats, EventsWriteStats::default()); + assert!(!fresh_tmp.path().join("events").exists()); + + // 3. Curate error on fresh dir creates no events/ directory. + let err = curate_and_write_events( + fresh_tmp.path(), + [filing("QM_A", "2024-05-01T10:00:00 EDT", "10-Q", None, None)], + std::iter::empty::>(), + " ", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + CurateEventsWriteError::Curate(CurateEventsError::EmptyMappingSource) + )); + assert!(err.source().is_some()); + assert!(err.to_string().contains("curation failed")); + assert!(!fresh_tmp.path().join("events").exists()); + + // 4. Curate error on pre-existing out_dir leaves live part.parquet byte-identical. + let existing_tmp = TempDirGuard::new("preexisting-protect"); + curate_and_write_events( + existing_tmp.path(), + [filing("QM_A", "2024-05-01T10:00:00 EDT", "10-Q", Some("F1"), None)], + std::iter::empty::>(), + "qm", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap(); + let part_path = existing_tmp.path().join("events/year=2024/part.parquet"); + let before_bytes = fs::read(&part_path).expect("read live part.parquet"); + + let err_existing = curate_and_write_events( + existing_tmp.path(), + [filing("QM_A", "2024-05-02T10:00:00 EDT", "10-K", Some("F2"), None)], + std::iter::empty::>(), + "", + &mapping, + EventsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err_existing, + CurateEventsWriteError::Curate(CurateEventsError::EmptyMappingSource) + )); + assert_eq!(fs::read(&part_path).unwrap(), before_bytes); + + // 5. Invalid EventsWriteOptions surfaces as CurateEventsWriteError::Parquet. + let pq_err = curate_and_write_events( + fresh_tmp.path(), + std::iter::empty::>(), + std::iter::empty::>(), + "qm", + &mapping, + EventsWriteOptions { + row_group_rows: 0, + ..EventsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + pq_err, + CurateEventsWriteError::Parquet(ParquetEventsError::InvalidRowGroupRows) + )); + assert!(pq_err.source().is_some()); + assert!(pq_err.to_string().contains("Parquet write failed")); +} + +#[test] +fn permutation_invariance_including_contrived_mismatched_zone_duplicates() { + 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 mapping = ProviderMappingTable::from_rows([ + map_row("qm", "K1", day(2000, 1, 1), Some(day(2024, 6, 1)), 10), + map_row("qm", "K1", day(2024, 6, 2), None, 20), + map_row("qm", "K2", day(2000, 1, 1), None, 10), + map_row("qm", "K3", day(2020, 1, 1), Some(day(2023, 12, 31)), 30), + ]) + .unwrap(); + + // Include contrived mismatched-zone duplicate filings on K1 that resolve to the exact same + // UTC instant (2024-06-02T04:30:00Z) but have different ET dates (2024-06-01 vs 2024-06-02), + // straddling K1's listing switch. `event_date_tiebreak()` ensures both permutations collapse + // deterministically to the same event_date (2024-06-01 -> listing 10). + let filings = vec![ + filing("K1", "2024-06-02T00:30:00 EDT", "8-K", Some("MISMATCH"), None), + filing("K1", "2024-06-01T23:30:00 EST", "8-K", Some("MISMATCH"), None), + filing("K1", "2003-04-10T11:00:00 EDT", "10-K", Some("OLD-K1"), None), + filing("K2", "2024-06-01T23:30:00 EST", "8-K", Some("MISMATCH"), None), + filing("K2", "2024-07-01T16:00:00 EDT", "10-Q", Some("K2-Q2"), None), + filing("K3", "2023-12-31T22:00:00 EST", "News release", Some("K3-NR"), None), + filing("K3", "2024-01-02T09:00:00 EST", "10-K", Some("K3-POST"), None), // unmapped + filing("GHOST", "2024-05-01T12:00:00 EDT", "8-K", Some("G1"), None), // unmapped + filing("K1", "bad-ts", "8-K", None, None), // builder skip + ]; + + let earnings = vec![ + earning("K1", day(2024, 6, 1), "AMC", Some(day(2024, 3, 31)), Some(1.1), Some(50.0)), + earning("K2", day(2024, 6, 1), "AMC", Some(day(2024, 3, 31)), Some(1.1), Some(50.0)), + earning("K3", day(2023, 12, 31), "N/A", None, Some(0.5), None), + earning("K3", day(2024, 5, 1), "BTO", None, Some(0.6), None), // unmapped + ]; + + let baseline = curate_events(filings.clone(), earnings.clone(), "qm", &mapping).unwrap(); + assert_conservation_and_order(&baseline); + assert!(baseline.stats.dropped_unmapped > 0); + assert!(baseline.stats.listing_duplicate_collapsed > 0); + assert!(baseline.stats.builder.filings_duplicate_collapsed > 0); + + // Reversed order + let mut rev_f = filings.clone(); + let mut rev_e = earnings.clone(); + rev_f.reverse(); + rev_e.reverse(); + let rev_out = curate_events(rev_f, rev_e, "qm", &mapping).unwrap(); + assert_eq!(rev_out, baseline); + + // Multiple fixed-seed Fisher-Yates shuffles + for seed in [0x1111_2222_3333_4444u64, 0xAAAA_BBBB_CCCC_DDDDu64, 0x570C_4B07_E7E4_7511u64] { + let mut shuf_f = filings.clone(); + let mut shuf_e = earnings.clone(); + let mut rng = SplitMix64(seed); + for i in (1..shuf_f.len()).rev() { + let j = (rng.next_u64() as usize) % (i + 1); + shuf_f.swap(i, j); + } + for i in (1..shuf_e.len()).rev() { + let j = (rng.next_u64() as usize) % (i + 1); + shuf_e.swap(i, j); + } + let shuf_out = curate_events(shuf_f, shuf_e, "qm", &mapping).unwrap(); + assert_eq!(shuf_out, baseline); + } +} diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs index 9c9ef553..e1f6b52b 100644 --- a/tools/curate-etl/src/events.rs +++ b/tools/curate-etl/src/events.rs @@ -654,22 +654,66 @@ impl NormalizedEarning { } } -/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and -/// `qmEarnings` streams. -/// -/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range -/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking. -/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`. -pub fn build_events(filings: IF, earnings: IE) -> EventsBuild +/// Crate-internal [`EventRow`] paired with its exact Eastern local calendar date (`et_date` for +/// filings, `report_date` for earnings) for point-in-time `provider_mapping` resolution across all +/// supported years (including pre-2008 filings and late-evening ET rollovers). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct EventRowWithDate { + pub(crate) row: EventRow, + pub(crate) event_date: i32, +} + +trait EventRecord: Sized { + fn from_parts(row: EventRow, event_date: i32) -> Self; + fn event_row(&self) -> &EventRow; + fn event_date_tiebreak(&self) -> i32; +} + +impl EventRecord for EventRow { + #[inline] + fn from_parts(row: EventRow, _event_date: i32) -> Self { + row + } + + #[inline] + fn event_row(&self) -> &EventRow { + self + } + + #[inline] + fn event_date_tiebreak(&self) -> i32 { + 0 + } +} + +impl EventRecord for EventRowWithDate { + #[inline] + fn from_parts(row: EventRow, event_date: i32) -> Self { + Self { row, event_date } + } + + #[inline] + fn event_row(&self) -> &EventRow { + &self.row + } + + #[inline] + fn event_date_tiebreak(&self) -> i32 { + self.event_date + } +} + +fn build_events_impl(filings: IF, earnings: IE) -> (Vec, EventsStats) where K: Ord + Clone, + R: EventRecord, IF: IntoIterator>, IE: IntoIterator>, { let filings_iter = filings.into_iter(); let (filings_lower, _) = filings_iter.size_hint(); let mut stats = EventsStats::default(); - let mut rows: Vec> = Vec::with_capacity(filings_lower); + let mut rows: Vec = Vec::with_capacity(filings_lower); let mut links: Vec> = Vec::new(); for filing in filings_iter { @@ -710,15 +754,18 @@ where }); } - rows.push(EventRow { - key: filing.key, - ts_micros: parsed.utc_micros, - known_at_micros: parsed.utc_micros, - known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, - kind: EVENT_KIND_FILING, - subtype: group.as_str().to_string(), - payload_json, - }); + rows.push(R::from_parts( + EventRow { + key: filing.key, + ts_micros: parsed.utc_micros, + known_at_micros: parsed.utc_micros, + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + kind: EVENT_KIND_FILING, + subtype: group.as_str().to_string(), + payload_json, + }, + parsed.et_date, + )); } // Retain the strictly earliest deterministic qualifying filing per (key, et_date). @@ -735,18 +782,23 @@ where // Collapse exact duplicate filing rows. rows.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) + let ra = a.event_row(); + let rb = b.event_row(); + ra.key + .cmp(&rb.key) + .then_with(|| ra.ts_micros.cmp(&rb.ts_micros)) + .then_with(|| ra.subtype.cmp(&rb.subtype)) + .then_with(|| ra.payload_json.cmp(&rb.payload_json)) + .then_with(|| a.event_date_tiebreak().cmp(&b.event_date_tiebreak())) }); let filings_before_dedup = rows.len(); rows.dedup_by(|b, a| { - a.key == b.key - && a.ts_micros == b.ts_micros - && a.subtype == b.subtype - && a.payload_json == b.payload_json + let ra = a.event_row(); + let rb = b.event_row(); + ra.key == rb.key + && ra.ts_micros == rb.ts_micros + && ra.subtype == rb.subtype + && ra.payload_json == rb.payload_json }); stats.filings_duplicate_collapsed = filings_before_dedup - rows.len(); stats.filings_out = rows.len(); @@ -845,15 +897,18 @@ where first.report_date, first.revenue, ); - rows.push(EventRow { - key: first.key.clone(), - ts_micros: first.ts_micros, - known_at_micros: first.ts_micros, - known_at_source: first.known_at_source, - kind: EVENT_KIND_EARNINGS, - subtype: first.subtype.to_string(), - payload_json, - }); + rows.push(R::from_parts( + EventRow { + key: first.key.clone(), + ts_micros: first.ts_micros, + known_at_micros: first.ts_micros, + known_at_source: first.known_at_source, + kind: EVENT_KIND_EARNINGS, + subtype: first.subtype.to_string(), + payload_json, + }, + first.report_date, + )); } else { stats.earnings_duplicate_conflict_dropped += group_len; } @@ -864,20 +919,24 @@ where stats.earnings_out = stats.earnings_linked_to_filing + stats.earnings_lagged_1605; rows.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.ts_micros.cmp(&b.ts_micros)) - .then_with(|| a.kind.cmp(b.kind)) - .then_with(|| a.subtype.cmp(&b.subtype)) - .then_with(|| a.payload_json.cmp(&b.payload_json)) - .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) - .then_with(|| a.known_at_source.cmp(b.known_at_source)) + let ra = a.event_row(); + let rb = b.event_row(); + ra.key + .cmp(&rb.key) + .then_with(|| ra.ts_micros.cmp(&rb.ts_micros)) + .then_with(|| ra.kind.cmp(rb.kind)) + .then_with(|| ra.subtype.cmp(&rb.subtype)) + .then_with(|| ra.payload_json.cmp(&rb.payload_json)) + .then_with(|| ra.known_at_micros.cmp(&rb.known_at_micros)) + .then_with(|| ra.known_at_source.cmp(rb.known_at_source)) + .then_with(|| a.event_date_tiebreak().cmp(&b.event_date_tiebreak())) }); stats.rows_out = rows.len(); let mut keys_out = 0usize; let mut prev_key: Option<&K> = None; - for row in &rows { + for item in &rows { + let row = item.event_row(); if prev_key != Some(&row.key) { keys_out += 1; prev_key = Some(&row.key); @@ -885,6 +944,36 @@ where } stats.keys_out = keys_out; + (rows, stats) +} + +/// Crate-internal entry point returning each [`EventRow`] alongside its exact Eastern local +/// calendar date (`ParsedFilingTime::et_date` for filings, `QmEarning::report_date` for earnings). +pub(crate) fn build_events_with_dates( + filings: IF, + earnings: IE, +) -> (Vec>, EventsStats) +where + K: Ord + Clone, + IF: IntoIterator>, + IE: IntoIterator>, +{ + build_events_impl(filings, earnings) +} + +/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and +/// `qmEarnings` streams. +/// +/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range +/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking. +/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`. +pub fn build_events(filings: IF, earnings: IE) -> EventsBuild +where + K: Ord + Clone, + IF: IntoIterator>, + IE: IntoIterator>, +{ + let (rows, stats) = build_events_impl(filings, earnings); EventsBuild { rows, stats } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index c08bccfd..021556cc 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -108,3 +108,9 @@ pub use curate_shorts::{ curate_and_write_shorts, curate_shorts, CurateShortsError, CurateShortsOutput, CurateShortsStats, CurateShortsWriteError, CurateShortsWriteReport, }; + +pub mod curate_events; +pub use curate_events::{ + curate_and_write_events, curate_events, CurateEventsError, CurateEventsOutput, + CurateEventsStats, CurateEventsWriteError, CurateEventsWriteReport, +}; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index b9034cfa..0be131f4 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -5,8 +5,9 @@ use std::process::ExitCode; use curate_etl::bench::{ run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, - run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_shorts_benchmark, - run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, + run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_events_benchmark, + run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark, + run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, @@ -630,6 +631,70 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchCurateEvents(rows)) => { + let report = match run_curate_events_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-events 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-events"); + println!( + " input: rows={} filings={} earnings={} keys={}", + report.rows, report.filings_in, report.earnings_in, report.key_count + ); + println!( + " builder: rows_out={} filings_out={} earnings_out={} malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={}", + report.stats.builder.rows_out, + report.stats.builder.filings_out, + report.stats.builder.earnings_out, + report.stats.builder.filings_skipped_malformed_timestamp, + report.stats.builder.filings_skipped_unknown_zone, + report.stats.builder.filings_skipped_invalid_date_time, + report.stats.builder.filings_duplicate_collapsed, + report.stats.builder.earnings_linked_to_filing, + report.stats.builder.earnings_lagged_1605, + report.stats.builder.earnings_skipped_out_of_range, + report.stats.builder.earnings_duplicate_collapsed, + report.stats.builder.earnings_duplicate_conflict_dropped + ); + println!( + " stage: rows_out={} ({:.2}% retained) filings_out={} earnings_out={} listings_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + retention_pct, + report.stats.filings_out, + report.stats.earnings_out, + 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={} dup_collapsed={}", + report.stats.dropped_unmapped, report.stats.listing_duplicate_collapsed + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME));