diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 41c0bbcf..5f90bda9 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1673,7 +1673,7 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **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`. -- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow>`) atomically to `/macro/part.parquet` (6-column Zstd contract schema); deferred: `teData` BSON decoding, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access. +- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow>`) atomically to `/macro/part.parquet` (6-column Zstd contract schema); deferred: file-to-file runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access. ## Zero-Copy `teData` BSON Decoder (`M2.2p`) @@ -1682,3 +1682,10 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **History-only (zero forecast leakage):** Reads only `data` (`[{ d: "YYYY-MM-DD", v: number }]`) and skips `forecast`, descriptive metadata, timestamps, and unknown fields without calling `elem.value()`. - **Writer-derived schema & no hardcoded mappings:** Field names (`teSymbol`, `country`, `category`, `data`, `forecast`, `d`, `v`) come from `apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts` and are not verified against a live `mongodump`. Provider `te_symbol`, `country`, and `category` strings are preserved verbatim; downstream runners own country/indicator/lag mapping into `build_macro_rows`. - **Fail-closed accounting:** Rejects missing/empty/non-string `teSymbol`, `country`, or `category`, and missing/non-array `data` before emitting any point; rejects malformed/non-string `d` and non-numeric `v` per point while passing finite and non-finite `Double` values through unchanged. `BsonTeDataDecodeStats` maintains `docs_in == docs_accepted + docs_rejected_total()` and `points_in == points_decoded + rejected_total()`. + +## Pure `macro` Curation Stage (`M2.2q`) + +`curate_macro` and `curate_and_write_macro` (`src/curate_macro.rs`, tested in `src/curate_macro_tests.rs`) join decoded `TeDataPoint<'a>` records, `build_macro_rows`, and `write_macro_dataset` into atomically published `/macro/part.parquet`: + +- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option`; unmapped points are dropped into `dropped_unmapped_series` with no default lag, and conflicting lag classes targeting the same `(country_iso, indicator)` fail closed with `CurateMacroError::ConflictingLagClass` independent of input order before writing. +- **Delegated builder & atomic publish:** Delegates filtering, sorting, deduplication, and `known_at` calculation unchanged to `build_macro_rows`, emits strictly ascending unique `MacroParquetRow`s with reconciling `CurateMacroStats` (`points_in == dropped_unmapped_series + builder.input`, `rows_out == builder.emitted`), and leaves `/macro/part.parquet` untouched on empty/all-unmapped input or any curation error. diff --git a/tools/curate-etl/src/curate_macro.rs b/tools/curate-etl/src/curate_macro.rs new file mode 100644 index 00000000..73fb72ff --- /dev/null +++ b/tools/curate-etl/src/curate_macro.rs @@ -0,0 +1,347 @@ +//! Pure, in-memory `macro` curation stage joining [`crate::bson_te_data::TeDataPoint`], +//! [`crate::macro_series::build_macro_rows`], and +//! [`crate::parquet_macro::write_macro_dataset`] into contract [`MacroParquetRow`]s. +//! +//! # Governance & Contract Rules +//! - **Caller-owned series mapping:** Every [`TeDataPoint`] carries verbatim provider +//! `(te_symbol, country, category)` labels. No country-to-ISO, indicator-name, or lag-class +//! mapping is hardcoded here because live `teData` labels are unverified and Quant Research owns +//! the coarse regime-use policy. +//! - **Fail-closed unmapped drop:** Points whose `(te_symbol, country, category)` maps to `None` +//! are dropped and counted in [`CurateMacroStats::dropped_unmapped_series`] without ever +//! assigning a default publication lag. +//! - **Fail-closed lag-class consistency:** If two mapped points reach the same +//! `(country_iso, indicator)` target with different [`MacroLagClass`] values (even if one point +//! has a non-finite value), curation fails with [`CurateMacroError::ConflictingLagClass`] +//! naming the first conflicting target in ascending `(country_iso, indicator)` key order, +//! independent of input order. +//! - **Delegated builder semantics:** Mapped observations pass unchanged to [`build_macro_rows`] +//! for finite-value filtering, sorting, bitwise deduplication / conflict detection, and +//! estimated `known_at` calculation (`00:00:00 UTC` of `period_date + lag_days`, +//! `known_at_source = "publication_lag_estimate"`). Output rows are converted via +//! [`MacroParquetRow::from`] in strictly ascending, unique `(country_iso, indicator, period_date)` +//! order. + +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; +use std::path::Path; + +use crate::bson_te_data::TeDataPoint; +use crate::macro_series::{ + build_macro_rows, MacroBuildStats, MacroError, MacroLagClass, MacroObservation, +}; +use crate::parquet_macro::{ + write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError, +}; + +/// Caller-supplied mapping target for a provider `teData` series. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct MacroSeriesTarget { + pub country_iso: String, + pub indicator: String, + pub lag_class: MacroLagClass, +} + +/// Accounting summary produced alongside [`CurateMacroOutput::rows`]. +/// +/// Conservation invariants: +/// - `points_in == dropped_unmapped_series + builder.input` +/// - `rows_out == builder.emitted` +/// - `builder` independently satisfies +/// `builder.input == builder.emitted + builder.skipped_unmapped_indicator + builder.skipped_non_finite_value + builder.skipped_duplicate` +/// (with `builder.skipped_unmapped_indicator == 0` because unmapped series are filtered before +/// calling [`build_macro_rows`]). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateMacroStats { + pub builder: MacroBuildStats, + pub points_in: usize, + pub rows_out: usize, + pub dropped_unmapped_series: usize, + pub series_out: usize, +} + +/// Output of [`curate_macro`]: contract Parquet rows strictly ascending and unique by +/// `(country_iso, indicator, period_date)` and reconciling stage + builder stats. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateMacroOutput { + pub rows: Vec, + pub stats: CurateMacroStats, +} + +/// Typed error returned by [`curate_macro`]. +/// +/// Every variant's `Display` output is guaranteed to be a single line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CurateMacroError { + /// One `(country_iso, indicator)` target was reached with two different [`MacroLagClass`] + /// values across mapped points. `first_lag_class < second_lag_class` in [`MacroLagClass`] + /// `Ord` order so the error is identical for any input permutation. + ConflictingLagClass { + country_iso: String, + indicator: String, + first_lag_class: MacroLagClass, + second_lag_class: MacroLagClass, + }, + /// Error propagated from [`build_macro_rows`] (`ConflictingDuplicate` or `KnownAtOverflow`). + Macro(MacroError), +} + +fn fmt_single_line(f: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result { + for ch in text.chars() { + match ch { + '\n' => f.write_str("\\n")?, + '\r' => f.write_str("\\r")?, + other => fmt::Write::write_char(f, other)?, + } + } + Ok(()) +} + +impl fmt::Display for CurateMacroError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ConflictingLagClass { + country_iso, + indicator, + first_lag_class, + second_lag_class, + } => write!( + f, + "conflicting lag classes for macro target ({country_iso:?}, {indicator:?}): {first_lag_class:?} (+{}d) vs {second_lag_class:?} (+{}d)", + first_lag_class.lag_days(), + second_lag_class.lag_days(), + ), + Self::Macro(err) => fmt_single_line(f, &err.to_string()), + } + } +} + +impl Error for CurateMacroError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::ConflictingLagClass { .. } => None, + Self::Macro(err) => Some(err), + } + } +} + +impl From> for CurateMacroError { + fn from(err: MacroError) -> Self { + Self::Macro(err) + } +} + +/// Combined stats returned by [`curate_and_write_macro`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CurateMacroWriteReport { + pub curate_stats: CurateMacroStats, + pub write_stats: MacroWriteStats, +} + +/// Typed error returned by [`curate_and_write_macro`]. +/// +/// Every variant's `Display` output is guaranteed to be a single line. +#[derive(Debug)] +pub enum CurateMacroWriteError { + Curate(CurateMacroError), + Parquet(ParquetMacroError), +} + +impl fmt::Display for CurateMacroWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Curate(err) => { + f.write_str("macro curation failed: ")?; + fmt_single_line(f, &err.to_string()) + } + Self::Parquet(err) => { + f.write_str("macro Parquet write failed: ")?; + fmt_single_line(f, &err.to_string()) + } + } + } +} + +impl Error for CurateMacroWriteError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Curate(err) => Some(err), + Self::Parquet(err) => Some(err), + } + } +} + +impl From for CurateMacroWriteError { + fn from(err: CurateMacroError) -> Self { + Self::Curate(err) + } +} + +impl From for CurateMacroWriteError { + fn from(err: ParquetMacroError) -> Self { + Self::Parquet(err) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LagAssignment { + Single(MacroLagClass), + Conflict { + min_class: MacroLagClass, + max_class: MacroLagClass, + }, +} + +impl LagAssignment { + #[inline] + fn record(&mut self, lag_class: MacroLagClass) { + match *self { + Self::Single(existing) if existing == lag_class => {} + Self::Single(existing) => { + *self = Self::Conflict { + min_class: existing.min(lag_class), + max_class: existing.max(lag_class), + }; + } + Self::Conflict { + min_class, + max_class, + } => { + *self = Self::Conflict { + min_class: min_class.min(lag_class), + max_class: max_class.max(lag_class), + }; + } + } + } + + #[inline] + fn single(&self) -> Option { + match *self { + Self::Single(class) => Some(class), + Self::Conflict { .. } => None, + } + } +} + +/// Pure `macro` curation stage: maps decoded [`TeDataPoint`]s via the caller-supplied +/// `(te_symbol, country, category) -> Option` lookup, verifies lag-class +/// consistency per `(country_iso, indicator)` target, delegates filtering, deduplication, and +/// `known_at` derivation to [`build_macro_rows`], and emits contract [`MacroParquetRow`]s +/// strictly ascending and unique by `(country_iso, indicator, period_date)`. +/// +/// The caller lookup `series_for` must be deterministic/stable for each verbatim +/// `(te_symbol, country, category)` triple. Any permutation of `points` produces identical `rows` +/// (including `f64` bit patterns) and `stats`, or the same [`CurateMacroError`]. +pub fn curate_macro<'a, I, F>( + points: I, + series_for: F, +) -> Result +where + I: IntoIterator>, + F: Fn(&str, &str, &str) -> Option, +{ + let iter = points.into_iter(); + let (lower, _) = iter.size_hint(); + let mut stats = CurateMacroStats::default(); + let mut observations: Vec> = Vec::with_capacity(lower); + let mut target_lags: BTreeMap> = BTreeMap::new(); + + for point in iter { + stats.points_in += 1; + let Some(target) = series_for(point.te_symbol, point.country, point.category) else { + stats.dropped_unmapped_series += 1; + continue; + }; + + if let Some(assignment) = target_lags + .get_mut(&target.country_iso) + .and_then(|by_indicator| by_indicator.get_mut(&target.indicator)) + { + assignment.record(target.lag_class); + } else { + target_lags + .entry(target.country_iso.clone()) + .or_default() + .insert( + target.indicator.clone(), + LagAssignment::Single(target.lag_class), + ); + } + + observations.push(MacroObservation { + country_iso: target.country_iso, + indicator: target.indicator, + period_date: point.period_date, + value: point.value, + }); + } + + for (country_iso, by_indicator) in &target_lags { + for (indicator, assignment) in by_indicator { + if let LagAssignment::Conflict { + min_class, + max_class, + } = *assignment + { + return Err(CurateMacroError::ConflictingLagClass { + country_iso: country_iso.clone(), + indicator: indicator.clone(), + first_lag_class: min_class, + second_lag_class: max_class, + }); + } + } + } + + let built = build_macro_rows(observations, |country_iso, indicator| { + target_lags + .get(country_iso.as_str()) + .and_then(|by_indicator| by_indicator.get(indicator.as_str())) + .and_then(LagAssignment::single) + })?; + + stats.builder = built.stats; + let rows: Vec = built.rows.iter().map(MacroParquetRow::from).collect(); + stats.rows_out = rows.len(); + + let mut last_series: Option<(&str, &str)> = None; + for row in &rows { + let series = (row.country_iso.as_ref(), row.indicator.as_ref()); + if last_series != Some(series) { + stats.series_out += 1; + last_series = Some(series); + } + } + + Ok(CurateMacroOutput { rows, stats }) +} + +/// Thin end-to-end wrapper running [`curate_macro`] and publishing the resulting contract rows +/// via [`write_macro_dataset`] to `/macro/part.parquet`. +/// +/// Any [`CurateMacroError`] returns before [`write_macro_dataset`] is invoked, leaving `out_dir` +/// and any pre-existing `macro/part.parquet` completely untouched. +pub fn curate_and_write_macro<'a, P, I, F>( + out_dir: P, + points: I, + series_for: F, + options: MacroWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator>, + F: Fn(&str, &str, &str) -> Option, +{ + let curated = curate_macro(points, series_for)?; + let write_stats = write_macro_dataset(out_dir, &curated.rows, options)?; + Ok(CurateMacroWriteReport { + curate_stats: curated.stats, + write_stats, + }) +} + +#[cfg(test)] +#[path = "curate_macro_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_macro_tests.rs b/tools/curate-etl/src/curate_macro_tests.rs new file mode 100644 index 00000000..ea63fb65 --- /dev/null +++ b/tools/curate-etl/src/curate_macro_tests.rs @@ -0,0 +1,1069 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; +use bson::DateTime; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroStats, + CurateMacroWriteError, MacroSeriesTarget, +}; +use crate::bson_te_data::{decode_te_data_doc, TeDataPoint}; +use crate::macro_series::{ + MacroError, MacroLagClass, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, + MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, +}; +use crate::parquet_macro::{ + write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError, +}; +use crate::split::ymd_to_epoch_days; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +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-macro-test-{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 make_point_doc(d: &str, v: f64) -> RawDocumentBuf { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), d); + pt.append(cstr!("v"), v); + pt +} + +fn make_te_data_doc( + te_symbol: &str, + country: &str, + category: &str, + data_points: &[(&str, f64)], + forecast_points: &[(&str, f64)], +) -> RawDocumentBuf { + let mut data_arr = RawArrayBuf::new(); + for &(d, v) in data_points { + data_arr.push(make_point_doc(d, v)); + } + + let mut forecast_arr = RawArrayBuf::new(); + for &(d, v) in forecast_points { + forecast_arr.push(make_point_doc(d, v)); + } + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("teSymbol"), te_symbol); + doc.append(cstr!("name"), format!("{country} {category}")); + doc.append(cstr!("unit"), "percent"); + doc.append(cstr!("source"), "TradingEconomics"); + doc.append(cstr!("frequency"), "Monthly"); + doc.append(cstr!("country"), country); + doc.append(cstr!("category"), category); + doc.append(cstr!("data"), data_arr); + doc.append(cstr!("forecast"), forecast_arr); + doc.append( + cstr!("lastUpdated"), + DateTime::from_millis(1_710_000_000_000), + ); + doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000)); + doc +} + +fn target(country_iso: &str, indicator: &str, lag_class: MacroLagClass) -> MacroSeriesTarget { + MacroSeriesTarget { + country_iso: country_iso.to_owned(), + indicator: indicator.to_owned(), + lag_class, + } +} + +fn expected_row( + country_iso: &'static str, + indicator: &'static str, + period_date: i32, + lag_days: i32, + value: f64, +) -> MacroParquetRow { + MacroParquetRow { + country_iso: Cow::Borrowed(country_iso), + indicator: Cow::Borrowed(indicator), + period_date, + known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY, + known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE), + value, + } +} + +fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + 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 read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_f64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned()) + .collect() + }; + + let country_iso = read_str(0); + let indicator = read_str(1); + let period_date = read_i32(2); + let known_at_micros = read_i64(3); + let known_at_source = read_str(4); + let value = read_f64(5); + + for i in 0..num_rows { + out.push(MacroParquetRow { + country_iso: Cow::Owned(country_iso[i].clone()), + indicator: Cow::Owned(indicator[i].clone()), + period_date: period_date[i], + known_at_micros: known_at_micros[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + value: value[i], + }); + } + } + out +} + +fn assert_rows_bitwise_eq(actual: &[MacroParquetRow], expected: &[MacroParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count mismatch"); + for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() { + assert_eq!(a.country_iso, e.country_iso, "row {idx} country_iso"); + assert_eq!(a.indicator, e.indicator, "row {idx} indicator"); + assert_eq!(a.period_date, e.period_date, "row {idx} period_date"); + assert_eq!( + a.known_at_micros, e.known_at_micros, + "row {idx} known_at_micros" + ); + assert_eq!( + a.known_at_source, e.known_at_source, + "row {idx} known_at_source" + ); + assert_eq!( + a.value.to_bits(), + e.value.to_bits(), + "row {idx} value bits ({} vs {})", + a.value, + e.value + ); + } +} + +fn assert_strictly_ascending_unique(rows: &[MacroParquetRow]) { + for pair in rows.windows(2) { + let prev = ( + pair[0].country_iso.as_ref(), + pair[0].indicator.as_ref(), + pair[0].period_date, + ); + let next = ( + pair[1].country_iso.as_ref(), + pair[1].indicator.as_ref(), + pair[1].period_date, + ); + assert!( + prev < next, + "rows not strictly ascending and unique: {prev:?} >= {next:?}" + ); + } +} + +fn assert_stats_conserved(stats: &CurateMacroStats) { + assert_eq!( + stats.points_in, + stats.dropped_unmapped_series + stats.builder.input, + "stage input conservation failed: {stats:?}" + ); + assert_eq!( + stats.rows_out, stats.builder.emitted, + "stage output conservation failed: {stats:?}" + ); + assert_eq!( + stats.builder.skipped_unmapped_indicator, 0, + "builder should never observe unmapped indicators from stage: {stats:?}" + ); + assert_eq!( + stats.builder.input, + stats.builder.emitted + + stats.builder.skipped_unmapped_indicator + + stats.builder.skipped_non_finite_value + + stats.builder.skipped_duplicate, + "builder conservation failed: {stats:?}" + ); +} + +fn sorted_dir_entries(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + let mut entries: Vec = fs::read_dir(dir) + .expect("read dir") + .map(|entry| { + entry + .expect("dir entry") + .file_name() + .to_string_lossy() + .into_owned() + }) + .collect(); + entries.sort(); + entries +} + +fn seed_existing_parquet(out_dir: &Path) -> (PathBuf, Vec, Vec) { + let seed = vec![ + expected_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), + expected_row( + "US", + "cpi_yoy", + day(2024, 1, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.1, + ), + ]; + write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).expect("seed parquet"); + let part = out_dir.join("macro/part.parquet"); + let bytes = fs::read(&part).expect("read seeded parquet"); + let entries = sorted_dir_entries(&out_dir.join("macro")); + (part, bytes, entries) +} + +#[test] +fn decode_te_data_bson_curate_and_write_all_four_lag_classes_without_forecast_leakage() { + let docs = vec![ + make_te_data_doc( + "USGDPQOQ", + "United States", + "GDP Growth Rate", + &[("2024-03-31", 1.4), ("2024-06-30", -0.0)], + &[("2025-12-31", 99.9)], + ), + make_te_data_doc( + "CAGDPQOQ", + "Canada", + "GDP Growth Rate", + &[("2024-03-31", -0.25)], + &[("2026-03-31", 88.8)], + ), + make_te_data_doc( + "USCPIYOY", + "United States", + "Inflation Rate", + &[("2024-02-29", 3.2), ("2024-01-31", 3.1)], + &[("2025-06-30", 77.7)], + ), + make_te_data_doc( + "CABOCRATE", + "Canada", + "Interest Rate", + &[("2024-01-24", 5.0), ("2024-06-05", 0.0)], + &[("2025-09-30", 66.6)], + ), + make_te_data_doc( + "UKUNEMP", + "United Kingdom", + "Unemployment Rate", + &[("2024-01-31", 4.2)], + &[("2025-10-31", 55.5)], + ), + ]; + + let mut decoded_points: Vec> = Vec::new(); + let mut decode_errors = Vec::new(); + let mut total_points_in = 0usize; + let mut total_points_decoded = 0usize; + for doc in &docs { + let stats = decode_te_data_doc( + doc.as_ref(), + |pt| decoded_points.push(pt), + |err| decode_errors.push(err), + ); + assert_eq!(stats.docs_accepted, 1); + assert_eq!(stats.docs_rejected_total(), 0); + assert_eq!(stats.rejected_total(), 0); + total_points_in += stats.points_in; + total_points_decoded += stats.points_decoded; + } + assert!(decode_errors.is_empty(), "unexpected decode errors: {decode_errors:?}"); + // Only the 8 historical data points were decoded; none of the 5 forecast points leaked. + assert_eq!(total_points_in, 8); + assert_eq!(total_points_decoded, 8); + assert_eq!(decoded_points.len(), 8); + + let series_map = |te_symbol: &str, country: &str, category: &str| match ( + te_symbol, country, category, + ) { + ("CABOCRATE", "Canada", "Interest Rate") => { + Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)) + } + ("USCPIYOY", "United States", "Inflation Rate") => { + Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) + } + ("USGDPQOQ", "United States", "GDP Growth Rate") => { + Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)) + } + ("CAGDPQOQ", "Canada", "GDP Growth Rate") => { + Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90)) + } + _ => None, + }; + + let tmp = TempDirGuard::new("bson-roundtrip"); + let report = curate_and_write_macro( + tmp.path(), + decoded_points, + series_map, + MacroWriteOptions::default(), + ) + .expect("curate_and_write_macro should succeed"); + + assert_stats_conserved(&report.curate_stats); + assert_eq!(report.curate_stats.points_in, 8); + assert_eq!(report.curate_stats.dropped_unmapped_series, 1); + assert_eq!(report.curate_stats.builder.input, 7); + assert_eq!(report.curate_stats.builder.emitted, 7); + assert_eq!(report.curate_stats.rows_out, 7); + assert_eq!(report.curate_stats.series_out, 4); + assert_eq!(report.write_stats.rows_written, 7); + assert_eq!(report.write_stats.files_written, 1); + + let part_path = tmp.path().join("macro/part.parquet"); + assert!(part_path.exists()); + assert_eq!( + sorted_dir_entries(&tmp.path().join("macro")), + vec!["part.parquet"] + ); + + let read_back = read_parquet_rows(&part_path); + assert_strictly_ascending_unique(&read_back); + + let expected = vec![ + expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, -0.25), + expected_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), + expected_row("CA", "policy_rate", day(2024, 6, 5), POLICY_RATE_LAG_DAYS, 0.0), + expected_row("US", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 3.1), + expected_row("US", "cpi_yoy", day(2024, 2, 29), MONTHLY_RELEASE_LAG_DAYS, 3.2), + expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4), + expected_row("US", "gdp_qoq", day(2024, 6, 30), GDP65_LAG_DAYS, -0.0), + ]; + assert_rows_bitwise_eq(&read_back, &expected); + + // Explicitly verify each lag class UTC midnight timestamp and provenance label, and absence of + // all forecast dates. + let forecast_dates = [ + day(2025, 12, 31), + day(2026, 3, 31), + day(2025, 6, 30), + day(2025, 9, 30), + day(2025, 10, 31), + ]; + for row in &read_back { + assert_eq!(row.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE); + assert_eq!(row.known_at_source.as_ref(), "publication_lag_estimate"); + assert_eq!(row.known_at_micros % MICROS_PER_DAY, 0); + assert!( + !forecast_dates.contains(&row.period_date), + "forecast date leaked into output: {row:?}" + ); + } + assert_eq!( + read_back[0].known_at_micros, + i64::from(day(2024, 3, 31) + 90) * MICROS_PER_DAY + ); + assert_eq!( + read_back[1].known_at_micros, + i64::from(day(2024, 1, 24) + 1) * MICROS_PER_DAY + ); + assert_eq!( + read_back[3].known_at_micros, + i64::from(day(2024, 1, 31) + 35) * MICROS_PER_DAY + ); + assert_eq!( + read_back[5].known_at_micros, + i64::from(day(2024, 3, 31) + 65) * MICROS_PER_DAY + ); +} + +#[test] +fn permutation_invariance_unmapped_duplicates_and_non_finite_accounting() { + let base_points = vec![ + // Mapped US cpi_yoy (+35d): two dates + exact duplicate + NaN + +inf + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 2, 29), + value: 3.2, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 3, 31), + value: f64::NAN, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 4, 30), + value: f64::INFINITY, + }, + // Mapped CA policy_rate (+1d): one finite + one -inf + TeDataPoint { + te_symbol: "CABOCRATE", + country: "Canada", + category: "Interest Rate", + period_date: day(2024, 1, 24), + value: 5.0, + }, + TeDataPoint { + te_symbol: "CABOCRATE", + country: "Canada", + category: "Interest Rate", + period_date: day(2024, 3, 6), + value: f64::NEG_INFINITY, + }, + // Unmapped tuples: case difference, whitespace difference, and unknown series + TeDataPoint { + te_symbol: "uscpiyoy", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 9.9, + }, + TeDataPoint { + te_symbol: "USCPIYOY ", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 9.9, + }, + TeDataPoint { + te_symbol: "DEUNEMP", + country: "Germany", + category: "Unemployment Rate", + period_date: day(2024, 1, 31), + value: 5.9, + }, + ]; + + let series_map = |te_symbol: &str, country: &str, category: &str| match ( + te_symbol, country, category, + ) { + ("USCPIYOY", "United States", "Inflation Rate") => { + Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) + } + ("CABOCRATE", "Canada", "Interest Rate") => { + Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)) + } + _ => None, + }; + + let mut reversed = base_points.clone(); + reversed.reverse(); + + let interleaved: Vec> = vec![ + base_points[9], + base_points[5], + base_points[2], + base_points[7], + base_points[4], + base_points[0], + base_points[8], + base_points[6], + base_points[3], + base_points[1], + ]; + + let out_base = curate_macro(base_points, series_map).expect("base ok"); + let out_rev = curate_macro(reversed, series_map).expect("reversed ok"); + let out_inter = curate_macro(interleaved, series_map).expect("interleaved ok"); + + for out in [&out_base, &out_rev, &out_inter] { + assert_strictly_ascending_unique(&out.rows); + assert_stats_conserved(&out.stats); + assert_eq!(out.stats.points_in, 10); + assert_eq!(out.stats.dropped_unmapped_series, 3); + assert_eq!(out.stats.builder.input, 7); + assert_eq!(out.stats.builder.emitted, 3); + assert_eq!(out.stats.builder.skipped_non_finite_value, 3); + assert_eq!(out.stats.builder.skipped_duplicate, 1); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.series_out, 2); + } + + assert_eq!(out_base.stats, out_rev.stats); + assert_eq!(out_base.stats, out_inter.stats); + assert_rows_bitwise_eq(&out_base.rows, &out_rev.rows); + assert_rows_bitwise_eq(&out_base.rows, &out_inter.rows); + + let expected = vec![ + expected_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), + expected_row("US", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 3.1), + expected_row("US", "cpi_yoy", day(2024, 2, 29), MONTHLY_RELEASE_LAG_DAYS, 3.2), + ]; + assert_rows_bitwise_eq(&out_base.rows, &expected); +} + +#[test] +fn empty_and_all_unmapped_inputs_produce_zero_rows_and_do_not_touch_out_dir() { + let never_map = |_: &str, _: &str, _: &str| -> Option { None }; + + // 1. Fresh directory with empty input + let fresh_empty = TempDirGuard::new("fresh-empty"); + let report = curate_and_write_macro( + fresh_empty.path(), + std::iter::empty::>(), + never_map, + MacroWriteOptions::default(), + ) + .expect("empty input succeeds"); + assert_stats_conserved(&report.curate_stats); + assert_eq!(report.curate_stats.points_in, 0); + assert_eq!(report.curate_stats.rows_out, 0); + assert_eq!(report.curate_stats.series_out, 0); + assert_eq!(report.write_stats, MacroWriteStats::default()); + assert!(!fresh_empty.path().join("macro").exists()); + + // 2. Fresh directory with all-unmapped input + let fresh_unmapped = TempDirGuard::new("fresh-unmapped"); + let unmapped = [TeDataPoint { + te_symbol: "UNKNOWN", + country: "Nowhere", + category: "Mystery", + period_date: day(2024, 1, 1), + value: 1.0, + }]; + let report = curate_and_write_macro( + fresh_unmapped.path(), + unmapped, + never_map, + MacroWriteOptions::default(), + ) + .expect("all-unmapped input succeeds"); + assert_stats_conserved(&report.curate_stats); + assert_eq!(report.curate_stats.points_in, 1); + assert_eq!(report.curate_stats.dropped_unmapped_series, 1); + assert_eq!(report.curate_stats.rows_out, 0); + assert_eq!(report.curate_stats.series_out, 0); + assert_eq!(report.write_stats, MacroWriteStats::default()); + assert!(!fresh_unmapped.path().join("macro").exists()); + + // 3. Pre-existing part.parquet is preserved byte-identical on all-unmapped input + let existing = TempDirGuard::new("existing-unmapped"); + let (part, before_bytes, before_entries) = seed_existing_parquet(existing.path()); + let report = curate_and_write_macro( + existing.path(), + unmapped, + never_map, + MacroWriteOptions::default(), + ) + .expect("all-unmapped against existing succeeds"); + assert_eq!(report.write_stats, MacroWriteStats::default()); + assert_eq!(fs::read(&part).expect("read after"), before_bytes); + assert_eq!( + sorted_dir_entries(&existing.path().join("macro")), + before_entries + ); +} + +#[test] +fn conflicting_duplicate_and_signed_zero_propagate_macro_error() { + let map_cpi = |_: &str, _: &str, _: &str| { + Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) + }; + + // Unequal finite values at same (country_iso, indicator, period_date) + let unequal = [ + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 1, 31), + value: 3.2, + }, + ]; + let err = curate_macro(unequal, map_cpi).expect_err("unequal duplicate must fail"); + assert_eq!( + err, + CurateMacroError::Macro(MacroError::ConflictingDuplicate { + country_iso: "US".to_owned(), + indicator: "cpi_yoy".to_owned(), + period_date: day(2024, 1, 31), + }) + ); + assert!(err.source().is_some()); + + // Opposite signed zeros (+0.0 vs -0.0) at same (country_iso, indicator, period_date) + let signed_zeros = [ + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 2, 29), + value: 0.0, + }, + TeDataPoint { + te_symbol: "USCPIYOY", + country: "United States", + category: "Inflation Rate", + period_date: day(2024, 2, 29), + value: -0.0, + }, + ]; + let err = curate_macro(signed_zeros, map_cpi).expect_err("signed zero conflict must fail"); + assert_eq!( + err, + CurateMacroError::Macro(MacroError::ConflictingDuplicate { + country_iso: "US".to_owned(), + indicator: "cpi_yoy".to_owned(), + period_date: day(2024, 2, 29), + }) + ); +} + +#[test] +fn conflicting_lag_class_is_order_independent_and_checks_before_non_finite_filtering() { + // Two distinct provider aliases targeting the same (country_iso, indicator) on different dates + // with different lag classes, including one non-finite point. + let p_gdp65 = TeDataPoint { + te_symbol: "USGDP_FAST", + country: "United States", + category: "GDP Growth Rate", + period_date: day(2024, 3, 31), + value: 1.4, + }; + let p_gdp90_nan = TeDataPoint { + te_symbol: "USGDP_SLOW", + country: "United States", + category: "GDP Growth Rate Revised", + period_date: day(2024, 6, 30), + value: f64::NAN, + }; + + let alias_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), + "USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), + _ => None, + }; + + let err_ab = curate_macro([p_gdp65, p_gdp90_nan], alias_map).expect_err("order A must fail"); + let err_ba = curate_macro([p_gdp90_nan, p_gdp65], alias_map).expect_err("order B must fail"); + + let expected = CurateMacroError::ConflictingLagClass { + country_iso: "US".to_owned(), + indicator: "gdp_qoq".to_owned(), + first_lag_class: MacroLagClass::Gdp65, + second_lag_class: MacroLagClass::Gdp90, + }; + assert_eq!(err_ab, expected); + assert_eq!(err_ba, expected); + assert!(err_ab.source().is_none()); + + // Multiple conflicting targets: always report the lowest (country_iso, indicator) in key order. + let ca_rate_a = TeDataPoint { + te_symbol: "CA_A", + country: "Canada", + category: "Rate", + period_date: day(2024, 1, 1), + value: 5.0, + }; + let ca_rate_b = TeDataPoint { + te_symbol: "CA_B", + country: "Canada", + category: "Rate", + period_date: day(2024, 2, 1), + value: 5.0, + }; + let multi_map = |te_symbol: &str, _: &str, _: &str| match te_symbol { + "USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)), + "USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)), + "CA_A" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)), + "CA_B" => Some(target("CA", "policy_rate", MacroLagClass::MonthlyRelease)), + _ => None, + }; + + let err_multi_1 = curate_macro([p_gdp65, p_gdp90_nan, ca_rate_a, ca_rate_b], multi_map) + .expect_err("multi 1 must fail"); + let err_multi_2 = curate_macro([ca_rate_b, p_gdp90_nan, ca_rate_a, p_gdp65], multi_map) + .expect_err("multi 2 must fail"); + assert_eq!( + err_multi_1, + CurateMacroError::ConflictingLagClass { + country_iso: "CA".to_owned(), + indicator: "policy_rate".to_owned(), + first_lag_class: MacroLagClass::PolicyRate, + second_lag_class: MacroLagClass::MonthlyRelease, + } + ); + assert_eq!(err_multi_1, err_multi_2); +} + +#[test] +fn known_at_overflow_and_invalid_write_options_and_single_line_display() { + // 1. KnownAtOverflow propagated from build_macro_rows + let overflow_pt = [TeDataPoint { + te_symbol: "EXTREME", + country: "United States", + category: "GDP", + period_date: i32::MAX, + value: 1.0, + }]; + let map_gdp90 = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90)); + let err = curate_macro(overflow_pt, map_gdp90).expect_err("overflow must fail"); + assert_eq!( + err, + CurateMacroError::Macro(MacroError::KnownAtOverflow { + period_date: i32::MAX, + lag_class: MacroLagClass::Gdp90, + }) + ); + assert!(err.source().is_some()); + let msg = err.to_string(); + assert!(!msg.contains('\n') && !msg.contains('\r'), "multi-line: {msg:?}"); + + // 2. InvalidRowGroupRows wrapped in CurateMacroWriteError::Parquet + let tmp = TempDirGuard::new("invalid-opts"); + let valid_pt = [TeDataPoint { + te_symbol: "CABOCRATE", + country: "Canada", + category: "Interest Rate", + period_date: day(2024, 1, 24), + value: 5.0, + }]; + let map_rate = + |_: &str, _: &str, _: &str| Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)); + let write_err = curate_and_write_macro( + tmp.path(), + valid_pt, + map_rate, + MacroWriteOptions { + row_group_rows: 0, + ..MacroWriteOptions::default() + }, + ) + .expect_err("row_group_rows=0 must fail"); + assert!(matches!( + write_err, + CurateMacroWriteError::Parquet(ParquetMacroError::InvalidRowGroupRows) + )); + assert!(write_err.source().is_some()); + let msg = write_err.to_string(); + assert!(!msg.contains('\n') && !msg.contains('\r'), "multi-line: {msg:?}"); + + // 3. Newline-bearing diagnostic labels stay single-line in both CurateMacroError and + // CurateMacroWriteError (covering ConflictingLagClass, ConflictingDuplicate, and Parquet). + let nl_lag_err = CurateMacroWriteError::from(CurateMacroError::ConflictingLagClass { + country_iso: "US\nline2".to_owned(), + indicator: "cpi\r\nyoy".to_owned(), + first_lag_class: MacroLagClass::PolicyRate, + second_lag_class: MacroLagClass::MonthlyRelease, + }); + let nl_lag_msg = nl_lag_err.to_string(); + assert!( + !nl_lag_msg.contains('\n') && !nl_lag_msg.contains('\r'), + "ConflictingLagClass display must be single-line: {nl_lag_msg:?}" + ); + assert!(nl_lag_msg.contains("US\\nline2")); + assert!(nl_lag_msg.contains("cpi\\r\\nyoy")); + + let nl_dup_err = CurateMacroWriteError::from(CurateMacroError::from( + MacroError::ConflictingDuplicate { + country_iso: "CA\n2".to_owned(), + indicator: "gdp\r3".to_owned(), + period_date: day(2024, 1, 1), + }, + )); + let nl_dup_msg = nl_dup_err.to_string(); + assert!( + !nl_dup_msg.contains('\n') && !nl_dup_msg.contains('\r'), + "ConflictingDuplicate display must be single-line: {nl_dup_msg:?}" + ); + + // ParquetMacroError::EmptyCountryIso displays `indicator` with `{indicator}`, so newlines + // would leak unless CurateMacroWriteError escapes them. + let nl_pq_err = curate_and_write_macro( + tmp.path(), + valid_pt, + |_: &str, _: &str, _: &str| { + Some(target(" ", "bad\nindicator\rname", MacroLagClass::PolicyRate)) + }, + MacroWriteOptions::default(), + ) + .expect_err("blank country_iso must fail in writer"); + assert!(matches!( + nl_pq_err, + CurateMacroWriteError::Parquet(ParquetMacroError::EmptyCountryIso { .. }) + )); + let nl_pq_msg = nl_pq_err.to_string(); + assert!( + !nl_pq_msg.contains('\n') && !nl_pq_msg.contains('\r'), + "Parquet display must be single-line: {nl_pq_msg:?}" + ); + assert!(nl_pq_msg.contains("bad\\nindicator\\rname")); +} + +#[test] +fn curation_errors_never_write_or_modify_out_dir() { + // 1. ConflictingLagClass + let lag_conflict_points = [ + TeDataPoint { + te_symbol: "A", + country: "US", + category: "GDP", + period_date: day(2024, 3, 31), + value: 1.4, + }, + TeDataPoint { + te_symbol: "B", + country: "US", + category: "GDP", + period_date: day(2024, 6, 30), + value: 1.8, + }, + ]; + let lag_conflict_map = |sym: &str, _: &str, _: &str| match sym { + "A" => Some(target("US", "gdp", MacroLagClass::Gdp65)), + "B" => Some(target("US", "gdp", MacroLagClass::Gdp90)), + _ => None, + }; + + // 2. ConflictingDuplicate + let dup_conflict_points = [ + TeDataPoint { + te_symbol: "A", + country: "US", + category: "CPI", + period_date: day(2024, 1, 31), + value: 3.1, + }, + TeDataPoint { + te_symbol: "A", + country: "US", + category: "CPI", + period_date: day(2024, 1, 31), + value: 3.2, + }, + ]; + let cpi_map = |_: &str, _: &str, _: &str| { + Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)) + }; + + // 3. KnownAtOverflow + let overflow_points = [TeDataPoint { + te_symbol: "A", + country: "US", + category: "GDP", + period_date: i32::MAX, + value: 1.0, + }]; + let gdp_map = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90)); + + // Fresh destination checks + for (label, result, dir) in [ + { + let dir = TempDirGuard::new("err-fresh-lag"); + let res = curate_and_write_macro( + dir.path(), + lag_conflict_points, + lag_conflict_map, + MacroWriteOptions::default(), + ); + ("ConflictingLagClass", res, dir) + }, + { + let dir = TempDirGuard::new("err-fresh-dup"); + let res = curate_and_write_macro( + dir.path(), + dup_conflict_points, + cpi_map, + MacroWriteOptions::default(), + ); + ("ConflictingDuplicate", res, dir) + }, + { + let dir = TempDirGuard::new("err-fresh-overflow"); + let res = curate_and_write_macro( + dir.path(), + overflow_points, + gdp_map, + MacroWriteOptions::default(), + ); + ("KnownAtOverflow", res, dir) + }, + ] { + let err = result.expect_err(&format!("{label} must fail")); + assert!( + matches!(err, CurateMacroWriteError::Curate(_)), + "{label} should be Curate error: {err}" + ); + assert!( + !dir.path().join("macro").exists(), + "{label} must not create macro/ dir" + ); + assert!( + sorted_dir_entries(dir.path()).is_empty(), + "{label} must leave fresh out_dir empty" + ); + } + + // Existing valid macro/part.parquet preservation checks + for (label, result, part, before_bytes, before_entries, dir) in [ + { + let dir = TempDirGuard::new("err-existing-lag"); + let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); + let res = curate_and_write_macro( + dir.path(), + lag_conflict_points, + lag_conflict_map, + MacroWriteOptions::default(), + ); + ("ConflictingLagClass", res, part, before_bytes, before_entries, dir) + }, + { + let dir = TempDirGuard::new("err-existing-dup"); + let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); + let res = curate_and_write_macro( + dir.path(), + dup_conflict_points, + cpi_map, + MacroWriteOptions::default(), + ); + ("ConflictingDuplicate", res, part, before_bytes, before_entries, dir) + }, + { + let dir = TempDirGuard::new("err-existing-overflow"); + let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path()); + let res = curate_and_write_macro( + dir.path(), + overflow_points, + gdp_map, + MacroWriteOptions::default(), + ); + ("KnownAtOverflow", res, part, before_bytes, before_entries, dir) + }, + ] { + let err = result.expect_err(&format!("{label} must fail")); + assert!( + matches!(err, CurateMacroWriteError::Curate(_)), + "{label} should be Curate error: {err}" + ); + assert_eq!( + fs::read(&part).expect("read existing parquet"), + before_bytes, + "{label} must leave existing part.parquet byte-identical" + ); + assert_eq!( + sorted_dir_entries(&dir.path().join("macro")), + before_entries, + "{label} must leave macro/ directory entries unchanged" + ); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6e49d299..c1dcf4ee 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -269,6 +269,12 @@ pub use curate_fundamentals::{ CurateFundamentalsWriteReport, }; +pub mod curate_macro; +pub use curate_macro::{ + curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroOutput, CurateMacroStats, + CurateMacroWriteError, CurateMacroWriteReport, MacroSeriesTarget, +}; + pub mod curate_fx; pub use curate_fx::{ curate_and_write_fx_1d, curate_fx_1d, fx_1d_utc_day_end_micros, CurateFx1dOutput,