diff --git a/tools/curate-etl/tests/shorts_reference.rs b/tools/curate-etl/tests/shorts_reference.rs new file mode 100644 index 00000000..b50101ea --- /dev/null +++ b/tools/curate-etl/tests/shorts_reference.rs @@ -0,0 +1,463 @@ +//! Independent reference / point-in-time QA tests for the `shorts` builder (T-76 / M1.2f). +//! +//! Oracles here are written independently of `src/shorts.rs`: +//! - the full TSX market-holiday list for `2017..=2027` (the `ceoShorts` data window plus a year +//! of headroom), typed out by hand from the published TSX holiday schedules; +//! - `America/Toronto` DST switch dates for `2008..=2030`, extracted from the system IANA tzdata +//! (`zoneinfo.ZoneInfo("America/Toronto")` offset changes at 12:00 local). +//! +//! Point-in-time checks follow the leakage lens: `known_at` is strictly after the whole report +//! day in Toronto, adding later reports ("poison") never moves earlier rows, and an out-of-range +//! date fails the build wherever it appears in the input. + +use std::collections::BTreeSet; + +use curate_etl::bench::{run_shorts_benchmark, DEFAULT_SHORTS_BENCH_ROWS}; +use curate_etl::{ + add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, + is_canadian_business_day, ymd_to_epoch_days, CeoShortReport, ShortsError, MAX_SUPPORTED_DATE, + MIN_SUPPORTED_DATE, SHORTS_LAG_BUSINESS_DAYS, +}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 24 * MICROS_PER_HOUR; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn is_weekend(epoch_day: i32) -> bool { + // 1970-01-01 was a Thursday; 0 = Thursday, 2 = Saturday, 3 = Sunday. + matches!(epoch_day.rem_euclid(7), 2 | 3) +} + +#[rustfmt::skip] +/// Every TSX full-day market closure on a weekday, 2017..=2027. +const TSX_HOLIDAYS_2017_2027: &[(i32, u32, u32)] = &[ + // 2017 (Jan 1 Sun, Jul 1 Sat) + (2017, 1, 2), (2017, 2, 20), (2017, 4, 14), (2017, 5, 22), (2017, 7, 3), + (2017, 8, 7), (2017, 9, 4), (2017, 10, 9), (2017, 12, 25), (2017, 12, 26), + // 2018 (Jul 1 Sun) + (2018, 1, 1), (2018, 2, 19), (2018, 3, 30), (2018, 5, 21), (2018, 7, 2), + (2018, 8, 6), (2018, 9, 3), (2018, 10, 8), (2018, 12, 25), (2018, 12, 26), + // 2019 + (2019, 1, 1), (2019, 2, 18), (2019, 4, 19), (2019, 5, 20), (2019, 7, 1), + (2019, 8, 5), (2019, 9, 2), (2019, 10, 14), (2019, 12, 25), (2019, 12, 26), + // 2020 (Dec 25 Fri -> Boxing Day Mon Dec 28) + (2020, 1, 1), (2020, 2, 17), (2020, 4, 10), (2020, 5, 18), (2020, 7, 1), + (2020, 8, 3), (2020, 9, 7), (2020, 10, 12), (2020, 12, 25), (2020, 12, 28), + // 2021 (Dec 25 Sat -> Mon 27 / Tue 28; Victoria Day is May 24 itself) + (2021, 1, 1), (2021, 2, 15), (2021, 4, 2), (2021, 5, 24), (2021, 7, 1), + (2021, 8, 2), (2021, 9, 6), (2021, 10, 11), (2021, 12, 27), (2021, 12, 28), + // 2022 (Jan 1 Sat -> Mon Jan 3; Dec 25 Sun -> Mon 26 / Tue 27) + (2022, 1, 3), (2022, 2, 21), (2022, 4, 15), (2022, 5, 23), (2022, 7, 1), + (2022, 8, 1), (2022, 9, 5), (2022, 10, 10), (2022, 12, 26), (2022, 12, 27), + // 2023 (Jan 1 Sun, Jul 1 Sat) + (2023, 1, 2), (2023, 2, 20), (2023, 4, 7), (2023, 5, 22), (2023, 7, 3), + (2023, 8, 7), (2023, 9, 4), (2023, 10, 9), (2023, 12, 25), (2023, 12, 26), + // 2024 + (2024, 1, 1), (2024, 2, 19), (2024, 3, 29), (2024, 5, 20), (2024, 7, 1), + (2024, 8, 5), (2024, 9, 2), (2024, 10, 14), (2024, 12, 25), (2024, 12, 26), + // 2025 + (2025, 1, 1), (2025, 2, 17), (2025, 4, 18), (2025, 5, 19), (2025, 7, 1), + (2025, 8, 4), (2025, 9, 1), (2025, 10, 13), (2025, 12, 25), (2025, 12, 26), + // 2026 (Dec 25 Fri -> Boxing Day Mon Dec 28) + (2026, 1, 1), (2026, 2, 16), (2026, 4, 3), (2026, 5, 18), (2026, 7, 1), + (2026, 8, 3), (2026, 9, 7), (2026, 10, 12), (2026, 12, 25), (2026, 12, 28), + // 2027 (Easter Mar 28; Dec 25 Sat -> Mon 27 / Tue 28) + (2027, 1, 1), (2027, 2, 15), (2027, 3, 26), (2027, 5, 24), (2027, 7, 1), + (2027, 8, 2), (2027, 9, 6), (2027, 10, 11), (2027, 12, 27), (2027, 12, 28), +]; + +/// `(year, (month, day) of DST start Sunday, (month, day) of DST end Sunday)`. +type DstSwitches = (i32, (u32, u32), (u32, u32)); + +/// `America/Toronto` DST switch Sundays per year from IANA tzdata. +#[rustfmt::skip] +const TZDATA_DST_2008_2030: &[DstSwitches] = &[ + (2008, (3, 9), (11, 2)), (2009, (3, 8), (11, 1)), (2010, (3, 14), (11, 7)), + (2011, (3, 13), (11, 6)), (2012, (3, 11), (11, 4)), (2013, (3, 10), (11, 3)), + (2014, (3, 9), (11, 2)), (2015, (3, 8), (11, 1)), (2016, (3, 13), (11, 6)), + (2017, (3, 12), (11, 5)), (2018, (3, 11), (11, 4)), (2019, (3, 10), (11, 3)), + (2020, (3, 8), (11, 1)), (2021, (3, 14), (11, 7)), (2022, (3, 13), (11, 6)), + (2023, (3, 12), (11, 5)), (2024, (3, 10), (11, 3)), (2025, (3, 9), (11, 2)), + (2026, (3, 8), (11, 1)), (2027, (3, 14), (11, 7)), (2028, (3, 12), (11, 5)), + (2029, (3, 11), (11, 4)), (2030, (3, 10), (11, 3)), +]; + +fn tzdata_offset_hours_at_local(epoch_day: i32, hour: u8) -> i64 { + let (y, _, _) = epoch_days_to_ymd(epoch_day); + let &(_, (sm, sd), (em, ed)) = TZDATA_DST_2008_2030 + .iter() + .find(|(year, _, _)| *year == y) + .expect("year in tzdata table"); + let (start, end) = (day(y, sm, sd), day(y, em, ed)); + let edt = if epoch_day == start { + hour >= 3 + } else if epoch_day == end { + hour < 1 + } else { + epoch_day > start && epoch_day < end + }; + if edt { + 4 + } else { + 5 + } +} + +#[test] +fn calendar_matches_hand_typed_tsx_holiday_list_for_every_day_2017_to_2027() { + let holidays: BTreeSet = TSX_HOLIDAYS_2017_2027 + .iter() + .map(|&(y, m, d)| day(y, m, d)) + .collect(); + assert_eq!(holidays.len(), 110, "10 TSX weekday closures per year"); + assert!(holidays.iter().all(|&h| !is_weekend(h))); + + let mut mismatches = Vec::new(); + for d in day(2017, 1, 1)..=day(2027, 12, 31) { + let expected = !is_weekend(d) && !holidays.contains(&d); + let actual = is_canadian_business_day(d).expect("in supported range"); + if expected != actual { + mismatches.push((epoch_days_to_ymd(d), expected, actual)); + } + } + assert!(mismatches.is_empty(), "calendar mismatches: {mismatches:?}"); +} + +#[test] +fn every_supported_year_has_exactly_ten_weekday_closures_and_no_weekend_business_days() { + for year in 2008..=2030 { + let mut weekday_closures = 0; + for d in day(year, 1, 1)..=day(year, 12, 31) { + let business = is_canadian_business_day(d).unwrap(); + if is_weekend(d) { + assert!( + !business, + "weekend {:?} marked business", + epoch_days_to_ymd(d) + ); + } else if !business { + weekday_closures += 1; + } + } + // 9 holidays, Christmas/Boxing counted as two closures; observance never lands on a + // weekend and never collides with another holiday. + assert_eq!(weekday_closures, 10, "year {year}"); + } +} + +#[test] +fn et_to_utc_matches_tzdata_for_every_supported_day_at_17_00_and_16_05() { + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + for (hour, minute) in [(17_u8, 0_u8), (16, 5), (0, 0), (23, 59)] { + let offset = tzdata_offset_hours_at_local(d, hour); + let expected = i64::from(d) * MICROS_PER_DAY + + (i64::from(hour) + offset) * MICROS_PER_HOUR + + i64::from(minute) * 60_000_000; + assert_eq!( + et_to_utc_micros(d, hour, minute, 0), + Ok(expected), + "{:?} {hour:02}:{minute:02}", + epoch_days_to_ymd(d) + ); + } + } +} + +#[test] +fn dst_switch_instants_are_continuous_in_utc() { + for &(y, (sm, sd), (em, ed)) in TZDATA_DST_2008_2030 { + // Spring forward: 01:59:59 EST and 03:00:00 EDT are one second apart in UTC. + let start = day(y, sm, sd); + let before = et_to_utc_micros(start, 1, 59, 59).unwrap(); + let after = et_to_utc_micros(start, 3, 0, 0).unwrap(); + assert_eq!(after - before, 1_000_000, "spring {y}"); + assert!(matches!( + et_to_utc_micros(start, 2, 0, 0), + Err(ShortsError::NonexistentLocalTime { .. }) + )); + assert!(matches!( + et_to_utc_micros(start, 2, 59, 59), + Err(ShortsError::NonexistentLocalTime { .. }) + )); + + // Fall back: 00:59:59 EDT -> 02:00:00 EST spans 2h01s of real time. + let end = day(y, em, ed); + let before = et_to_utc_micros(end, 0, 59, 59).unwrap(); + let after = et_to_utc_micros(end, 2, 0, 0).unwrap(); + assert_eq!(after - before, 2 * MICROS_PER_HOUR + 1_000_000, "fall {y}"); + assert!(matches!( + et_to_utc_micros(end, 1, 0, 0), + Err(ShortsError::AmbiguousLocalTime { .. }) + )); + } +} + +#[test] +fn plus_four_business_days_is_exact_for_every_supported_start_date() { + let mut first_error_start = None; + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + match add_canadian_business_days(d, SHORTS_LAG_BUSINESS_DAYS) { + Ok(r) => { + assert!(r > d); + assert!(is_canadian_business_day(r).unwrap()); + let counted = ((d + 1)..=r) + .filter(|&x| is_canadian_business_day(x).unwrap()) + .count(); + assert_eq!(counted, 4, "start {:?}", epoch_days_to_ymd(d)); + // Worst case is a Fri Christmas + Mon Boxing Day + Fri New Year's run + // (e.g. 2009-12-24 -> 2010-01-04 = 11 calendar days). + assert!(r - d <= 11, "start {:?}", epoch_days_to_ymd(d)); + assert!( + first_error_start.is_none(), + "error must only happen at the tail" + ); + } + Err(ShortsError::DateOutOfRange { epoch_day, .. }) => { + assert_eq!(epoch_day, MAX_SUPPORTED_DATE + 1); + first_error_start.get_or_insert(d); + } + Err(other) => panic!("unexpected error {other:?}"), + } + } + // 2030-12-24 (Tue) -> Fri 27, Mon 30, Tue 31, then out of range; 2030-12-23 -> 2030-12-31. + assert_eq!(first_error_start, Some(day(2030, 12, 24))); + assert_eq!( + add_canadian_business_days(day(2030, 12, 23), 4), + Ok(day(2030, 12, 31)) + ); + assert_eq!( + add_canadian_business_days(day(2009, 12, 24), 4), + Ok(day(2010, 1, 4)) + ); +} + +#[test] +fn every_semi_monthly_report_date_in_dataset_window_resolves() { + // ceoShorts report dates: the 15th and month-end, Apr 2017 .. Dec 2027. + for y in 2017..=2027 { + for m in 1..=12_u32 { + let next = if m == 12 { + day(y + 1, 1, 1) + } else { + day(y, m + 1, 1) + }; + for report_date in [day(y, m, 15), next - 1] { + let built = build_shorts(vec![CeoShortReport { + key: 1_i32, + report_date, + shares_short: 1.0, + net_change: None, + pct_float: None, + }]) + .expect("dataset window must be fully supported"); + assert_eq!(built.rows.len(), 1); + } + } + } +} + +#[test] +fn known_at_is_strictly_after_the_whole_toronto_report_day_and_on_known_at_date() { + let mut input = Vec::new(); + for (i, d) in (day(2017, 4, 1)..=day(2027, 12, 31)).step_by(3).enumerate() { + input.push(CeoShortReport { + key: (i % 7) as i32, + report_date: d, + shares_short: 100.0 + i as f64, + net_change: None, + pct_float: None, + }); + } + let built = build_shorts(input).unwrap(); + assert!(built.rows.len() > 1_000); + for row in &built.rows { + let end_of_report_day_utc = et_to_utc_micros(row.report_date, 23, 59, 59).unwrap(); + assert!(row.known_at_utc_micros > end_of_report_day_utc); + // 17:00 ET is 21:00/22:00 UTC, so the UTC calendar day equals known_at_date. + assert_eq!( + row.known_at_utc_micros.div_euclid(MICROS_PER_DAY), + i64::from(row.known_at_date) + ); + let hour_utc = row.known_at_utc_micros.rem_euclid(MICROS_PER_DAY) / MICROS_PER_HOUR; + let expected_hour = 17 + tzdata_offset_hours_at_local(row.known_at_date, 17); + assert_eq!(hour_utc, expected_hour); + assert_eq!( + row.known_at_date, + add_canadian_business_days(row.report_date, 4).unwrap() + ); + } +} + +#[test] +fn appending_future_reports_and_poison_rows_never_moves_earlier_rows() { + let base_dates = [day(2024, 1, 15), day(2024, 1, 31), day(2024, 2, 15)]; + let mut base = Vec::new(); + for key in 1..=3_i32 { + for (i, &d) in base_dates.iter().enumerate() { + base.push(CeoShortReport { + key, + report_date: d, + shares_short: f64::from(key * 1_000 + i as i32), + net_change: Some(10.0), + pct_float: Some(0.5), + }); + } + } + let before = build_shorts(base.clone()).unwrap(); + + let mut poisoned = base; + // Absurd later reports for the same keys, a conflicting pair and a bad row for a later date. + for key in 1..=3_i32 { + poisoned.push(CeoShortReport { + key, + report_date: day(2024, 2, 29), + shares_short: 1e15, + net_change: Some(-1e15), + pct_float: Some(9_999.0), + }); + } + poisoned.push(CeoShortReport { + key: 2, + report_date: day(2024, 3, 15), + shares_short: 1.0, + net_change: None, + pct_float: None, + }); + poisoned.push(CeoShortReport { + key: 2, + report_date: day(2024, 3, 15), + shares_short: 2.0, + net_change: None, + pct_float: None, + }); + poisoned.push(CeoShortReport { + key: 3, + report_date: day(2024, 3, 15), + shares_short: f64::NAN, + net_change: None, + pct_float: None, + }); + let after = build_shorts(poisoned).unwrap(); + + let earlier: Vec<_> = after + .rows + .iter() + .filter(|r| r.report_date <= day(2024, 2, 15)) + .cloned() + .collect(); + assert_eq!(earlier, before.rows); + assert_eq!(after.rows.len(), before.rows.len() + 3); + assert_eq!(after.stats.duplicate_conflict_dropped, 2); + assert_eq!(after.stats.dropped_invalid_shares_short, 1); +} + +#[test] +fn out_of_range_row_fails_build_regardless_of_position_and_other_rows() { + let good = |key: i32| CeoShortReport { + key, + report_date: day(2024, 6, 14), + shares_short: 5.0, + net_change: None, + pct_float: None, + }; + for bad_date in [day(2007, 12, 31), day(2030, 12, 28), i32::MIN, i32::MAX] { + for pos in 0..=3 { + let mut rows = vec![good(1), good(2), good(3)]; + rows.insert( + pos, + CeoShortReport { + key: 9, + report_date: bad_date, + shares_short: f64::NAN, + net_change: None, + pct_float: None, + }, + ); + assert!( + matches!(build_shorts(rows), Err(ShortsError::DateOutOfRange { .. })), + "bad date {bad_date} at position {pos}" + ); + } + } +} + +#[test] +fn signed_and_unsigned_zero_or_nan_payloads_do_not_create_false_conflicts() { + let d = day(2025, 5, 15); + let rows = vec![ + CeoShortReport { + key: "X", + report_date: d, + shares_short: 10.0, + net_change: Some(f64::NAN), + pct_float: Some(-0.0), + }, + CeoShortReport { + key: "X", + report_date: d, + // Different NaN payload / infinity must sanitise to the same `None`. + shares_short: 10.0, + net_change: Some(f64::from_bits(0x7ff8_0000_0000_0001)), + pct_float: Some(0.0), + }, + CeoShortReport { + key: "X", + report_date: d, + shares_short: 10.0, + net_change: Some(f64::INFINITY), + pct_float: Some(0.0), + }, + ]; + let built = build_shorts(rows).unwrap(); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.stats.duplicate_collapsed, 2); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); + assert_eq!(built.stats.nulled_invalid_net_change, 3); + assert_eq!(built.rows[0].net_change, None); + assert_eq!( + built.rows[0].pct_float.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + + // A valid row sharing a (key, date) with an invalid-shares row is not treated as a conflict. + let built = build_shorts(vec![ + CeoShortReport { + key: "Y", + report_date: d, + shares_short: -1.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: "Y", + report_date: d, + shares_short: 7.0, + net_change: None, + pct_float: None, + }, + ]) + .unwrap(); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].shares_short, 7.0); + assert_eq!(built.stats.dropped_invalid_shares_short, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); +} + +#[test] +fn default_bench_shorts_matches_readme_recorded_output() { + // README records rows_out=528426, keys_out=12500, checksum 0x1a99126eaa1a519b and the stats + // line below for `cargo run --release -p curate-etl --offline -- bench-shorts`. + let report = run_shorts_benchmark(DEFAULT_SHORTS_BENCH_ROWS).expect("bench builds"); + assert_eq!(DEFAULT_SHORTS_BENCH_ROWS, 700_000); + assert_eq!(report.rows_out, 528_426); + assert_eq!(report.keys_out, 12_500); + assert_eq!(report.stats.dropped_invalid_shares_short, 6_915); + assert_eq!(report.stats.nulled_invalid_net_change, 3_673); + assert_eq!(report.stats.nulled_invalid_pct_float, 3_500); + assert_eq!(report.stats.duplicate_collapsed, 5_352); + assert_eq!(report.stats.duplicate_conflict_dropped, 159_307); + assert_eq!(report.checksum, 0x1a99_126e_aa1a_519b); +}