diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 9330232b..bbaaa394 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1665,3 +1665,12 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`. - **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_idvenue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number. - **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up. + +## Lagged Macro Regime Series Builder (`M2.2n`) + +`build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation` inputs and a caller-supplied `(country_iso, indicator) -> Option` lookup into sorted, unique `MacroRow` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A). + +- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`). +- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`). +- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`. +- **Deferred:** `teData` BSON decoding, `macro/part.parquet` writer, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access. diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 381779b9..a561edc3 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -21,6 +21,7 @@ pub mod events; pub mod fundamentals; pub mod fx; pub mod ilp; +pub mod macro_series; pub mod mongo_safety; pub mod mongo_stream; pub mod parquet_adj; @@ -148,6 +149,11 @@ pub use ilp::{ DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS, FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, }; +pub use macro_series::{ + build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation, + MacroRow, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS, + POLICY_RATE_LAG_DAYS, +}; pub use mongo_safety::{ assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts, MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, diff --git a/tools/curate-etl/src/macro_series.rs b/tools/curate-etl/src/macro_series.rs new file mode 100644 index 00000000..247ec0d9 --- /dev/null +++ b/tools/curate-etl/src/macro_series.rs @@ -0,0 +1,284 @@ +//! Pure, in-memory `macro` builder for lagged `teData` regime series (`MacroObservation` + +//! caller-supplied [`MacroLagClass`] → sorted, unique [`MacroRow`]s matching +//! `macro/part.parquet` in `design/DATA-CONTRACTS.md` §1 and §3A). +//! +//! ## Governance & Provenance Assumptions +//! - **Regime-use policy owner:** Quant Research owns which macro indicators are admissible for +//! coarse regime filters and how estimated publication lags are stress-tested. +//! - **Lag-mapping owner:** The caller owns the explicit `(country_iso, indicator) -> Option` +//! lookup. Indicator names are **not** hardcoded here because live TradingEconomics indicator +//! names in `teIndicators` / `teData` are unverified in this crate (unverified assumption). +//! - **Final-revised source data:** `teData` stores `{d, v}` final-revised values only, with no +//! verified release timestamps or historical revision vintages. Every emitted row carries +//! [`MACRO_KNOWN_AT_SOURCE`] (`"publication_lag_estimate"`) and becomes available strictly at +//! its estimated `known_at` (`00:00:00 UTC` on `period_date + lag_days`). +//! +//! ## Builder Rules +//! 1. **Fail-closed mapping & validation:** Each input observation is counted once in +//! [`MacroBuildStats::input`]. Unmapped `(country_iso, indicator)` pairs are skipped first +//! (`skipped_unmapped_indicator`) and never given a default lag. Mapped observations with +//! non-finite `value` (`NaN` / `±inf`) are skipped (`skipped_non_finite_value`). +//! 2. **Deterministic deduplication:** Surviving observations are sorted by +//! `(country_iso, indicator, period_date)`. Bitwise-identical duplicates (`f64::to_bits()`) +//! collapse to one row and count each extra copy in `skipped_duplicate`. Any conflicting value +//! for the same `(country_iso, indicator, period_date)`—including opposite signed zeros (`+0.0` +//! vs. `-0.0`)—fails the build with [`MacroError::ConflictingDuplicate`], independent of input +//! order. +//! 3. **Checked `known_at` arithmetic:** `known_at` is computed as +//! `00:00:00 UTC` on `period_date + lag_days` using checked `i32` date addition and checked +//! `i64` microsecond scaling (`86_400_000_000` µs/day). Overflow returns +//! [`MacroError::KnownAtOverflow`] rather than panicking. +//! 4. **Accounting invariant:** +//! `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`. + +use std::error::Error; +use std::fmt; + +use crate::shorts::epoch_days_to_ymd; + +/// Locked publication lag (calendar days) for central-bank policy rates (`design/DATA-CONTRACTS.md` §1). +pub const POLICY_RATE_LAG_DAYS: i32 = 1; + +/// Locked publication lag (calendar days) for monthly releases such as CPI / NFP (`design/DATA-CONTRACTS.md` §1). +pub const MONTHLY_RELEASE_LAG_DAYS: i32 = 35; + +/// Locked publication lag (calendar days) for 65-day GDP releases (`design/DATA-CONTRACTS.md` §1). +pub const GDP65_LAG_DAYS: i32 = 65; + +/// Locked publication lag (calendar days) for 90-day GDP releases (`design/DATA-CONTRACTS.md` §1). +pub const GDP90_LAG_DAYS: i32 = 90; + +/// Canonical provenance label written to [`MacroRow::known_at_source`]. +pub const MACRO_KNOWN_AT_SOURCE: &str = "publication_lag_estimate"; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +/// Caller-assigned publication lag class from `design/DATA-CONTRACTS.md` §1. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum MacroLagClass { + /// Central-bank policy rates (`+1` calendar day). + PolicyRate, + /// Monthly macro releases such as CPI / NFP (`+35` calendar days). + MonthlyRelease, + /// Faster GDP releases (`+65` calendar days). + Gdp65, + /// Conservative / slower GDP releases (`+90` calendar days). + Gdp90, +} + +impl MacroLagClass { + /// Returns the locked publication lag in calendar days. + #[inline] + pub const fn lag_days(self) -> i32 { + match self { + Self::PolicyRate => POLICY_RATE_LAG_DAYS, + Self::MonthlyRelease => MONTHLY_RELEASE_LAG_DAYS, + Self::Gdp65 => GDP65_LAG_DAYS, + Self::Gdp90 => GDP90_LAG_DAYS, + } + } +} + +/// A single raw `teData` macro observation input (BSON-free). +#[derive(Debug, Clone, PartialEq)] +pub struct MacroObservation { + pub country_iso: K, + pub indicator: K, + /// Observation period date as days since `1970-01-01` (UTC Gregorian). + pub period_date: i32, + pub value: f64, +} + +/// A single curated `macro` row matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` §3A, +/// sorted and unique by `(country_iso, indicator, period_date)`. +#[derive(Debug, Clone, PartialEq)] +pub struct MacroRow { + pub country_iso: K, + pub indicator: K, + /// Observation period date as days since `1970-01-01` (UTC Gregorian). + pub period_date: i32, + /// Estimated point-in-time availability timestamp (`00:00:00 UTC` of `period_date + lag_days`) + /// in UTC microseconds since `1970-01-01T00:00:00Z`. + pub known_at: i64, + pub known_at_source: &'static str, + pub value: f64, +} + +/// Summary accounting counters produced alongside [`MacroBuild::rows`]. +/// +/// Conservation invariant: +/// `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MacroBuildStats { + pub input: usize, + pub emitted: usize, + pub skipped_unmapped_indicator: usize, + pub skipped_non_finite_value: usize, + pub skipped_duplicate: usize, +} + +/// Output of [`build_macro_rows`]: sorted, unique lagged macro rows and reconciling stats. +#[derive(Debug, Clone, PartialEq)] +pub struct MacroBuild { + pub rows: Vec>, + pub stats: MacroBuildStats, +} + +/// Typed errors returned by [`build_macro_rows`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MacroError { + /// Two or more mapped, finite observations shared `(country_iso, indicator, period_date)` with + /// non-identical `f64::to_bits()` values (including opposite signed zeros `+0.0` vs. `-0.0`). + ConflictingDuplicate { + country_iso: K, + indicator: K, + period_date: i32, + }, + /// Computing `00:00:00 UTC` for `period_date + lag_class.lag_days()` overflowed `i32` day + /// addition or `i64` microsecond scaling. + KnownAtOverflow { + period_date: i32, + lag_class: MacroLagClass, + }, +} + +impl fmt::Display for MacroError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ConflictingDuplicate { + country_iso, + indicator, + period_date, + } => { + let (y, m, d) = epoch_days_to_ymd(*period_date); + write!( + f, + "conflicting duplicate macro observation for ({country_iso:?}, {indicator:?}, {y:04}-{m:02}-{d:02} [epoch_day={period_date}])" + ) + } + Self::KnownAtOverflow { + period_date, + lag_class, + } => write!( + f, + "known_at timestamp overflow for period_date={period_date} with lag_class={lag_class:?} (+{} days)", + lag_class.lag_days() + ), + } + } +} + +impl Error for MacroError {} + +struct MappedObservation { + country_iso: K, + indicator: K, + period_date: i32, + lag_class: MacroLagClass, + value: f64, +} + +/// Builds sorted, unique lagged `macro` rows from raw observations and a caller-supplied +/// `(country_iso, indicator) -> Option` lookup. +/// +/// The caller lookup `lag_for` must be deterministic/stable for each exact `(country_iso, indicator)` +/// pair. Any permutation of `observations` produces identical `rows` (including `f64` bit patterns) +/// and `stats`, or the same [`MacroError`]. +pub fn build_macro_rows( + observations: I, + lag_for: F, +) -> Result, MacroError> +where + K: Ord, + I: IntoIterator>, + F: Fn(&K, &K) -> Option, +{ + let iter = observations.into_iter(); + let (lower, _) = iter.size_hint(); + let mut stats = MacroBuildStats::default(); + let mut mapped: Vec> = Vec::with_capacity(lower); + + for obs in iter { + stats.input += 1; + + let Some(lag_class) = lag_for(&obs.country_iso, &obs.indicator) else { + stats.skipped_unmapped_indicator += 1; + continue; + }; + + if !obs.value.is_finite() { + stats.skipped_non_finite_value += 1; + continue; + } + + mapped.push(MappedObservation { + country_iso: obs.country_iso, + indicator: obs.indicator, + period_date: obs.period_date, + lag_class, + value: obs.value, + }); + } + + mapped.sort_unstable_by(|a, b| { + a.country_iso + .cmp(&b.country_iso) + .then_with(|| a.indicator.cmp(&b.indicator)) + .then_with(|| a.period_date.cmp(&b.period_date)) + }); + + let mut rows: Vec> = Vec::with_capacity(mapped.len()); + let mut sorted = mapped.into_iter().peekable(); + + while let Some(first) = sorted.next() { + while let Some(next) = sorted.peek() { + if next.country_iso == first.country_iso + && next.indicator == first.indicator + && next.period_date == first.period_date + { + if next.value.to_bits() != first.value.to_bits() { + return Err(MacroError::ConflictingDuplicate { + country_iso: first.country_iso, + indicator: first.indicator, + period_date: first.period_date, + }); + } + stats.skipped_duplicate += 1; + sorted.next(); + } else { + break; + } + } + + let known_at_day = first + .period_date + .checked_add(first.lag_class.lag_days()) + .ok_or(MacroError::KnownAtOverflow { + period_date: first.period_date, + lag_class: first.lag_class, + })?; + let known_at = i64::from(known_at_day) + .checked_mul(MICROS_PER_DAY) + .ok_or(MacroError::KnownAtOverflow { + period_date: first.period_date, + lag_class: first.lag_class, + })?; + + rows.push(MacroRow { + country_iso: first.country_iso, + indicator: first.indicator, + period_date: first.period_date, + known_at, + known_at_source: MACRO_KNOWN_AT_SOURCE, + value: first.value, + }); + } + + stats.emitted = rows.len(); + + Ok(MacroBuild { rows, stats }) +} + +#[cfg(test)] +#[path = "macro_series_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/macro_series_tests.rs b/tools/curate-etl/src/macro_series_tests.rs new file mode 100644 index 00000000..8dadcc35 --- /dev/null +++ b/tools/curate-etl/src/macro_series_tests.rs @@ -0,0 +1,325 @@ +use super::*; +use crate::split::ymd_to_epoch_days; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn obs(country_iso: &str, indicator: &str, period_date: i32, value: f64) -> MacroObservation { + MacroObservation { + country_iso: country_iso.to_string(), + indicator: indicator.to_string(), + period_date, + value, + } +} + +fn assert_accounting_and_order(build: &MacroBuild) { + let s = &build.stats; + assert_eq!(s.emitted, build.rows.len()); + assert_eq!( + s.input, + s.emitted + s.skipped_unmapped_indicator + s.skipped_non_finite_value + s.skipped_duplicate, + "accounting invariant failed: {s:?}" + ); + for pair in build.rows.windows(2) { + assert!( + (&pair[0].country_iso, &pair[0].indicator, pair[0].period_date) + < (&pair[1].country_iso, &pair[1].indicator, pair[1].period_date), + "rows must be strictly sorted and unique by (country_iso, indicator, period_date)" + ); + } + for row in &build.rows { + assert_eq!(row.known_at_source, MACRO_KNOWN_AT_SOURCE); + let period_midnight = i64::from(row.period_date) * 86_400_000_000; + assert!( + row.known_at > period_midnight, + "look-ahead violation: known_at {} <= period midnight {}", + row.known_at, + period_midnight + ); + } +} + +fn assert_rows_bit_eq(left: &[MacroRow], right: &[MacroRow]) { + assert_eq!(left.len(), right.len()); + for (a, b) in left.iter().zip(right.iter()) { + assert_eq!(a.country_iso, b.country_iso); + assert_eq!(a.indicator, b.indicator); + assert_eq!(a.period_date, b.period_date); + assert_eq!(a.known_at, b.known_at); + assert_eq!(a.known_at_source, b.known_at_source); + assert_eq!(a.value.to_bits(), b.value.to_bits()); + } +} + +#[test] +fn lag_classes_produce_exact_utc_midnights() { + assert_eq!(POLICY_RATE_LAG_DAYS, 1); + assert_eq!(MONTHLY_RELEASE_LAG_DAYS, 35); + assert_eq!(GDP65_LAG_DAYS, 65); + assert_eq!(GDP90_LAG_DAYS, 90); + assert_eq!(MacroLagClass::PolicyRate.lag_days(), 1); + assert_eq!(MacroLagClass::MonthlyRelease.lag_days(), 35); + assert_eq!(MacroLagClass::Gdp65.lag_days(), 65); + assert_eq!(MacroLagClass::Gdp90.lag_days(), 90); + assert_eq!(MACRO_KNOWN_AT_SOURCE, "publication_lag_estimate"); + + let jan31 = day(2024, 1, 31); + let inputs = vec![ + obs("US", "ind_policy", jan31, 5.50), + obs("US", "ind_monthly", jan31, 3.10), + obs("US", "ind_gdp65", jan31, 2.25), + obs("US", "ind_gdp90", jan31, 1.80), + ]; + + let build = build_macro_rows(inputs, |country, indicator| match (country.as_str(), indicator.as_str()) { + ("US", "ind_policy") => Some(MacroLagClass::PolicyRate), + ("US", "ind_monthly") => Some(MacroLagClass::MonthlyRelease), + ("US", "ind_gdp65") => Some(MacroLagClass::Gdp65), + ("US", "ind_gdp90") => Some(MacroLagClass::Gdp90), + _ => None, + }) + .expect("lag class fixture should succeed"); + + assert_accounting_and_order(&build); + assert_eq!( + build.stats, + MacroBuildStats { + input: 4, + emitted: 4, + skipped_unmapped_indicator: 0, + skipped_non_finite_value: 0, + skipped_duplicate: 0, + } + ); + + // Sorted alphabetically by indicator: ind_gdp65, ind_gdp90, ind_monthly, ind_policy + let expected: [(&str, i64, f64); 4] = [ + ("ind_gdp65", 1_712_275_200_000_000, 2.25), // 2024-04-05T00:00:00Z + ("ind_gdp90", 1_714_435_200_000_000, 1.80), // 2024-04-30T00:00:00Z + ("ind_monthly", 1_709_683_200_000_000, 3.10), // 2024-03-06T00:00:00Z (+35d across 2024-02-29) + ("ind_policy", 1_706_745_600_000_000, 5.50), // 2024-02-01T00:00:00Z + ]; + + assert_eq!(build.rows.len(), expected.len()); + for (row, (indicator, known_at, value)) in build.rows.iter().zip(expected.iter()) { + assert_eq!(row.country_iso, "US"); + assert_eq!(row.indicator, *indicator); + assert_eq!(row.period_date, jan31); + assert_eq!(row.known_at, *known_at); + assert_eq!(row.known_at_source, MACRO_KNOWN_AT_SOURCE); + assert_eq!(row.value.to_bits(), value.to_bits()); + } +} + +#[test] +fn skips_unmapped_and_non_finite_once() { + let d = day(2024, 6, 30); + let inputs = vec![ + // Mapped indicator for US, valid value -> emitted + obs("US", "cpi_yoy", d, 3.0), + // Same indicator in unmapped country -> skipped_unmapped_indicator (pair-keyed lookup) + obs("CA", "cpi_yoy", d, 2.7), + // Unmapped indicator with NaN -> counted once as skipped_unmapped_indicator (precedence) + obs("CA", "cpi_yoy", day(2024, 7, 31), f64::NAN), + // Mapped pair with NaN, +inf, -inf -> skipped_non_finite_value + obs("US", "cpi_yoy", day(2024, 7, 31), f64::NAN), + obs("US", "cpi_yoy", day(2024, 8, 31), f64::INFINITY), + obs("US", "cpi_yoy", day(2024, 9, 30), f64::NEG_INFINITY), + ]; + + let build = build_macro_rows(inputs, |country, indicator| { + if country == "US" && indicator == "cpi_yoy" { + Some(MacroLagClass::MonthlyRelease) + } else { + None + } + }) + .expect("skips should not fail the build"); + + assert_accounting_and_order(&build); + assert_eq!( + build.stats, + MacroBuildStats { + input: 6, + emitted: 1, + skipped_unmapped_indicator: 2, + skipped_non_finite_value: 3, + skipped_duplicate: 0, + } + ); + assert_eq!(build.rows[0].country_iso, "US"); + assert_eq!(build.rows[0].indicator, "cpi_yoy"); + assert_eq!(build.rows[0].period_date, d); + assert_eq!(build.rows[0].value.to_bits(), 3.0_f64.to_bits()); +} + +#[test] +fn sorts_deduplicates_and_accounts_for_all_inputs() { + let empty: Vec> = Vec::new(); + let empty_build = + build_macro_rows(empty, |_, _| Some(MacroLagClass::PolicyRate)).expect("empty succeeds"); + assert!(empty_build.rows.is_empty()); + assert_eq!(empty_build.stats, MacroBuildStats::default()); + assert_accounting_and_order(&empty_build); + + let d1 = day(2024, 1, 31); + let d2 = day(2024, 2, 29); + + let fixture_a = vec![ + obs("US", "rate", d2, 5.25), + obs("CA", "gdp", d1, 1.50), + obs("US", "rate", d1, 5.50), + obs("CA", "gdp", d1, 1.50), // exact duplicate + obs("CA", "gdp", d1, 1.50), // second exact duplicate + obs("US", "unmapped_ind", d1, 42.0), + obs("US", "rate", day(2024, 3, 31), f64::NAN), + obs("CA", "rate", d1, -0.0), // signed zero preserved identically + obs("CA", "rate", d1, -0.0), // bitwise-identical -0.0 duplicate collapses + ]; + + let fixture_b = vec![ + obs("CA", "rate", d1, -0.0), + obs("US", "rate", day(2024, 3, 31), f64::NAN), + obs("CA", "gdp", d1, 1.50), + obs("US", "unmapped_ind", d1, 42.0), + obs("US", "rate", d1, 5.50), + obs("CA", "rate", d1, -0.0), + obs("CA", "gdp", d1, 1.50), + obs("US", "rate", d2, 5.25), + obs("CA", "gdp", d1, 1.50), + ]; + + let lag_for = |country: &String, indicator: &String| match (country.as_str(), indicator.as_str()) { + ("CA", "gdp") => Some(MacroLagClass::Gdp65), + ("CA", "rate") | ("US", "rate") => Some(MacroLagClass::PolicyRate), + _ => None, + }; + + let build_a = build_macro_rows(fixture_a, lag_for).expect("fixture_a succeeds"); + let build_b = build_macro_rows(fixture_b, lag_for).expect("fixture_b succeeds"); + + assert_accounting_and_order(&build_a); + assert_accounting_and_order(&build_b); + assert_rows_bit_eq(&build_a.rows, &build_b.rows); + assert_eq!(build_a.stats, build_b.stats); + assert_eq!( + build_a.stats, + MacroBuildStats { + input: 9, + emitted: 4, + skipped_unmapped_indicator: 1, + skipped_non_finite_value: 1, + skipped_duplicate: 3, + } + ); + + let keys: Vec<(&str, &str, i32)> = build_a + .rows + .iter() + .map(|r| (r.country_iso.as_str(), r.indicator.as_str(), r.period_date)) + .collect(); + assert_eq!( + keys, + vec![ + ("CA", "gdp", d1), + ("CA", "rate", d1), + ("US", "rate", d1), + ("US", "rate", d2), + ] + ); + assert_eq!(build_a.rows[1].value.to_bits(), (-0.0_f64).to_bits()); +} + +#[test] +fn rejects_conflicting_duplicates_in_either_order() { + let d = day(2024, 3, 31); + let lag_for = |_: &String, _: &String| Some(MacroLagClass::MonthlyRelease); + + // Distinct finite values in both orders + let err_ab = build_macro_rows( + vec![obs("US", "cpi", d, 3.1), obs("US", "cpi", d, 3.2)], + lag_for, + ) + .expect_err("distinct duplicate values must fail"); + let err_ba = build_macro_rows( + vec![obs("US", "cpi", d, 3.2), obs("US", "cpi", d, 3.1)], + lag_for, + ) + .expect_err("distinct duplicate values in reverse order must fail"); + + let expected = MacroError::ConflictingDuplicate { + country_iso: "US".to_string(), + indicator: "cpi".to_string(), + period_date: d, + }; + assert_eq!(err_ab, expected); + assert_eq!(err_ba, expected); + assert!(err_ab.to_string().contains("2024-03-31")); + + // Opposite signed zeros (+0.0 vs -0.0) in both orders + let err_pos_neg = build_macro_rows( + vec![obs("CA", "cpi", d, 0.0), obs("CA", "cpi", d, -0.0)], + lag_for, + ) + .expect_err("+0.0 vs -0.0 must be treated as conflicting"); + let err_neg_pos = build_macro_rows( + vec![obs("CA", "cpi", d, -0.0), obs("CA", "cpi", d, 0.0)], + lag_for, + ) + .expect_err("-0.0 vs +0.0 must be treated as conflicting"); + + let expected_zero = MacroError::ConflictingDuplicate { + country_iso: "CA".to_string(), + indicator: "cpi".to_string(), + period_date: d, + }; + assert_eq!(err_pos_neg, expected_zero); + assert_eq!(err_neg_pos, expected_zero); +} + +#[test] +fn returns_typed_known_at_overflow() { + // 1. i32 day addition overflow: i32::MAX + 1 + let err_add = build_macro_rows( + vec![obs("US", "rate", i32::MAX, 5.0)], + |_, _| Some(MacroLagClass::PolicyRate), + ) + .expect_err("i32::MAX + PolicyRate must overflow"); + assert_eq!( + err_add, + MacroError::KnownAtOverflow { + period_date: i32::MAX, + lag_class: MacroLagClass::PolicyRate, + } + ); + assert!(err_add.to_string().contains("known_at timestamp overflow")); + + // 2. i64 microsecond multiplication overflow after valid i32 addition: + // (106_751_991 + 1) * 86_400_000_000 > i64::MAX + let err_mul = build_macro_rows( + vec![obs("US", "rate", 106_751_991, 5.0)], + |_, _| Some(MacroLagClass::PolicyRate), + ) + .expect_err("106_751_991 + PolicyRate must overflow microsecond scaling"); + assert_eq!( + err_mul, + MacroError::KnownAtOverflow { + period_date: 106_751_991, + lag_class: MacroLagClass::PolicyRate, + } + ); + + // 3. Adjacent representable PolicyRate case succeeds: + // (106_751_990 + 1) * 86_400_000_000 == 9_223_372_020_000_000_000 <= i64::MAX + let ok = build_macro_rows( + vec![obs("US", "rate", 106_751_990, 5.0)], + |_, _| Some(MacroLagClass::PolicyRate), + ) + .expect("adjacent representable policy-rate date must succeed"); + assert_accounting_and_order(&ok); + assert_eq!(ok.rows.len(), 1); + assert_eq!(ok.rows[0].period_date, 106_751_990); + assert_eq!(ok.rows[0].known_at, 106_751_991_i64 * 86_400_000_000); +}