347 lines
12 KiB
Rust
347 lines
12 KiB
Rust
//! 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<MacroParquetRow>,
|
|
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<String>),
|
|
}
|
|
|
|
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<MacroError<String>> for CurateMacroError {
|
|
fn from(err: MacroError<String>) -> 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<CurateMacroError> for CurateMacroWriteError {
|
|
fn from(err: CurateMacroError) -> Self {
|
|
Self::Curate(err)
|
|
}
|
|
}
|
|
|
|
impl From<ParquetMacroError> 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<MacroLagClass> {
|
|
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<MacroSeriesTarget>` 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<CurateMacroOutput, CurateMacroError>
|
|
where
|
|
I: IntoIterator<Item = TeDataPoint<'a>>,
|
|
F: Fn(&str, &str, &str) -> Option<MacroSeriesTarget>,
|
|
{
|
|
let iter = points.into_iter();
|
|
let (lower, _) = iter.size_hint();
|
|
let mut stats = CurateMacroStats::default();
|
|
let mut observations: Vec<MacroObservation<String>> = Vec::with_capacity(lower);
|
|
let mut target_lags: BTreeMap<String, BTreeMap<String, LagAssignment>> = 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<MacroParquetRow> = 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 `<out_dir>/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<CurateMacroWriteReport, CurateMacroWriteError>
|
|
where
|
|
P: AsRef<Path>,
|
|
I: IntoIterator<Item = TeDataPoint<'a>>,
|
|
F: Fn(&str, &str, &str) -> Option<MacroSeriesTarget>,
|
|
{
|
|
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;
|