From fc2312ebebce7b64d5293b772dc1329da95836ae Mon Sep 17 00:00:00 2001 From: Studio Date: Thu, 3 Dec 2026 14:50:00 -0500 Subject: [PATCH] =?UTF-8?q?T-199:=20M2.2s=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20file-mode=20`run=5Fcurate=5Fmacro`=20runner=20(`teData`=20B?= =?UTF-8?q?SON=20dump=20+=20caller-supplied=20series-map=20TSV=20=E2=86=92?= =?UTF-8?q?=20`curate=5Fand=5Fwrite=5Fmacro`=20=E2=86=92=20`macro/part.par?= =?UTF-8?q?quet`)=20in=20`run=5Fcurate=5Fmacro.rs`=20with=20lib=20tests=20?= =?UTF-8?q?(no=20new=20crates,=20no=20CLI/bench=20changes,=20no=20live=20M?= =?UTF-8?q?ongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 10 +- tools/curate-etl/src/lib.rs | 7 + tools/curate-etl/src/run_curate_macro.rs | 657 +++++++++++ .../curate-etl/src/run_curate_macro_tests.rs | 1047 +++++++++++++++++ 4 files changed, 1720 insertions(+), 1 deletion(-) create mode 100644 tools/curate-etl/src/run_curate_macro.rs create mode 100644 tools/curate-etl/src/run_curate_macro_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index f7c4cd28..d16eb94b 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1833,7 +1833,7 @@ curate-etl send-ilp \ - **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: file-to-file 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: CLI command (`curate-macro`), `macroAsOf` DuckDB reader, and live MongoDB access. ## Zero-Copy `teData` BSON Decoder (`M2.2p`) @@ -1849,3 +1849,11 @@ curate-etl send-ilp \ - **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. + +## `run_curate_macro` File-to-File Runner (`M2.2s`) + +`run_curate_macro` and `run_curate_macro_with_readers` (`src/run_curate_macro.rs`, tested in `src/run_curate_macro_tests.rs`) connect a concatenated length-prefixed raw BSON `teData` dump (`te_data`) and a caller-supplied series-map TSV (`series_map`) through `decode_te_data_buffer` and `curate_and_write_macro` into `/macro/part.parquet`: + +- **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbolcountrycategorycountry_isoindicatorlag_class` (LF or CRLF line endings). Each data row must have 6 nonempty tab-separated columns with verbatim `(te_symbol, country, category)` keys (no trimming, no case folding), unique key triples (duplicates fail closed even when targets match), and an exact `lag_class` token in `policy_rate`, `monthly_release`, `gdp65`, or `gdp90`. There is no hardcoded default mapping or default lag class. +- **Buffering, decode & fail-closed behavior:** Validates the full series map first, buffers the concatenated `teData` BSON input in memory (memory grows with dump size), counts per-document/per-point semantic rejects in `BsonTeDataDecodeStats`, and fails closed on the first structural BSON error (`TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`, `CorruptPointBson`) before publishing. Any I/O, TSV, structural BSON, or curation error (such as `ConflictingLagClass`) returns a single-line `RunCurateMacroError` and leaves `out_dir` and any pre-existing `/macro/part.parquet` byte-identical. Empty or all-unmapped inputs preserve `curate_and_write_macro`'s zero-row no-op. +- **Governance, provenance & reproducibility:** Quant Research owns the coarse regime-use policy and the caller owns the mapping. Because `teData` carries final-revised `{d, v}` values without verified release timestamps or historical vintages, observations become available strictly at the estimated `known_at` (`00:00:00 UTC` of `period_date + lag_days`, `known_at_source = "publication_lag_estimate"`) for coarse regime use. For reproducible checks, pin the `teData` BSON dump and series-map TSV together against the pure stage and fixed expected rows. Real QA `teData` provider-label verification remains a manual host check, and `curate-macro` CLI / `--from-mongo` wiring are separate follow-ups. diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a9c774db..a16d00be 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -388,6 +388,13 @@ pub use run_curate_fundamentals::{ CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, }; +pub mod run_curate_macro; +pub use run_curate_macro::{ + format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro, + run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap, + RunCurateMacroError, MACRO_SERIES_MAP_HEADER, +}; + pub mod run_curate_shorts; pub use run_curate_shorts::{ format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader, diff --git a/tools/curate-etl/src/run_curate_macro.rs b/tools/curate-etl/src/run_curate_macro.rs new file mode 100644 index 00000000..6d2320b8 --- /dev/null +++ b/tools/curate-etl/src/run_curate_macro.rs @@ -0,0 +1,657 @@ +//! File-to-file `curate-macro` runner (`M2.2s`). +//! +//! Reads a concatenated length-prefixed raw BSON `teData` dump and a caller-supplied +//! series-map TSV into an atomically published `/macro/part.parquet` dataset via +//! [`curate_and_write_macro`]. +//! +//! # Governance & Series-Map Contract +//! - **Caller-owned mapping (no defaults):** Every row in the series-map TSV maps a verbatim +//! `(te_symbol, country, category)` triple (no trimming, no case folding) to a +//! [`MacroSeriesTarget`] (`country_iso`, `indicator`, `lag_class`). 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. +//! - **Strict TSV format (`load_macro_series_map_tsv`):** +//! - Required exact line-1 header: +//! `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class` +//! - LF (`\n`) and CRLF (`\r\n`) line endings are accepted; bare/embedded `\r` and invalid UTF-8 +//! fail closed with the 1-based physical line number. +//! - Every data row must have exactly 6 nonempty tab-separated fields, verbatim keys, an exact +//! `lag_class` token in `{policy_rate, monthly_release, gdp65, gdp90}`, and unique +//! `(te_symbol, country, category)` triples (duplicates fail closed even when targets match). +//! +//! # Decode, Buffering & Fail-Closed Policy +//! - **Series-map validation first:** The entire series map is parsed and validated before any +//! `teData` bytes are decoded or `out_dir` is touched. +//! - **In-memory file-mode buffering:** `run_curate_macro_with_readers` buffers the concatenated +//! `teData` BSON input and collects borrowed [`TeDataPoint`] views from +//! [`decode_te_data_buffer`] before calling [`curate_and_write_macro`], so memory usage grows +//! with input size. +//! - **Decode error policy (matching `run_curate_fx.rs`):** Per-document and per-point semantic +//! rejects (missing/empty/wrong-type `teSymbol`, `country`, `category`, `data`, non-document +//! points, invalid point dates/values) are counted in [`BsonTeDataDecodeStats`] and skipped so +//! valid points continue. Structural BSON framing or element corruption +//! ([`BsonTeDataError::TruncatedDocument`], [`BsonTeDataError::CorruptDocumentLength`], +//! [`BsonTeDataError::CorruptBson`], [`BsonTeDataError::CorruptPointBson`]) is captured on the +//! first occurrence and returned as [`RunCurateMacroError::CorruptTeDataBson`] before publishing, +//! preventing partial datasets from a truncated or corrupt tail. +//! - **Atomic publish & zero-row preservation:** Any series-map, I/O, structural BSON, or curation +//! error (such as [`crate::curate_macro::CurateMacroError::ConflictingLagClass`]) returns before +//! writing, leaving `out_dir` and any pre-existing `/macro/part.parquet` byte-identical. +//! Empty or all-unmapped inputs preserve [`curate_and_write_macro`]'s zero-row success no-op. +//! +//! # Counter Conservation Invariants +//! Every successful [`CurateMacroRunReport`] satisfies: +//! - `decode_stats.docs_in == decode_stats.docs_accepted + decode_stats.docs_rejected_total()` +//! - `decode_stats.points_in == decode_stats.points_decoded + decode_stats.rejected_total()` +//! - `decode_stats.points_decoded == curate_stats.points_in` +//! - `curate_stats.points_in == curate_stats.dropped_unmapped_series + curate_stats.builder.input` +//! - `curate_stats.rows_out == curate_stats.builder.emitted == write_stats.rows_written` + +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt::{self, Write as _}; +use std::fs::File; +use std::io::{self, BufRead, BufReader}; +use std::path::{Path, PathBuf}; + +use crate::bson_te_data::{ + decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint, +}; +use crate::curate_macro::{ + curate_and_write_macro, CurateMacroError, CurateMacroStats, CurateMacroWriteError, + MacroSeriesTarget, +}; +use crate::macro_series::MacroLagClass; +use crate::parquet_macro::{MacroWriteOptions, MacroWriteStats, ParquetMacroError}; + +/// Required exact header line (line 1) for the macro series-map TSV. +pub const MACRO_SERIES_MAP_HEADER: &str = + "te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class"; + +const ROLE_TE_DATA: &str = "te-data"; +const ROLE_SERIES_MAP: &str = "series-map"; +const SERIES_MAP_COLUMN_COUNT: usize = 6; +const SERIES_MAP_COLUMNS: [&str; SERIES_MAP_COLUMN_COUNT] = [ + "te_symbol", + "country", + "category", + "country_iso", + "indicator", + "lag_class", +]; + +/// File-mode arguments for [`run_curate_macro`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateMacroArgs { + pub te_data: PathBuf, + pub series_map: PathBuf, + pub out_dir: PathBuf, +} + +/// Validated caller-owned lookup from verbatim `(te_symbol, country, category)` triples to +/// [`MacroSeriesTarget`], loaded by [`load_macro_series_map_tsv`]. +/// +/// Backed by nested [`BTreeMap`]s so lookups accept borrowed `&str` slices with zero allocation. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MacroSeriesMap { + entries: BTreeMap>>, + len: usize, +} + +impl MacroSeriesMap { + /// Returns the number of mapped series entries. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Returns `true` if the series map contains no entries. + #[inline] + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Looks up a verbatim `(te_symbol, country, category)` triple without trimming or case folding. + #[inline] + pub fn get( + &self, + te_symbol: &str, + country: &str, + category: &str, + ) -> Option<&MacroSeriesTarget> { + self.entries + .get(te_symbol) + .and_then(|by_country| by_country.get(country)) + .and_then(|by_category| by_category.get(category)) + } + + fn insert( + &mut self, + te_symbol: String, + country: String, + category: String, + target: MacroSeriesTarget, + ) -> bool { + let by_category = self + .entries + .entry(te_symbol) + .or_default() + .entry(country) + .or_default(); + if by_category.contains_key(&category) { + return false; + } + by_category.insert(category, target); + self.len += 1; + true + } +} + +/// Full run report produced by [`run_curate_macro`] and [`run_curate_macro_with_readers`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CurateMacroRunReport { + pub series_map_entries: usize, + pub decode_stats: BsonTeDataDecodeStats, + pub curate_stats: CurateMacroStats, + pub write_stats: MacroWriteStats, +} + +/// Typed errors returned by [`load_macro_series_map_tsv`], [`run_curate_macro`], and +/// [`run_curate_macro_with_readers`]. +/// +/// Every variant's `Display` output is guaranteed to be a single line (CR and LF in dynamic +/// strings, paths, and wrapped error messages are escaped as `\r` and `\n`). +#[derive(Debug)] +pub enum RunCurateMacroError { + /// Failed to open a file-mode input (`te-data` or `series-map`). + OpenInput { + role: &'static str, + path: PathBuf, + source: io::Error, + }, + /// Failed to read bytes from an input stream (`te-data` or `series-map`). + ReadInput { + role: &'static str, + path: Option, + source: io::Error, + }, + /// Series-map TSV line contained invalid UTF-8 or a bare/embedded carriage return. + SeriesMapMalformedLine { line: usize, detail: &'static str }, + /// Series-map TSV was empty or line 1 did not match [`MACRO_SERIES_MAP_HEADER`] verbatim. + SeriesMapBadHeader { line: usize, found: Option }, + /// Series-map TSV data row did not contain exactly 6 tab-separated columns. + SeriesMapWrongColumnCount { + line: usize, + expected: usize, + actual: usize, + }, + /// Series-map TSV data row contained an empty (or blank) required field. + SeriesMapEmptyField { line: usize, column: &'static str }, + /// Series-map TSV data row contained an unknown `lag_class` token. + SeriesMapUnknownLagClass { line: usize, value: String }, + /// Series-map TSV contained a duplicate `(te_symbol, country, category)` triple. + SeriesMapDuplicateKey { + line: usize, + te_symbol: String, + country: String, + category: String, + }, + /// Structural BSON framing or element corruption in `teData` input. + CorruptTeDataBson { + path: Option, + offset: usize, + source: BsonTeDataError, + }, + /// Error returned by [`curate_and_write_macro`] (curation or Parquet write). + CurateWrite(CurateMacroWriteError), +} + +impl RunCurateMacroError { + fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self { + match self { + Self::ReadInput { + role, + path: None, + source, + } => { + let path = match role { + ROLE_TE_DATA => Some(te_data.to_path_buf()), + ROLE_SERIES_MAP => Some(series_map.to_path_buf()), + _ => None, + }; + Self::ReadInput { role, path, source } + } + Self::CorruptTeDataBson { + path: None, + offset, + source, + } => Self::CorruptTeDataBson { + path: Some(te_data.to_path_buf()), + offset, + source, + }, + other => other, + } + } +} + +struct SingleLineWriter<'a, 'b> { + f: &'a mut fmt::Formatter<'b>, +} + +impl fmt::Write for SingleLineWriter<'_, '_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + let mut rest = s; + while let Some(idx) = rest.find(['\n', '\r']) { + let (head, tail) = rest.split_at(idx); + if !head.is_empty() { + self.f.write_str(head)?; + } + let mut chars = tail.chars(); + match chars.next() { + Some('\n') => self.f.write_str("\\n")?, + Some('\r') => self.f.write_str("\\r")?, + _ => unreachable!(), + } + rest = chars.as_str(); + } + if !rest.is_empty() { + self.f.write_str(rest)?; + } + Ok(()) + } +} + +impl fmt::Display for RunCurateMacroError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut w = SingleLineWriter { f }; + match self { + Self::OpenInput { role, path, source } => { + write!(w, "failed to open {role} '{}': {source}", path.display()) + } + Self::ReadInput { role, path, source } => match path { + Some(path) => write!(w, "failed to read {role} '{}': {source}", path.display()), + None => write!(w, "failed to read {role}: {source}"), + }, + Self::SeriesMapMalformedLine { line, detail } => { + write!(w, "series-map TSV line {line}: {detail}") + } + Self::SeriesMapBadHeader { line, found } => match found { + Some(found) => write!( + w, + "series-map TSV line {line}: invalid header {found:?}; expected exact {MACRO_SERIES_MAP_HEADER:?}" + ), + None => write!( + w, + "series-map TSV line {line}: missing required header {MACRO_SERIES_MAP_HEADER:?}" + ), + }, + Self::SeriesMapWrongColumnCount { + line, + expected, + actual, + } => write!( + w, + "series-map TSV line {line}: expected {expected} tab-separated columns, got {actual}" + ), + Self::SeriesMapEmptyField { line, column } => { + write!( + w, + "series-map TSV line {line}: field '{column}' must not be empty" + ) + } + Self::SeriesMapUnknownLagClass { line, value } => write!( + w, + "series-map TSV line {line}: unknown lag_class {value:?}; expected one of 'policy_rate', 'monthly_release', 'gdp65', 'gdp90'" + ), + Self::SeriesMapDuplicateKey { + line, + te_symbol, + country, + category, + } => write!( + w, + "series-map TSV line {line}: duplicate series key ({te_symbol:?}, {country:?}, {category:?})" + ), + Self::CorruptTeDataBson { + path, + offset, + source, + } => match path { + Some(path) => write!( + w, + "corrupt {ROLE_TE_DATA} BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + None => write!( + w, + "corrupt {ROLE_TE_DATA} BSON at byte offset {offset}: {source}" + ), + }, + Self::CurateWrite(source) => write!(w, "{source}"), + } + } +} + +impl Error for RunCurateMacroError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), + Self::CorruptTeDataBson { source, .. } => Some(source), + Self::CurateWrite(source) => Some(source), + Self::SeriesMapMalformedLine { .. } + | Self::SeriesMapBadHeader { .. } + | Self::SeriesMapWrongColumnCount { .. } + | Self::SeriesMapEmptyField { .. } + | Self::SeriesMapUnknownLagClass { .. } + | Self::SeriesMapDuplicateKey { .. } => None, + } + } +} + +impl From for RunCurateMacroError { + fn from(err: CurateMacroWriteError) -> Self { + Self::CurateWrite(err) + } +} + +impl From for RunCurateMacroError { + fn from(err: CurateMacroError) -> Self { + Self::CurateWrite(CurateMacroWriteError::Curate(err)) + } +} + +impl From for RunCurateMacroError { + fn from(err: ParquetMacroError) -> Self { + Self::CurateWrite(CurateMacroWriteError::Parquet(err)) + } +} + +#[inline] +fn parse_lag_class_token(token: &str) -> Option { + match token { + "policy_rate" => Some(MacroLagClass::PolicyRate), + "monthly_release" => Some(MacroLagClass::MonthlyRelease), + "gdp65" => Some(MacroLagClass::Gdp65), + "gdp90" => Some(MacroLagClass::Gdp90), + _ => None, + } +} + +#[inline] +fn is_structural_te_data_bson_error(err: &BsonTeDataError) -> bool { + matches!( + err, + BsonTeDataError::TruncatedDocument { .. } + | BsonTeDataError::CorruptDocumentLength { .. } + | BsonTeDataError::CorruptBson { .. } + | BsonTeDataError::CorruptPointBson { .. } + ) +} + +/// Parses and validates a caller-supplied macro series-map TSV into a [`MacroSeriesMap`]. +/// +/// Format: +/// - Line 1 must be the exact header +/// `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class`. +/// - Each subsequent line must have 6 nonempty tab-separated fields, preserved verbatim (no +/// trimming or case folding), with `lag_class` in +/// `{"policy_rate", "monthly_release", "gdp65", "gdp90"}` and unique +/// `(te_symbol, country, category)` keys. +pub fn load_macro_series_map_tsv( + reader: R, +) -> Result { + let mut buf_reader = BufReader::new(reader); + let mut raw_buf: Vec = Vec::with_capacity(256); + let mut line_no: usize = 0; + let mut map = MacroSeriesMap::default(); + let mut saw_header = false; + + loop { + raw_buf.clear(); + let bytes_read = buf_reader.read_until(b'\n', &mut raw_buf).map_err(|source| { + RunCurateMacroError::ReadInput { + role: ROLE_SERIES_MAP, + path: None, + source, + } + })?; + if bytes_read == 0 { + break; + } + line_no += 1; + + let mut slice = raw_buf.as_slice(); + if slice.ends_with(b"\n") { + slice = &slice[..slice.len() - 1]; + if slice.ends_with(b"\r") { + slice = &slice[..slice.len() - 1]; + } + } + if slice.contains(&b'\r') { + return Err(RunCurateMacroError::SeriesMapMalformedLine { + line: line_no, + detail: "unexpected carriage return inside TSV line", + }); + } + + let line = std::str::from_utf8(slice).map_err(|_| { + RunCurateMacroError::SeriesMapMalformedLine { + line: line_no, + detail: "invalid UTF-8 in TSV line", + } + })?; + + if !saw_header { + if line != MACRO_SERIES_MAP_HEADER { + return Err(RunCurateMacroError::SeriesMapBadHeader { + line: 1, + found: Some(line.to_owned()), + }); + } + saw_header = true; + continue; + } + + let cols: Vec<&str> = line.split('\t').collect(); + if cols.len() != SERIES_MAP_COLUMN_COUNT { + return Err(RunCurateMacroError::SeriesMapWrongColumnCount { + line: line_no, + expected: SERIES_MAP_COLUMN_COUNT, + actual: cols.len(), + }); + } + + for (idx, (&col, &col_name)) in cols.iter().zip(SERIES_MAP_COLUMNS.iter()).enumerate() { + let is_empty = if idx == 5 { + col.is_empty() + } else { + col.trim().is_empty() + }; + if is_empty { + return Err(RunCurateMacroError::SeriesMapEmptyField { + line: line_no, + column: col_name, + }); + } + } + + let te_symbol = cols[0]; + let country = cols[1]; + let category = cols[2]; + let country_iso = cols[3]; + let indicator = cols[4]; + let lag_token = cols[5]; + + let lag_class = parse_lag_class_token(lag_token).ok_or_else(|| { + RunCurateMacroError::SeriesMapUnknownLagClass { + line: line_no, + value: lag_token.to_owned(), + } + })?; + + let target = MacroSeriesTarget { + country_iso: country_iso.to_owned(), + indicator: indicator.to_owned(), + lag_class, + }; + + if !map.insert( + te_symbol.to_owned(), + country.to_owned(), + category.to_owned(), + target, + ) { + return Err(RunCurateMacroError::SeriesMapDuplicateKey { + line: line_no, + te_symbol: te_symbol.to_owned(), + country: country.to_owned(), + category: category.to_owned(), + }); + } + } + + if !saw_header { + return Err(RunCurateMacroError::SeriesMapBadHeader { + line: 1, + found: None, + }); + } + + Ok(map) +} + +/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and +/// the series-map TSV, publishing `/macro/part.parquet` via [`curate_and_write_macro`]. +/// +/// The series map is validated in full before `te_data` is decoded or `out_dir` is touched. Any +/// map, I/O, structural BSON, or curation error returns before publishing and leaves `out_dir` and +/// any pre-existing `/macro/part.parquet` untouched. +pub fn run_curate_macro_with_readers( + mut te_data: RT, + series_map: RM, + out_dir: &Path, +) -> Result { + let map = load_macro_series_map_tsv(series_map)?; + + let mut te_data_buf = Vec::new(); + te_data + .read_to_end(&mut te_data_buf) + .map_err(|source| RunCurateMacroError::ReadInput { + role: ROLE_TE_DATA, + path: None, + source, + })?; + + let mut points: Vec> = Vec::new(); + let mut structural_err: Option<(usize, BsonTeDataError)> = None; + let decode_stats = decode_te_data_buffer( + &te_data_buf, + |point| points.push(point), + |offset, err| { + if structural_err.is_none() && is_structural_te_data_bson_error(&err) { + structural_err = Some((offset, err)); + } + }, + ); + if let Some((offset, source)) = structural_err { + return Err(RunCurateMacroError::CorruptTeDataBson { + path: None, + offset, + source, + }); + } + + let write_report = curate_and_write_macro( + out_dir, + points, + |te_symbol, country, category| map.get(te_symbol, country, category).cloned(), + MacroWriteOptions::default(), + )?; + + Ok(CurateMacroRunReport { + series_map_entries: map.len(), + decode_stats, + curate_stats: write_report.curate_stats, + write_stats: write_report.write_stats, + }) +} + +/// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating +/// to [`run_curate_macro_with_readers`]. +/// +/// File open, read, and structural BSON errors attach the offending role (`te-data` or +/// `series-map`) and path. Any error returns before writing to `args.out_dir`. +pub fn run_curate_macro(args: &CurateMacroArgs) -> Result { + let series_map_file = + File::open(&args.series_map).map_err(|source| RunCurateMacroError::OpenInput { + role: ROLE_SERIES_MAP, + path: args.series_map.clone(), + source, + })?; + let te_data_file = + File::open(&args.te_data).map_err(|source| RunCurateMacroError::OpenInput { + role: ROLE_TE_DATA, + path: args.te_data.clone(), + source, + })?; + + run_curate_macro_with_readers(te_data_file, series_map_file, &args.out_dir) + .map_err(|err| err.with_input_paths(&args.te_data, &args.series_map)) +} + +/// Formats [`CurateMacroRunReport`] into deterministic multi-line `key=value` text. +pub fn format_curate_macro_report(report: &CurateMacroRunReport) -> String { + let d = &report.decode_stats; + let c = &report.curate_stats; + let b = &c.builder; + let w = &report.write_stats; + format!( + "curate-etl curate-macro\n\ + \x20 map: entries={}\n\ + \x20 decode: docs_in={} docs_accepted={} docs_rejected={} (missing_symbol={} empty_symbol={} wrong_symbol_type={} missing_country={} empty_country={} wrong_country_type={} missing_category={} empty_category={} wrong_category_type={} data_missing={} data_not_array={} corrupt_doc={}) points_in={} points_decoded={} points_rejected={} (not_doc={} invalid_date={} invalid_value={} corrupt_point={})\n\ + \x20 builder: input={} emitted={} skipped_unmapped_indicator={} skipped_non_finite_value={} skipped_duplicate={}\n\ + \x20 curate: points_in={} rows_out={} dropped_unmapped_series={} series_out={}\n\ + \x20 write: files={} row_groups={} rows_written={} bytes_written={}", + report.series_map_entries, + d.docs_in, + d.docs_accepted, + d.docs_rejected_total(), + d.rejected_missing_symbol, + d.rejected_empty_symbol, + d.rejected_wrong_symbol_type, + d.rejected_missing_country, + d.rejected_empty_country, + d.rejected_wrong_country_type, + d.rejected_missing_category, + d.rejected_empty_category, + d.rejected_wrong_category_type, + d.rejected_data_missing, + d.rejected_data_not_array, + d.rejected_corrupt_document, + d.points_in, + d.points_decoded, + d.rejected_total(), + d.rejected_point_not_document, + d.rejected_invalid_date, + d.rejected_invalid_value, + d.rejected_corrupt_point, + b.input, + b.emitted, + b.skipped_unmapped_indicator, + b.skipped_non_finite_value, + b.skipped_duplicate, + c.points_in, + c.rows_out, + c.dropped_unmapped_series, + c.series_out, + w.files_written, + w.row_groups_written, + w.rows_written, + w.bytes_written, + ) +} + +#[cfg(test)] +#[path = "run_curate_macro_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_macro_tests.rs b/tools/curate-etl/src/run_curate_macro_tests.rs new file mode 100644 index 00000000..1c7a691f --- /dev/null +++ b/tools/curate-etl/src/run_curate_macro_tests.rs @@ -0,0 +1,1047 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::io; +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::{ + format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro, + run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, RunCurateMacroError, + MACRO_SERIES_MAP_HEADER, +}; +use crate::bson_te_data::BsonTeDataError; +use crate::curate_macro::{CurateMacroError, CurateMacroWriteError, MacroSeriesTarget}; +use crate::macro_series::{ + MacroLagClass, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, + MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS, +}; +use crate::parquet_macro::{MacroParquetRow, 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-run-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); + } +} + +struct FailingReader { + message: &'static str, +} + +impl io::Read for FailingReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::other(self.message)) + } +} + +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 concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut buf = Vec::new(); + for doc in docs { + buf.extend_from_slice(doc.as_bytes()); + } + buf +} + +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_single_line(msg: &str) { + assert!( + !msg.contains('\n') && !msg.contains('\r'), + "expected single-line message without CR/LF, got: {msg:?}" + ); +} + +fn assert_report_conservation(report: &CurateMacroRunReport, parquet_rows: usize) { + let d = &report.decode_stats; + let c = &report.curate_stats; + let b = &c.builder; + let w = &report.write_stats; + + assert_eq!(d.docs_in, d.docs_accepted + d.docs_rejected_total()); + assert_eq!(d.points_in, d.points_decoded + d.rejected_total()); + assert_eq!(d.points_decoded, c.points_in); + assert_eq!(c.points_in, c.dropped_unmapped_series + b.input); + assert_eq!(c.rows_out, b.emitted); + assert_eq!(b.skipped_unmapped_indicator, 0); + assert_eq!( + b.input, + b.emitted + b.skipped_unmapped_indicator + b.skipped_non_finite_value + b.skipped_duplicate + ); + assert_eq!(c.rows_out, w.rows_written); + assert_eq!(w.rows_written, parquet_rows); +} + +fn seed_existing_parquet(out_dir: &Path) -> (PathBuf, Vec) { + let macro_dir = out_dir.join("macro"); + fs::create_dir_all(¯o_dir).expect("create macro dir"); + let part_path = macro_dir.join("part.parquet"); + let sentinel = b"PREEXISTING_MACRO_PARQUET_SENTINEL_BYTES_v1".to_vec(); + fs::write(&part_path, &sentinel).expect("write sentinel parquet"); + (part_path, sentinel) +} + +#[test] +fn end_to_end_pinned_fixture_curates_sorts_filters_and_conserves_stats() { + // Out-of-order BSON fixture with: + // - 2 mapped series with different lag classes (policy_rate +1d, monthly_release +35d), + // multiple out-of-order dates, a forecast sentinel, and 1 invalid point date + // - 1 unmapped series + // - 1 semantic document reject (missing `country`) + let mut cpi_doc = make_te_data_doc( + "USCPIYOY", + "United States", + "Inflation Rate", + &[ + ("2024-03-31", 3.5), + ("2024-02-30", 9.9), // invalid Gregorian date -> point reject + ("2024-01-31", 3.1), + ], + &[("2025-12-31", 999.0)], // forecast sentinel must never leak + ); + // Re-check doc is valid RawDocumentBuf + let _ = &mut cpi_doc; + + let rate_doc = make_te_data_doc( + "CABOC", + "Canada", + "Interest Rate", + &[("2024-04-10", 5.0), ("2024-01-24", 5.0)], + &[("2026-06-01", 888.0)], + ); + + let unmapped_doc = make_te_data_doc( + "UKPMI", + "United Kingdom", + "Manufacturing PMI", + &[("2024-03-31", 50.3)], + &[], + ); + + let mut bad_doc = RawDocumentBuf::new(); + bad_doc.append(cstr!("teSymbol"), "MISSING_COUNTRY"); + bad_doc.append(cstr!("category"), "Interest Rate"); + bad_doc.append(cstr!("data"), RawArrayBuf::new()); + + let bson_bytes = concat_docs(&[cpi_doc, unmapped_doc, bad_doc, rate_doc]); + + let series_map_tsv = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + CABOC\tCanada\tInterest Rate\tCA\tpolicy_rate\tpolicy_rate\n\ + USCPIYOY\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n" + ); + + let expected = vec![ + expected_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0), + expected_row("CA", "policy_rate", day(2024, 4, 10), 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, 3, 31), + MONTHLY_RELEASE_LAG_DAYS, + 3.5, + ), + ]; + + // Run 1 via readers + let out1 = TempDirGuard::new("e2e-run1"); + let report1 = run_curate_macro_with_readers( + bson_bytes.as_slice(), + series_map_tsv.as_bytes(), + out1.path(), + ) + .expect("run 1 should succeed"); + + let parquet_path1 = out1.path().join("macro").join("part.parquet"); + let rows1 = read_parquet_rows(&parquet_path1); + assert_rows_bitwise_eq(&rows1, &expected); + assert_report_conservation(&report1, rows1.len()); + + assert_eq!(report1.series_map_entries, 2); + assert_eq!(report1.decode_stats.docs_in, 4); + assert_eq!(report1.decode_stats.docs_accepted, 3); + assert_eq!(report1.decode_stats.rejected_missing_country, 1); + assert_eq!(report1.decode_stats.points_in, 6); + assert_eq!(report1.decode_stats.points_decoded, 5); + assert_eq!(report1.decode_stats.rejected_invalid_date, 1); + assert_eq!(report1.curate_stats.points_in, 5); + assert_eq!(report1.curate_stats.dropped_unmapped_series, 1); + assert_eq!(report1.curate_stats.rows_out, 4); + assert_eq!(report1.curate_stats.series_out, 2); + assert_eq!(report1.write_stats.files_written, 1); + + // Run 2 with identical inputs via readers -> reproducible logical rows and counters + let out2 = TempDirGuard::new("e2e-run2"); + let report2 = run_curate_macro_with_readers( + bson_bytes.as_slice(), + series_map_tsv.as_bytes(), + out2.path(), + ) + .expect("run 2 should succeed"); + let rows2 = read_parquet_rows(&out2.path().join("macro").join("part.parquet")); + assert_rows_bitwise_eq(&rows2, &rows1); + assert_eq!(report2, report1); + + // File-mode run_curate_macro matches reader-mode results + let file_dir = TempDirGuard::new("e2e-file"); + let te_data_path = file_dir.path().join("teData.bson"); + let map_path = file_dir.path().join("series_map.tsv"); + let file_out = file_dir.path().join("out"); + fs::write(&te_data_path, &bson_bytes).expect("write bson fixture"); + fs::write(&map_path, &series_map_tsv).expect("write tsv fixture"); + + let file_report = run_curate_macro(&CurateMacroArgs { + te_data: te_data_path, + series_map: map_path, + out_dir: file_out.clone(), + }) + .expect("file-mode run should succeed"); + let file_rows = read_parquet_rows(&file_out.join("macro").join("part.parquet")); + assert_rows_bitwise_eq(&file_rows, &rows1); + assert_eq!(file_report, report1); +} + +#[test] +fn tsv_loader_accepts_all_four_lag_classes_and_preserves_verbatim_keys_and_crlf() { + let tsv = format!( + "{MACRO_SERIES_MAP_HEADER}\r\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\r\n\ + USCPI\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n\ + USGDP\tUnited States\tGDP Growth Rate\tUS\tgdp_qoq\tgdp65\r\n\ + \x20CAGDP \tcanada\tGDP Annual\tCA\tgdp_yoy\tgdp90" + ); + + let map = load_macro_series_map_tsv(tsv.as_bytes()).expect("valid TSV should parse"); + assert_eq!(map.len(), 4); + assert!(!map.is_empty()); + + assert_eq!( + map.get("FDTR", "United States", "Interest Rate"), + Some(&MacroSeriesTarget { + country_iso: "US".to_owned(), + indicator: "policy_rate".to_owned(), + lag_class: MacroLagClass::PolicyRate, + }) + ); + assert_eq!( + map.get("USCPI", "United States", "Inflation Rate"), + Some(&MacroSeriesTarget { + country_iso: "US".to_owned(), + indicator: "cpi_yoy".to_owned(), + lag_class: MacroLagClass::MonthlyRelease, + }) + ); + assert_eq!( + map.get("USGDP", "United States", "GDP Growth Rate"), + Some(&MacroSeriesTarget { + country_iso: "US".to_owned(), + indicator: "gdp_qoq".to_owned(), + lag_class: MacroLagClass::Gdp65, + }) + ); + assert_eq!( + map.get(" CAGDP ", "canada", "GDP Annual"), + Some(&MacroSeriesTarget { + country_iso: "CA".to_owned(), + indicator: "gdp_yoy".to_owned(), + lag_class: MacroLagClass::Gdp90, + }) + ); + + // Verbatim key checks: no trimming, no case folding + assert_eq!(map.get("CAGDP", "canada", "GDP Annual"), None); + assert_eq!(map.get(" CAGDP ", "Canada", "GDP Annual"), None); + assert_eq!(map.get("fdtr", "United States", "Interest Rate"), None); + assert_eq!(MacroLagClass::Gdp65.lag_days(), GDP65_LAG_DAYS); + assert_eq!(MacroLagClass::Gdp90.lag_days(), GDP90_LAG_DAYS); +} + +#[test] +fn tsv_loader_rejects_bad_headers_wrong_columns_empty_fields_unknown_lag_and_duplicates() { + // 1. Empty input -> missing header at line 1 + let err = load_macro_series_map_tsv(&b""[..]).expect_err("empty TSV must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapBadHeader { + line: 1, + found: None + } + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 1"), "msg: {msg}"); + + // 2. Wrong header at line 1 + let err = load_macro_series_map_tsv( + b"te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag\n".as_slice(), + ) + .expect_err("wrong header must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapBadHeader { + line: 1, + found: Some(_) + } + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 1"), "msg: {msg}"); + + // 3. Wrong column count (too few on line 2, too many on line 3, blank line on line 3) + let too_few = format!("{MACRO_SERIES_MAP_HEADER}\nFDTR\tUS\tRate\tUS\tpolicy_rate\n"); + let err = load_macro_series_map_tsv(too_few.as_bytes()).expect_err("5 cols must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapWrongColumnCount { + line: 2, + expected: 6, + actual: 5 + } + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 2"), "msg: {msg}"); + + let too_many = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ + A\tB\tC\tD\tE\tpolicy_rate\textra\n" + ); + let err = load_macro_series_map_tsv(too_many.as_bytes()).expect_err("7 cols must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapWrongColumnCount { + line: 3, + expected: 6, + actual: 7 + } + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 3"), "msg: {msg}"); + + let blank_line = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ + \n" + ); + let err = load_macro_series_map_tsv(blank_line.as_bytes()).expect_err("blank line must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapWrongColumnCount { + line: 3, + expected: 6, + actual: 1 + } + )); + assert_single_line(&err.to_string()); + + // 4. Empty field in each column position + let empty_cases = [ + ("\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate", "te_symbol"), + ("FDTR\t\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate", "country"), + ("FDTR\tUnited States\t\tUS\tpolicy_rate\tpolicy_rate", "category"), + ("FDTR\tUnited States\tInterest Rate\t\tpolicy_rate\tpolicy_rate", "country_iso"), + ("FDTR\tUnited States\tInterest Rate\tUS\t\tpolicy_rate", "indicator"), + ("FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\t", "lag_class"), + (" \tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate", "te_symbol"), + ]; + for (row, expected_col) in empty_cases { + let input = format!("{MACRO_SERIES_MAP_HEADER}\n{row}\n"); + let err = load_macro_series_map_tsv(input.as_bytes()) + .expect_err("empty field must fail"); + assert!( + matches!( + err, + RunCurateMacroError::SeriesMapEmptyField { line: 2, column } + if column == expected_col + ), + "unexpected error for {expected_col}: {err:?}" + ); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 2"), "msg: {msg}"); + } + + // 5. Unknown or whitespace-padded lag_class + for bad_lag in ["unknown", "PolicyRate", " policy_rate", "gdp65 ", "gdp30"] { + let input = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\t{bad_lag}\n" + ); + let err = load_macro_series_map_tsv(input.as_bytes()) + .expect_err("unknown lag_class must fail"); + assert!( + matches!( + &err, + RunCurateMacroError::SeriesMapUnknownLagClass { line: 2, value } + if value == bad_lag + ), + "unexpected error for lag_class {bad_lag:?}: {err:?}" + ); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 2"), "msg: {msg}"); + } + + // 6. Duplicate key triple (even when target is identical) + let dup_identical = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" + ); + let err = load_macro_series_map_tsv(dup_identical.as_bytes()) + .expect_err("identical duplicate key must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapDuplicateKey { line: 3, .. } + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("line 3"), "msg: {msg}"); + + // 7. Bare CR and invalid UTF-8 + let bare_cr = format!("{MACRO_SERIES_MAP_HEADER}\nFDTR\tUS\rX\tRate\tUS\tind\tpolicy_rate\n"); + let err = load_macro_series_map_tsv(bare_cr.as_bytes()).expect_err("bare CR must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapMalformedLine { line: 2, .. } + )); + assert_single_line(&err.to_string()); + + let mut invalid_utf8 = format!("{MACRO_SERIES_MAP_HEADER}\n").into_bytes(); + invalid_utf8.extend_from_slice(&[0xff, 0xfe, b'\n']); + let err = load_macro_series_map_tsv(invalid_utf8.as_slice()).expect_err("bad UTF-8 must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapMalformedLine { line: 2, .. } + )); + assert_single_line(&err.to_string()); +} + +#[test] +fn invalid_map_conflicting_lag_class_and_corrupt_bson_leave_outputs_untouched() { + let valid_doc = make_te_data_doc( + "FDTR", + "United States", + "Interest Rate", + &[("2024-03-20", 5.5)], + &[], + ); + let second_doc = make_te_data_doc( + "FDTR_ALT", + "United States", + "Fed Funds", + &[("2024-03-21", 5.5)], + &[], + ); + + // Case A: Invalid series map + let bad_map = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tnot_a_lag\n" + ); + for seeded in [false, true] { + let out = TempDirGuard::new("fail-bad-map"); + let existing = seeded.then(|| seed_existing_parquet(out.path())); + + let err = run_curate_macro_with_readers(valid_doc.as_bytes(), bad_map.as_bytes(), out.path()) + .expect_err("invalid map must fail"); + assert!(matches!( + err, + RunCurateMacroError::SeriesMapUnknownLagClass { line: 2, .. } + )); + assert_single_line(&err.to_string()); + + if let Some((part_path, sentinel)) = existing { + assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); + } else { + assert!(!out.path().join("macro").exists()); + } + } + + // Case B: ConflictingLagClass across two mapped series targeting the same (country_iso, indicator) + let conflict_bson = concat_docs(&[valid_doc.clone(), second_doc]); + let conflict_map = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\ + FDTR_ALT\tUnited States\tFed Funds\tUS\tpolicy_rate\tmonthly_release\n" + ); + for seeded in [false, true] { + let out = TempDirGuard::new("fail-conflict-lag"); + let existing = seeded.then(|| seed_existing_parquet(out.path())); + + let err = run_curate_macro_with_readers( + conflict_bson.as_slice(), + conflict_map.as_bytes(), + out.path(), + ) + .expect_err("conflicting lag class must fail"); + assert!(matches!( + err, + RunCurateMacroError::CurateWrite(CurateMacroWriteError::Curate( + CurateMacroError::ConflictingLagClass { .. } + )) + )); + assert_single_line(&err.to_string()); + + if let Some((part_path, sentinel)) = existing { + assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); + } else { + assert!(!out.path().join("macro").exists()); + } + } + + // Case C: Valid BSON prefix followed by a truncated BSON tail + let valid_map = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" + ); + let mut truncated_bson = valid_doc.as_bytes().to_vec(); + let corrupt_offset = truncated_bson.len(); + // Append a 4-byte length declaring 64 bytes with only 2 trailing bytes present + truncated_bson.extend_from_slice(&64_i32.to_le_bytes()); + truncated_bson.extend_from_slice(&[0x01, 0x02]); + + for seeded in [false, true] { + let out = TempDirGuard::new("fail-truncated-bson"); + let existing = seeded.then(|| seed_existing_parquet(out.path())); + + let err = run_curate_macro_with_readers( + truncated_bson.as_slice(), + valid_map.as_bytes(), + out.path(), + ) + .expect_err("truncated BSON tail must fail"); + assert!(matches!( + err, + RunCurateMacroError::CorruptTeDataBson { + path: None, + offset, + source: BsonTeDataError::TruncatedDocument { .. } + } if offset == corrupt_offset + )); + assert_single_line(&err.to_string()); + + if let Some((part_path, sentinel)) = existing { + assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); + } else { + assert!(!out.path().join("macro").exists()); + } + } +} + +#[test] +fn empty_and_all_unmapped_inputs_preserve_zero_row_noop() { + let header_only_map = format!("{MACRO_SERIES_MAP_HEADER}\n"); + let unmapped_doc = make_te_data_doc( + "UNMAPPED", + "Canada", + "CPI", + &[("2024-03-31", 2.9)], + &[], + ); + + for (label, bson_bytes, expected_dropped) in [ + ("empty-bson", Vec::new(), 0usize), + ("all-unmapped", unmapped_doc.as_bytes().to_vec(), 1usize), + ] { + for seeded in [false, true] { + let out = TempDirGuard::new(label); + let existing = seeded.then(|| seed_existing_parquet(out.path())); + + let report = run_curate_macro_with_readers( + bson_bytes.as_slice(), + header_only_map.as_bytes(), + out.path(), + ) + .expect("zero-row input should succeed"); + + assert_eq!(report.series_map_entries, 0); + assert_eq!(report.curate_stats.dropped_unmapped_series, expected_dropped); + assert_eq!(report.curate_stats.rows_out, 0); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert_report_conservation(&report, 0); + + if let Some((part_path, sentinel)) = existing { + assert_eq!(fs::read(&part_path).expect("read sentinel"), sentinel); + } else { + assert!(!out.path().join("macro").exists()); + } + } + } +} + +#[test] +fn missing_file_paths_and_reader_io_errors_report_role_and_path_without_writing() { + let dir = TempDirGuard::new("io-errors"); + let valid_map_path = dir.path().join("series_map.tsv"); + let valid_bson_path = dir.path().join("teData.bson"); + fs::write(&valid_map_path, format!("{MACRO_SERIES_MAP_HEADER}\n")).expect("write map"); + fs::write(&valid_bson_path, b"").expect("write bson"); + + // 1. Missing te_data with series_map present + let missing_te_data = dir.path().join("does-not-exist-teData.bson"); + let out1 = dir.path().join("out1"); + let err = run_curate_macro(&CurateMacroArgs { + te_data: missing_te_data.clone(), + series_map: valid_map_path.clone(), + out_dir: out1.clone(), + }) + .expect_err("missing te_data must fail"); + assert!(matches!( + &err, + RunCurateMacroError::OpenInput { + role: "te-data", + path, + .. + } if path == &missing_te_data + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("te-data"), "msg: {msg}"); + assert!( + msg.contains(&missing_te_data.display().to_string()), + "msg: {msg}" + ); + assert!(!out1.exists()); + + // 2. Missing series_map with te_data present + let missing_map = dir.path().join("does-not-exist-series-map.tsv"); + let out2 = dir.path().join("out2"); + let err = run_curate_macro(&CurateMacroArgs { + te_data: valid_bson_path, + series_map: missing_map.clone(), + out_dir: out2.clone(), + }) + .expect_err("missing series_map must fail"); + assert!(matches!( + &err, + RunCurateMacroError::OpenInput { + role: "series-map", + path, + .. + } if path == &missing_map + )); + let msg = err.to_string(); + assert_single_line(&msg); + assert!(msg.contains("series-map"), "msg: {msg}"); + assert!( + msg.contains(&missing_map.display().to_string()), + "msg: {msg}" + ); + assert!(!out2.exists()); + + // 3. Reader I/O failures in reader mode + let out3 = dir.path().join("out3"); + let err = run_curate_macro_with_readers( + &b""[..], + FailingReader { + message: "map read boom\nline2", + }, + &out3, + ) + .expect_err("failing series_map reader must fail"); + assert!(matches!( + err, + RunCurateMacroError::ReadInput { + role: "series-map", + path: None, + .. + } + )); + assert_single_line(&err.to_string()); + assert!(!out3.exists()); + + let err = run_curate_macro_with_readers( + FailingReader { + message: "bson read boom\r\nline2", + }, + format!("{MACRO_SERIES_MAP_HEADER}\n").as_bytes(), + &out3, + ) + .expect_err("failing te_data reader must fail"); + assert!(matches!( + err, + RunCurateMacroError::ReadInput { + role: "te-data", + path: None, + .. + } + )); + assert_single_line(&err.to_string()); + assert!(!out3.exists()); +} + +#[test] +fn report_formatting_is_deterministic_and_all_error_variants_are_single_line() { + let doc = make_te_data_doc( + "FDTR", + "United States", + "Interest Rate", + &[("2024-03-20", 5.5)], + &[], + ); + let map = format!( + "{MACRO_SERIES_MAP_HEADER}\n\ + FDTR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n" + ); + let out = TempDirGuard::new("report-format"); + let report = run_curate_macro_with_readers(doc.as_bytes(), map.as_bytes(), out.path()) + .expect("run should succeed"); + + let formatted_a = format_curate_macro_report(&report); + let formatted_b = format_curate_macro_report(&report); + assert_eq!(formatted_a, formatted_b); + let lines: Vec<&str> = formatted_a.lines().collect(); + assert_eq!(lines.len(), 6); + assert_eq!(lines[0], "curate-etl curate-macro"); + assert!(lines[1].contains("map:") && lines[1].contains("entries=1")); + assert!( + lines[2].contains("decode:") + && lines[2].contains("docs_in=1") + && lines[2].contains("points_decoded=1") + ); + assert!( + lines[3].contains("builder:") + && lines[3].contains("input=1") + && lines[3].contains("emitted=1") + ); + assert!( + lines[4].contains("curate:") + && lines[4].contains("points_in=1") + && lines[4].contains("rows_out=1") + && lines[4].contains("dropped_unmapped_series=0") + && lines[4].contains("series_out=1") + ); + assert!( + lines[5].contains("write:") + && lines[5].contains("files=1") + && lines[5].contains("rows_written=1") + ); + + // Exhaustive single-line Display + Error::source check across every RunCurateMacroError variant + let adversarial_path = PathBuf::from("dir/bad\npath\rname"); + let variants: Vec<(RunCurateMacroError, bool)> = vec![ + ( + RunCurateMacroError::OpenInput { + role: "te-data", + path: adversarial_path.clone(), + source: io::Error::other("open\nerr\rdetail"), + }, + true, + ), + ( + RunCurateMacroError::ReadInput { + role: "series-map", + path: Some(adversarial_path.clone()), + source: io::Error::other("read\nerr\rdetail"), + }, + true, + ), + ( + RunCurateMacroError::ReadInput { + role: "te-data", + path: None, + source: io::Error::other("read\nno-path"), + }, + true, + ), + ( + RunCurateMacroError::SeriesMapMalformedLine { + line: 4, + detail: "invalid UTF-8 in TSV line", + }, + false, + ), + ( + RunCurateMacroError::SeriesMapBadHeader { + line: 1, + found: Some("bad\nheader\r".to_owned()), + }, + false, + ), + ( + RunCurateMacroError::SeriesMapBadHeader { + line: 1, + found: None, + }, + false, + ), + ( + RunCurateMacroError::SeriesMapWrongColumnCount { + line: 2, + expected: 6, + actual: 3, + }, + false, + ), + ( + RunCurateMacroError::SeriesMapEmptyField { + line: 3, + column: "indicator", + }, + false, + ), + ( + RunCurateMacroError::SeriesMapUnknownLagClass { + line: 5, + value: "bad\nlag\r".to_owned(), + }, + false, + ), + ( + RunCurateMacroError::SeriesMapDuplicateKey { + line: 6, + te_symbol: "SYM\n1".to_owned(), + country: "US\r".to_owned(), + category: "CPI\n".to_owned(), + }, + false, + ), + ( + RunCurateMacroError::CorruptTeDataBson { + path: Some(adversarial_path), + offset: 42, + source: BsonTeDataError::CorruptBson { + offset: 42, + detail: "bad\nbson\rbytes".to_owned(), + }, + }, + true, + ), + ( + RunCurateMacroError::from(CurateMacroError::ConflictingLagClass { + country_iso: "US\n".to_owned(), + indicator: "cpi\r".to_owned(), + first_lag_class: MacroLagClass::PolicyRate, + second_lag_class: MacroLagClass::MonthlyRelease, + }), + true, + ), + ( + RunCurateMacroError::from(ParquetMacroError::InvalidRowGroupRows), + true, + ), + ]; + + for (err, expect_source) in &variants { + let msg = err.to_string(); + assert!(!msg.is_empty()); + assert_single_line(&msg); + assert_eq!(err.source().is_some(), *expect_source, "source for {err:?}"); + } +}