T-199: M2.2s — tools/curate-etl: file-mode run_curate_macro runner (teData BSON dump + caller-supplied series-map TSV → curate_and_write_macro → macro/part.parquet) in run_curate_macro.rs with lib tests (no new crates, no CLI/bench changes, no live Mongo)

This commit is contained in:
Studio 2026-12-03 14:50:00 -05:00
parent 2a7485a15c
commit fc2312ebeb
4 changed files with 1720 additions and 1 deletions

View file

@ -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<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.
- **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: 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<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.
## `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 `<out_dir>/macro/part.parquet`:
- **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbol<TAB>country<TAB>category<TAB>country_iso<TAB>indicator<TAB>lag_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 `<out_dir>/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.

View file

@ -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,

View file

@ -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 `<out_dir>/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 `<out_dir>/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<String, BTreeMap<String, BTreeMap<String, MacroSeriesTarget>>>,
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<PathBuf>,
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<String> },
/// 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<PathBuf>,
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<CurateMacroWriteError> for RunCurateMacroError {
fn from(err: CurateMacroWriteError) -> Self {
Self::CurateWrite(err)
}
}
impl From<CurateMacroError> for RunCurateMacroError {
fn from(err: CurateMacroError) -> Self {
Self::CurateWrite(CurateMacroWriteError::Curate(err))
}
}
impl From<ParquetMacroError> for RunCurateMacroError {
fn from(err: ParquetMacroError) -> Self {
Self::CurateWrite(CurateMacroWriteError::Parquet(err))
}
}
#[inline]
fn parse_lag_class_token(token: &str) -> Option<MacroLagClass> {
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<R: io::Read>(
reader: R,
) -> Result<MacroSeriesMap, RunCurateMacroError> {
let mut buf_reader = BufReader::new(reader);
let mut raw_buf: Vec<u8> = 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 `<out_dir>/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 `<out_dir>/macro/part.parquet` untouched.
pub fn run_curate_macro_with_readers<RT: io::Read, RM: io::Read>(
mut te_data: RT,
series_map: RM,
out_dir: &Path,
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
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<TeDataPoint<'_>> = 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<CurateMacroRunReport, RunCurateMacroError> {
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;

File diff suppressed because it is too large Load diff