diff --git a/tools/curate-etl/tests/fx_reference.rs b/tools/curate-etl/tests/fx_reference.rs new file mode 100644 index 00000000..45fe646b --- /dev/null +++ b/tools/curate-etl/tests/fx_reference.rs @@ -0,0 +1,427 @@ +//! QA differential and point-in-time tests for `build_fx_1d` / `fx_rate_on_or_before` (T-75 / M1.2e). +//! +//! Compares the optimized builder (sort + in-place compaction + two-pointer merge) against a +//! deliberately naive reference written only from the documented rules (`BTreeMap` grouping per +//! source, then a per-date merge), and the binary-search lookup against a linear scan. Also runs +//! truncation and poison tests: rows/lookups dated before a cutoff must not depend on any input +//! dated at or after it. All comparisons on `f64` fields are bitwise. + +use std::collections::BTreeMap; + +use curate_etl::{ + build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, + FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, +}; + +struct Rng(u64); + +impl Rng { + fn next(&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() % n + } +} + +fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +fn flat(session_date: i32, rate: f64) -> FxDailyBar { + bar(session_date, rate, rate, rate, rate) +} + +fn bits(b: &FxDailyBar) -> [u64; 4] { + [ + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + ] +} + +/// Reference per-source cleaning straight from the task rules. +fn reference_clean(input: &[FxDailyBar]) -> (BTreeMap, FxSourceStats) { + let mut stats = FxSourceStats { + rows_in: input.len(), + ..FxSourceStats::default() + }; + let mut groups: BTreeMap> = BTreeMap::new(); + for b in input { + let fields = [b.open, b.high, b.low, b.close]; + if fields.iter().any(|v| !v.is_finite() || *v <= 0.0) { + stats.dropped_invalid_ohlc += 1; + continue; + } + let inside = |v: f64| v >= b.low && v <= b.high; + if b.high < b.low || !inside(b.open) || !inside(b.close) { + stats.dropped_inconsistent_ohlc += 1; + continue; + } + groups.entry(b.session_date).or_default().push(*b); + } + let mut kept = BTreeMap::new(); + for (date, group) in groups { + if group.iter().all(|g| bits(g) == bits(&group[0])) { + stats.duplicate_collapsed += group.len() - 1; + kept.insert(date, group[0]); + } else { + stats.duplicate_conflict_dropped += group.len(); + } + } + stats.rows_kept = kept.len(); + (kept, stats) +} + +fn row(b: &FxDailyBar, source: FxSource) -> Fx1dRow { + Fx1dRow { + pair: FX_PAIR_USDCAD, + session_date: b.session_date, + open: b.open, + high: b.high, + low: b.low, + close: b.close, + source, + } +} + +/// Reference merge. The 1% check mirrors the documented few-ulp rounding slack; the boundary +/// semantics themselves are pinned by the hand-picked cases in `fx_contract.rs`. +fn reference_build(eod: &[FxDailyBar], te: &[FxDailyBar]) -> Fx1dBuild { + let (eod_kept, eod_stats) = reference_clean(eod); + let (te_kept, te_stats) = reference_clean(te); + let mut stats = Fx1dStats { + eod: eod_stats, + te: te_stats, + ..Fx1dStats::default() + }; + let mut dates: Vec = eod_kept.keys().chain(te_kept.keys()).copied().collect(); + dates.sort_unstable(); + dates.dedup(); + let mut rows = Vec::new(); + for d in dates { + match (eod_kept.get(&d), te_kept.get(&d)) { + (Some(e), Some(t)) => { + rows.push(row(e, FxSource::EodCadForex)); + stats.eod_rows_out += 1; + stats.te_superseded_by_eod += 1; + stats.overlap_checked += 1; + let rel = (e.close - t.close).abs() / e.close; + stats.max_overlap_rel = stats.max_overlap_rel.max(rel); + if rel <= FX_OVERLAP_REL_TOLERANCE + 4.0 * f64::EPSILON { + stats.overlap_within_tolerance += 1; + } else { + stats.overlap_mismatched += 1; + } + } + (Some(e), None) => { + rows.push(row(e, FxSource::EodCadForex)); + stats.eod_rows_out += 1; + } + (None, Some(t)) => { + rows.push(row(t, FxSource::TeUsdCad)); + stats.te_rows_out += 1; + } + (None, None) => unreachable!(), + } + } + stats.rows_out = rows.len(); + Fx1dBuild { rows, stats } +} + +fn assert_rows_bit_eq(actual: &[Fx1dRow], expected: &[Fx1dRow], ctx: &str) { + assert_eq!(actual.len(), expected.len(), "{ctx}: row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.pair, e.pair, "{ctx}: row {i} pair"); + assert_eq!(a.session_date, e.session_date, "{ctx}: row {i} date"); + assert_eq!(a.source, e.source, "{ctx}: row {i} source"); + assert_eq!(a.open.to_bits(), e.open.to_bits(), "{ctx}: row {i} open"); + assert_eq!(a.high.to_bits(), e.high.to_bits(), "{ctx}: row {i} high"); + assert_eq!(a.low.to_bits(), e.low.to_bits(), "{ctx}: row {i} low"); + assert_eq!(a.close.to_bits(), e.close.to_bits(), "{ctx}: row {i} close"); + } +} + +fn assert_stats_bit_eq(a: &Fx1dStats, e: &Fx1dStats, ctx: &str) { + assert_eq!(a.eod, e.eod, "{ctx}: eod stats"); + assert_eq!(a.te, e.te, "{ctx}: te stats"); + assert_eq!(a.rows_out, e.rows_out, "{ctx}: rows_out"); + assert_eq!(a.eod_rows_out, e.eod_rows_out, "{ctx}: eod_rows_out"); + assert_eq!(a.te_rows_out, e.te_rows_out, "{ctx}: te_rows_out"); + assert_eq!( + a.te_superseded_by_eod, e.te_superseded_by_eod, + "{ctx}: superseded" + ); + assert_eq!(a.overlap_checked, e.overlap_checked, "{ctx}: checked"); + assert_eq!( + a.overlap_within_tolerance, e.overlap_within_tolerance, + "{ctx}: within" + ); + assert_eq!( + a.overlap_mismatched, e.overlap_mismatched, + "{ctx}: mismatched" + ); + assert_eq!( + a.max_overlap_rel.to_bits(), + e.max_overlap_rel.to_bits(), + "{ctx}: max_overlap_rel" + ); +} + +/// Random bar over a small date window so duplicates, overlaps and gaps are frequent. Rates are +/// drawn from a coarse grid so bitwise-identical duplicates occur naturally. +fn random_bar(rng: &mut Rng, date_lo: i32, date_span: u64) -> FxDailyBar { + let d = date_lo + rng.below(date_span) as i32; + let grid = |rng: &mut Rng| 1.30 + rng.below(8) as f64 * 0.005; + let mut low = grid(rng); + let mut high = grid(rng); + if low > high { + std::mem::swap(&mut low, &mut high); + } + let pick = |rng: &mut Rng| if rng.below(2) == 0 { low } else { high }; + let mut b = bar(d, pick(rng), high, low, pick(rng)); + match rng.below(20) { + 0 => b.open = f64::NAN, + 1 => b.high = f64::INFINITY, + 2 => b.low = -0.0, + 3 => b.close = -1.0, + 4 => std::mem::swap(&mut b.high, &mut b.low), // possibly high < low + 5 => b.open = high + 0.01, // open above range + 6 => b.close = low - 0.01, // close below range + 7 => b.close *= 1.02, // maybe outside; also creates overlap mismatches + _ => {} + } + b +} + +#[test] +fn builder_matches_naive_reference_on_random_seeded_inputs() { + let mut rng = Rng(0xF1D0_C0DE_75FA_0001); + let mut coverage = Fx1dStats::default(); + for trial in 0..300 { + let n_eod = rng.below(60) as usize; + let n_te = rng.below(60) as usize; + let eod: Vec<_> = (0..n_eod).map(|_| random_bar(&mut rng, -10, 40)).collect(); + let te: Vec<_> = (0..n_te).map(|_| random_bar(&mut rng, 5, 50)).collect(); + let actual = build_fx_1d(&eod, &te); + let expected = reference_build(&eod, &te); + let ctx = format!("trial {trial}"); + assert_rows_bit_eq(&actual.rows, &expected.rows, &ctx); + assert_stats_bit_eq(&actual.stats, &expected.stats, &ctx); + let s = actual.stats; + coverage.eod.dropped_invalid_ohlc += s.eod.dropped_invalid_ohlc; + coverage.te.dropped_inconsistent_ohlc += s.te.dropped_inconsistent_ohlc; + coverage.eod.duplicate_collapsed += s.eod.duplicate_collapsed; + coverage.te.duplicate_conflict_dropped += s.te.duplicate_conflict_dropped; + coverage.overlap_within_tolerance += s.overlap_within_tolerance; + coverage.overlap_mismatched += s.overlap_mismatched; + coverage.te_rows_out += s.te_rows_out; + } + // The generator must actually exercise every rule, or the comparison proves little. + assert!(coverage.eod.dropped_invalid_ohlc > 0, "{coverage:?}"); + assert!(coverage.te.dropped_inconsistent_ohlc > 0, "{coverage:?}"); + assert!(coverage.eod.duplicate_collapsed > 0, "{coverage:?}"); + assert!(coverage.te.duplicate_conflict_dropped > 0, "{coverage:?}"); + assert!(coverage.overlap_within_tolerance > 0, "{coverage:?}"); + assert!(coverage.overlap_mismatched > 0, "{coverage:?}"); + assert!(coverage.te_rows_out > 0, "{coverage:?}"); +} + +#[test] +fn every_invalid_value_on_every_ohlc_field_counts_as_invalid() { + let bad_values = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, -0.0, -1.35]; + let mut eod = Vec::new(); + let mut d = 0; + for &v in &bad_values { + for field in 0..4 { + let mut b = bar(d, 1.35, 1.36, 1.34, 1.35); + match field { + 0 => b.open = v, + 1 => b.high = v, + 2 => b.low = v, + _ => b.close = v, + } + eod.push(b); + d += 1; + } + } + let built = build_fx_1d(&eod, &eod); + assert!(built.rows.is_empty()); + for s in [built.stats.eod, built.stats.te] { + assert_eq!(s.rows_in, 24); + assert_eq!(s.dropped_invalid_ohlc, 24); + assert_eq!(s.dropped_inconsistent_ohlc, 0); + assert_eq!(s.rows_kept, 0); + } + assert_eq!(built.stats.rows_out, 0); + assert_eq!(built.stats.overlap_checked, 0); +} + +#[test] +fn ohlc_exactly_on_range_bounds_is_kept() { + // open == low and close == high (and a fully flat bar) are consistent, not dropped. + let built = build_fx_1d( + &[bar(1, 1.30, 1.40, 1.30, 1.40), flat(2, 1.35)], + &[bar(3, 1.40, 1.40, 1.30, 1.30)], + ); + assert_eq!(built.stats.eod.rows_kept, 2); + assert_eq!(built.stats.te.rows_kept, 1); + assert_eq!(built.stats.eod.dropped_inconsistent_ohlc, 0); + assert_eq!(built.stats.te.dropped_inconsistent_ohlc, 0); + assert_eq!(built.rows.len(), 3); +} + +#[test] +fn identical_te_duplicates_on_overlap_date_supersede_once() { + let built = build_fx_1d( + &[flat(10, 1.35)], + &[flat(10, 1.351), flat(10, 1.351), flat(10, 1.351)], + ); + assert_eq!(built.stats.te.duplicate_collapsed, 2); + assert_eq!(built.stats.te.rows_kept, 1); + assert_eq!(built.stats.te_superseded_by_eod, 1); + assert_eq!(built.stats.overlap_checked, 1); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].source, FxSource::EodCadForex); + assert_eq!(built.rows[0].close.to_bits(), 1.35_f64.to_bits()); +} + +#[test] +fn te_only_and_eod_only_inputs_pass_through_with_correct_source() { + let te_only = build_fx_1d(&[], &[flat(3, 1.31), flat(1, 1.30)]); + assert_eq!(te_only.rows.len(), 2); + assert!(te_only.rows.iter().all(|r| r.source == FxSource::TeUsdCad)); + assert_eq!(te_only.rows[0].session_date, 1); + assert_eq!(te_only.stats.te_rows_out, 2); + assert_eq!(te_only.stats.eod_rows_out, 0); + assert_eq!(te_only.stats.max_overlap_rel, 0.0); + + let eod_only = build_fx_1d(&[flat(3, 1.31), flat(1, 1.30)], &[]); + assert!(eod_only + .rows + .iter() + .all(|r| r.source == FxSource::EodCadForex)); + assert_eq!(eod_only.stats.eod_rows_out, 2); +} + +fn linear_lookup(rows: &[Fx1dRow], date: i32, max_stale: u32) -> Option<&Fx1dRow> { + rows.iter() + .rev() + .find(|r| r.session_date <= date) + .filter(|r| i64::from(date) - i64::from(r.session_date) <= i64::from(max_stale)) +} + +#[test] +fn lookup_matches_linear_scan_on_random_series() { + let mut rng = Rng(0xF1D0_C0DE_75FA_0002); + for _ in 0..200 { + let n = rng.below(40) as usize; + let mut d = -500 + rng.below(1000) as i32; + let mut eod = Vec::with_capacity(n); + for _ in 0..n { + d += 1 + rng.below(6) as i32; + eod.push(flat(d, 1.30 + rng.below(100) as f64 * 0.001)); + } + let built = build_fx_1d(&eod, &[]); + for _ in 0..200 { + let q = -520 + rng.below(1400) as i32; + let stale = rng.below(8) as u32; + let got = fx_rate_on_or_before(&built.rows, q, stale); + assert_eq!( + got, + linear_lookup(&built.rows, q, stale), + "q={q} stale={stale}" + ); + if let Some(r) = got { + assert!(r.session_date <= q, "look-ahead: {} > {q}", r.session_date); + } + } + } +} + +/// Builds an input mix spanning dates 0..200 in both sources, with bad rows and duplicates. +fn mixed_inputs(seed: u64) -> (Vec, Vec) { + let mut rng = Rng(seed); + let eod = (0..300).map(|_| random_bar(&mut rng, 0, 150)).collect(); + let te = (0..300).map(|_| random_bar(&mut rng, 50, 150)).collect(); + (eod, te) +} + +#[test] +fn truncation_test_rows_before_cutoff_do_not_depend_on_later_inputs() { + let (eod, te) = mixed_inputs(0xF1D0_C0DE_75FA_0003); + let full = build_fx_1d(&eod, &te); + for cutoff in [0, 1, 49, 50, 51, 100, 149, 150, 199, 200] { + let eod_t: Vec<_> = eod + .iter() + .copied() + .filter(|b| b.session_date < cutoff) + .collect(); + let te_t: Vec<_> = te + .iter() + .copied() + .filter(|b| b.session_date < cutoff) + .collect(); + let truncated = build_fx_1d(&eod_t, &te_t); + let full_prefix: Vec = full + .rows + .iter() + .copied() + .filter(|r| r.session_date < cutoff) + .collect(); + assert_rows_bit_eq(&truncated.rows, &full_prefix, &format!("cutoff {cutoff}")); + for q in -5..cutoff { + assert_eq!( + fx_rate_on_or_before(&truncated.rows, q, 4), + fx_rate_on_or_before(&full.rows, q, 4), + "cutoff {cutoff} q {q}" + ); + } + } +} + +#[test] +fn poison_test_absurd_future_rows_never_move_earlier_rows_or_lookups() { + let (eod, te) = mixed_inputs(0xF1D0_C0DE_75FA_0004); + let clean = build_fx_1d(&eod, &te); + let cutoff = 120; + + let mut eod_p = eod.clone(); + let mut te_p = te.clone(); + for d in cutoff..cutoff + 100 { + // Absurd future "restatements": conflicting duplicates of existing dates, huge rates, + // and dates both sources share, all at or after the cutoff. + eod_p.push(flat(d, 1.0e9)); + te_p.push(flat(d, 1.0e-9)); + te_p.push(flat(d, 7.0)); + } + let poisoned = build_fx_1d(&eod_p, &te_p); + + let before = |b: &Fx1dBuild| -> Vec { + b.rows + .iter() + .copied() + .filter(|r| r.session_date < cutoff) + .collect() + }; + assert_rows_bit_eq(&before(&poisoned), &before(&clean), "poison prefix"); + for q in -5..cutoff { + assert_eq!( + fx_rate_on_or_before(&poisoned.rows, q, 10), + fx_rate_on_or_before(&clean.rows, q, 10), + "poison q {q}" + ); + } +}