T-176: M2.2q — tools/curate-etl: pure macro curation stage (TeDataPoint + caller-supplied series map → build_macro_rows → MacroParquetRows → macro/part.parquet) in curate_macro.rs with tests (no new crates, no CLI/bench/stream changes, no live Mongo)
This commit is contained in:
parent
c73e6b72aa
commit
193798f8b0
4 changed files with 1430 additions and 1 deletions
|
|
@ -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<K>>`) atomically to `<out_dir>/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<K>>`) atomically to `<out_dir>/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 `<out_dir>/macro/part.parquet`:
|
||||
|
||||
- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option<MacroSeriesTarget { country_iso, indicator, lag_class }>`; 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 `<out_dir>/macro/part.parquet` untouched on empty/all-unmapped input or any curation error.
|
||||
|
|
|
|||
347
tools/curate-etl/src/curate_macro.rs
Normal file
347
tools/curate-etl/src/curate_macro.rs
Normal file
|
|
@ -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<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;
|
||||
1069
tools/curate-etl/src/curate_macro_tests.rs
Normal file
1069
tools/curate-etl/src/curate_macro_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue