1564 lines
51 KiB
Rust
1564 lines
51 KiB
Rust
use std::borrow::Cow;
|
|
use std::error::Error as StdError;
|
|
use std::fs::{self, File};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
|
|
|
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
|
use bson::DateTime;
|
|
use parquet::column::reader::ColumnReader;
|
|
use parquet::file::reader::{FileReader, SerializedFileReader};
|
|
|
|
use super::{
|
|
curate_and_write_macro, curate_macro, CurateMacroError, CurateMacroStats,
|
|
CurateMacroWriteError, MacroSeriesTarget,
|
|
};
|
|
use crate::bson_te_data::{decode_te_data_doc, TeDataPoint};
|
|
use crate::macro_series::{
|
|
MacroError, MacroLagClass, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE,
|
|
MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS,
|
|
};
|
|
use crate::parquet_macro::{
|
|
write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, ParquetMacroError,
|
|
};
|
|
use crate::split::ymd_to_epoch_days;
|
|
|
|
const MICROS_PER_DAY: i64 = 86_400_000_000;
|
|
|
|
static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
|
|
|
struct TempDirGuard {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl TempDirGuard {
|
|
fn new(label: &str) -> Self {
|
|
let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed);
|
|
let pid = std::process::id();
|
|
let path =
|
|
std::env::temp_dir().join(format!("curate-etl-curate-macro-test-{label}-{pid}-{seq}"));
|
|
let _ = fs::remove_dir_all(&path);
|
|
fs::create_dir_all(&path).expect("create test temp dir");
|
|
Self { path }
|
|
}
|
|
|
|
fn path(&self) -> &Path {
|
|
&self.path
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDirGuard {
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
fn day(y: i32, m: u32, d: u32) -> i32 {
|
|
ymd_to_epoch_days(y, m, d).expect("valid date")
|
|
}
|
|
|
|
fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf {
|
|
let mut pt = RawDocumentBuf::new();
|
|
pt.append(cstr!("d"), d);
|
|
pt.append(cstr!("v"), v);
|
|
pt
|
|
}
|
|
|
|
fn make_te_data_doc(
|
|
te_symbol: &str,
|
|
country: &str,
|
|
category: &str,
|
|
data_points: &[(&str, f64)],
|
|
forecast_points: &[(&str, f64)],
|
|
) -> RawDocumentBuf {
|
|
let mut data_arr = RawArrayBuf::new();
|
|
for &(d, v) in data_points {
|
|
data_arr.push(make_point_doc(d, v));
|
|
}
|
|
|
|
let mut forecast_arr = RawArrayBuf::new();
|
|
for &(d, v) in forecast_points {
|
|
forecast_arr.push(make_point_doc(d, v));
|
|
}
|
|
|
|
let mut doc = RawDocumentBuf::new();
|
|
doc.append(cstr!("teSymbol"), te_symbol);
|
|
doc.append(cstr!("name"), format!("{country} {category}"));
|
|
doc.append(cstr!("unit"), "percent");
|
|
doc.append(cstr!("source"), "TradingEconomics");
|
|
doc.append(cstr!("frequency"), "Monthly");
|
|
doc.append(cstr!("country"), country);
|
|
doc.append(cstr!("category"), category);
|
|
doc.append(cstr!("data"), data_arr);
|
|
doc.append(cstr!("forecast"), forecast_arr);
|
|
doc.append(
|
|
cstr!("lastUpdated"),
|
|
DateTime::from_millis(1_710_000_000_000),
|
|
);
|
|
doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000));
|
|
doc
|
|
}
|
|
|
|
fn target(country_iso: &str, indicator: &str, lag_class: MacroLagClass) -> MacroSeriesTarget {
|
|
MacroSeriesTarget {
|
|
country_iso: country_iso.to_owned(),
|
|
indicator: indicator.to_owned(),
|
|
lag_class,
|
|
}
|
|
}
|
|
|
|
fn expected_row(
|
|
country_iso: &'static str,
|
|
indicator: &'static str,
|
|
period_date: i32,
|
|
lag_days: i32,
|
|
value: f64,
|
|
) -> MacroParquetRow {
|
|
MacroParquetRow {
|
|
country_iso: Cow::Borrowed(country_iso),
|
|
indicator: Cow::Borrowed(indicator),
|
|
period_date,
|
|
known_at_micros: i64::from(period_date + lag_days) * MICROS_PER_DAY,
|
|
known_at_source: Cow::Borrowed(MACRO_KNOWN_AT_SOURCE),
|
|
value,
|
|
}
|
|
}
|
|
|
|
fn read_parquet_rows(path: &Path) -> Vec<MacroParquetRow> {
|
|
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<i32> {
|
|
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<i64> {
|
|
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<f64> {
|
|
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<String> {
|
|
let mut vals = Vec::with_capacity(num_rows);
|
|
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
|
ColumnReader::ByteArrayColumnReader(mut r) => {
|
|
let (read, _, _) = r
|
|
.read_records(num_rows, None, None, &mut vals)
|
|
.expect("read utf8");
|
|
assert_eq!(read, num_rows);
|
|
}
|
|
_ => panic!("expected BYTE_ARRAY column at index {col_idx}"),
|
|
}
|
|
vals.into_iter()
|
|
.map(|b| {
|
|
std::str::from_utf8(b.data())
|
|
.expect("valid utf8")
|
|
.to_owned()
|
|
})
|
|
.collect()
|
|
};
|
|
|
|
let country_iso = read_str(0);
|
|
let indicator = read_str(1);
|
|
let period_date = read_i32(2);
|
|
let known_at_micros = read_i64(3);
|
|
let known_at_source = read_str(4);
|
|
let value = read_f64(5);
|
|
|
|
for i in 0..num_rows {
|
|
out.push(MacroParquetRow {
|
|
country_iso: Cow::Owned(country_iso[i].clone()),
|
|
indicator: Cow::Owned(indicator[i].clone()),
|
|
period_date: period_date[i],
|
|
known_at_micros: known_at_micros[i],
|
|
known_at_source: Cow::Owned(known_at_source[i].clone()),
|
|
value: value[i],
|
|
});
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn assert_rows_bitwise_eq(actual: &[MacroParquetRow], expected: &[MacroParquetRow]) {
|
|
assert_eq!(actual.len(), expected.len(), "row count mismatch");
|
|
for (idx, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
|
|
assert_eq!(a.country_iso, e.country_iso, "row {idx} country_iso");
|
|
assert_eq!(a.indicator, e.indicator, "row {idx} indicator");
|
|
assert_eq!(a.period_date, e.period_date, "row {idx} period_date");
|
|
assert_eq!(
|
|
a.known_at_micros, e.known_at_micros,
|
|
"row {idx} known_at_micros"
|
|
);
|
|
assert_eq!(
|
|
a.known_at_source, e.known_at_source,
|
|
"row {idx} known_at_source"
|
|
);
|
|
assert_eq!(
|
|
a.value.to_bits(),
|
|
e.value.to_bits(),
|
|
"row {idx} value bits ({} vs {})",
|
|
a.value,
|
|
e.value
|
|
);
|
|
}
|
|
}
|
|
|
|
fn assert_strictly_ascending_unique(rows: &[MacroParquetRow]) {
|
|
for pair in rows.windows(2) {
|
|
let prev = (
|
|
pair[0].country_iso.as_ref(),
|
|
pair[0].indicator.as_ref(),
|
|
pair[0].period_date,
|
|
);
|
|
let next = (
|
|
pair[1].country_iso.as_ref(),
|
|
pair[1].indicator.as_ref(),
|
|
pair[1].period_date,
|
|
);
|
|
assert!(
|
|
prev < next,
|
|
"rows not strictly ascending and unique: {prev:?} >= {next:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
fn assert_stats_conserved(stats: &CurateMacroStats) {
|
|
assert_eq!(
|
|
stats.points_in,
|
|
stats.dropped_unmapped_series + stats.builder.input,
|
|
"stage input conservation failed: {stats:?}"
|
|
);
|
|
assert_eq!(
|
|
stats.rows_out, stats.builder.emitted,
|
|
"stage output conservation failed: {stats:?}"
|
|
);
|
|
assert_eq!(
|
|
stats.builder.skipped_unmapped_indicator, 0,
|
|
"builder should never observe unmapped indicators from stage: {stats:?}"
|
|
);
|
|
assert_eq!(
|
|
stats.builder.input,
|
|
stats.builder.emitted
|
|
+ stats.builder.skipped_unmapped_indicator
|
|
+ stats.builder.skipped_non_finite_value
|
|
+ stats.builder.skipped_duplicate,
|
|
"builder conservation failed: {stats:?}"
|
|
);
|
|
}
|
|
|
|
fn sorted_dir_entries(dir: &Path) -> Vec<String> {
|
|
if !dir.exists() {
|
|
return Vec::new();
|
|
}
|
|
let mut entries: Vec<String> = fs::read_dir(dir)
|
|
.expect("read dir")
|
|
.map(|entry| {
|
|
entry
|
|
.expect("dir entry")
|
|
.file_name()
|
|
.to_string_lossy()
|
|
.into_owned()
|
|
})
|
|
.collect();
|
|
entries.sort();
|
|
entries
|
|
}
|
|
|
|
fn seed_existing_parquet(out_dir: &Path) -> (PathBuf, Vec<u8>, Vec<String>) {
|
|
let seed = vec![
|
|
expected_row(
|
|
"CA",
|
|
"policy_rate",
|
|
day(2024, 1, 24),
|
|
POLICY_RATE_LAG_DAYS,
|
|
5.0,
|
|
),
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 1, 31),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.1,
|
|
),
|
|
];
|
|
write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).expect("seed parquet");
|
|
let part = out_dir.join("macro/part.parquet");
|
|
let bytes = fs::read(&part).expect("read seeded parquet");
|
|
let entries = sorted_dir_entries(&out_dir.join("macro"));
|
|
(part, bytes, entries)
|
|
}
|
|
|
|
#[test]
|
|
fn decode_te_data_bson_curate_and_write_all_four_lag_classes_without_forecast_leakage() {
|
|
let docs = vec![
|
|
make_te_data_doc(
|
|
"USGDPQOQ",
|
|
"United States",
|
|
"GDP Growth Rate",
|
|
&[("2024-03-31", 1.4), ("2024-06-30", -0.0)],
|
|
&[("2025-12-31", 99.9)],
|
|
),
|
|
make_te_data_doc(
|
|
"CAGDPQOQ",
|
|
"Canada",
|
|
"GDP Growth Rate",
|
|
&[("2024-03-31", -0.25)],
|
|
&[("2026-03-31", 88.8)],
|
|
),
|
|
make_te_data_doc(
|
|
"USCPIYOY",
|
|
"United States",
|
|
"Inflation Rate",
|
|
&[("2024-02-29", 3.2), ("2024-01-31", 3.1)],
|
|
&[("2025-06-30", 77.7)],
|
|
),
|
|
make_te_data_doc(
|
|
"CABOCRATE",
|
|
"Canada",
|
|
"Interest Rate",
|
|
&[("2024-01-24", 5.0), ("2024-06-05", 0.0)],
|
|
&[("2025-09-30", 66.6)],
|
|
),
|
|
make_te_data_doc(
|
|
"UKUNEMP",
|
|
"United Kingdom",
|
|
"Unemployment Rate",
|
|
&[("2024-01-31", 4.2)],
|
|
&[("2025-10-31", 55.5)],
|
|
),
|
|
];
|
|
|
|
let mut decoded_points: Vec<TeDataPoint<'_>> = Vec::new();
|
|
let mut decode_errors = Vec::new();
|
|
let mut total_points_in = 0usize;
|
|
let mut total_points_decoded = 0usize;
|
|
for doc in &docs {
|
|
let stats = decode_te_data_doc(
|
|
doc.as_ref(),
|
|
|pt| decoded_points.push(pt),
|
|
|err| decode_errors.push(err),
|
|
);
|
|
assert_eq!(stats.docs_accepted, 1);
|
|
assert_eq!(stats.docs_rejected_total(), 0);
|
|
assert_eq!(stats.rejected_total(), 0);
|
|
total_points_in += stats.points_in;
|
|
total_points_decoded += stats.points_decoded;
|
|
}
|
|
assert!(
|
|
decode_errors.is_empty(),
|
|
"unexpected decode errors: {decode_errors:?}"
|
|
);
|
|
// Only the 8 historical data points were decoded; none of the 5 forecast points leaked.
|
|
assert_eq!(total_points_in, 8);
|
|
assert_eq!(total_points_decoded, 8);
|
|
assert_eq!(decoded_points.len(), 8);
|
|
|
|
let series_map =
|
|
|te_symbol: &str, country: &str, category: &str| match (te_symbol, country, category) {
|
|
("CABOCRATE", "Canada", "Interest Rate") => {
|
|
Some(target("CA", "policy_rate", MacroLagClass::PolicyRate))
|
|
}
|
|
("USCPIYOY", "United States", "Inflation Rate") => {
|
|
Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease))
|
|
}
|
|
("USGDPQOQ", "United States", "GDP Growth Rate") => {
|
|
Some(target("US", "gdp_qoq", MacroLagClass::Gdp65))
|
|
}
|
|
("CAGDPQOQ", "Canada", "GDP Growth Rate") => {
|
|
Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90))
|
|
}
|
|
_ => None,
|
|
};
|
|
|
|
let tmp = TempDirGuard::new("bson-roundtrip");
|
|
let report = curate_and_write_macro(
|
|
tmp.path(),
|
|
decoded_points,
|
|
series_map,
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect("curate_and_write_macro should succeed");
|
|
|
|
assert_stats_conserved(&report.curate_stats);
|
|
assert_eq!(report.curate_stats.points_in, 8);
|
|
assert_eq!(report.curate_stats.dropped_unmapped_series, 1);
|
|
assert_eq!(report.curate_stats.builder.input, 7);
|
|
assert_eq!(report.curate_stats.builder.emitted, 7);
|
|
assert_eq!(report.curate_stats.rows_out, 7);
|
|
assert_eq!(report.curate_stats.series_out, 4);
|
|
assert_eq!(report.write_stats.rows_written, 7);
|
|
assert_eq!(report.write_stats.files_written, 1);
|
|
|
|
let part_path = tmp.path().join("macro/part.parquet");
|
|
assert!(part_path.exists());
|
|
assert_eq!(
|
|
sorted_dir_entries(&tmp.path().join("macro")),
|
|
vec!["part.parquet"]
|
|
);
|
|
|
|
let read_back = read_parquet_rows(&part_path);
|
|
assert_strictly_ascending_unique(&read_back);
|
|
|
|
let expected = vec![
|
|
expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, -0.25),
|
|
expected_row(
|
|
"CA",
|
|
"policy_rate",
|
|
day(2024, 1, 24),
|
|
POLICY_RATE_LAG_DAYS,
|
|
5.0,
|
|
),
|
|
expected_row(
|
|
"CA",
|
|
"policy_rate",
|
|
day(2024, 6, 5),
|
|
POLICY_RATE_LAG_DAYS,
|
|
0.0,
|
|
),
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 1, 31),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.1,
|
|
),
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 2, 29),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.2,
|
|
),
|
|
expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4),
|
|
expected_row("US", "gdp_qoq", day(2024, 6, 30), GDP65_LAG_DAYS, -0.0),
|
|
];
|
|
assert_rows_bitwise_eq(&read_back, &expected);
|
|
|
|
// Explicitly verify each lag class UTC midnight timestamp and provenance label, and absence of
|
|
// all forecast dates.
|
|
let forecast_dates = [
|
|
day(2025, 12, 31),
|
|
day(2026, 3, 31),
|
|
day(2025, 6, 30),
|
|
day(2025, 9, 30),
|
|
day(2025, 10, 31),
|
|
];
|
|
for row in &read_back {
|
|
assert_eq!(row.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE);
|
|
assert_eq!(row.known_at_source.as_ref(), "publication_lag_estimate");
|
|
assert_eq!(row.known_at_micros % MICROS_PER_DAY, 0);
|
|
assert!(
|
|
!forecast_dates.contains(&row.period_date),
|
|
"forecast date leaked into output: {row:?}"
|
|
);
|
|
}
|
|
assert_eq!(
|
|
read_back[0].known_at_micros,
|
|
i64::from(day(2024, 3, 31) + 90) * MICROS_PER_DAY
|
|
);
|
|
assert_eq!(
|
|
read_back[1].known_at_micros,
|
|
i64::from(day(2024, 1, 24) + 1) * MICROS_PER_DAY
|
|
);
|
|
assert_eq!(
|
|
read_back[3].known_at_micros,
|
|
i64::from(day(2024, 1, 31) + 35) * MICROS_PER_DAY
|
|
);
|
|
assert_eq!(
|
|
read_back[5].known_at_micros,
|
|
i64::from(day(2024, 3, 31) + 65) * MICROS_PER_DAY
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn permutation_invariance_unmapped_duplicates_and_non_finite_accounting() {
|
|
let base_points = vec![
|
|
// Mapped US cpi_yoy (+35d): two dates + exact duplicate + NaN + +inf
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 2, 29),
|
|
value: 3.2,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 3.1,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 3.1,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 3, 31),
|
|
value: f64::NAN,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 4, 30),
|
|
value: f64::INFINITY,
|
|
},
|
|
// Mapped CA policy_rate (+1d): one finite + one -inf
|
|
TeDataPoint {
|
|
te_symbol: "CABOCRATE",
|
|
country: "Canada",
|
|
category: "Interest Rate",
|
|
period_date: day(2024, 1, 24),
|
|
value: 5.0,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "CABOCRATE",
|
|
country: "Canada",
|
|
category: "Interest Rate",
|
|
period_date: day(2024, 3, 6),
|
|
value: f64::NEG_INFINITY,
|
|
},
|
|
// Unmapped tuples: case difference, whitespace difference, and unknown series
|
|
TeDataPoint {
|
|
te_symbol: "uscpiyoy",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 9.9,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY ",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 9.9,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "DEUNEMP",
|
|
country: "Germany",
|
|
category: "Unemployment Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 5.9,
|
|
},
|
|
];
|
|
|
|
let series_map =
|
|
|te_symbol: &str, country: &str, category: &str| match (te_symbol, country, category) {
|
|
("USCPIYOY", "United States", "Inflation Rate") => {
|
|
Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease))
|
|
}
|
|
("CABOCRATE", "Canada", "Interest Rate") => {
|
|
Some(target("CA", "policy_rate", MacroLagClass::PolicyRate))
|
|
}
|
|
_ => None,
|
|
};
|
|
|
|
let mut reversed = base_points.clone();
|
|
reversed.reverse();
|
|
|
|
let interleaved: Vec<TeDataPoint<'_>> = vec![
|
|
base_points[9],
|
|
base_points[5],
|
|
base_points[2],
|
|
base_points[7],
|
|
base_points[4],
|
|
base_points[0],
|
|
base_points[8],
|
|
base_points[6],
|
|
base_points[3],
|
|
base_points[1],
|
|
];
|
|
|
|
let out_base = curate_macro(base_points, series_map).expect("base ok");
|
|
let out_rev = curate_macro(reversed, series_map).expect("reversed ok");
|
|
let out_inter = curate_macro(interleaved, series_map).expect("interleaved ok");
|
|
|
|
for out in [&out_base, &out_rev, &out_inter] {
|
|
assert_strictly_ascending_unique(&out.rows);
|
|
assert_stats_conserved(&out.stats);
|
|
assert_eq!(out.stats.points_in, 10);
|
|
assert_eq!(out.stats.dropped_unmapped_series, 3);
|
|
assert_eq!(out.stats.builder.input, 7);
|
|
assert_eq!(out.stats.builder.emitted, 3);
|
|
assert_eq!(out.stats.builder.skipped_non_finite_value, 3);
|
|
assert_eq!(out.stats.builder.skipped_duplicate, 1);
|
|
assert_eq!(out.stats.rows_out, 3);
|
|
assert_eq!(out.stats.series_out, 2);
|
|
}
|
|
|
|
assert_eq!(out_base.stats, out_rev.stats);
|
|
assert_eq!(out_base.stats, out_inter.stats);
|
|
assert_rows_bitwise_eq(&out_base.rows, &out_rev.rows);
|
|
assert_rows_bitwise_eq(&out_base.rows, &out_inter.rows);
|
|
|
|
let expected = vec![
|
|
expected_row(
|
|
"CA",
|
|
"policy_rate",
|
|
day(2024, 1, 24),
|
|
POLICY_RATE_LAG_DAYS,
|
|
5.0,
|
|
),
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 1, 31),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.1,
|
|
),
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 2, 29),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.2,
|
|
),
|
|
];
|
|
assert_rows_bitwise_eq(&out_base.rows, &expected);
|
|
}
|
|
|
|
#[test]
|
|
fn empty_and_all_unmapped_inputs_produce_zero_rows_and_do_not_touch_out_dir() {
|
|
let never_map = |_: &str, _: &str, _: &str| -> Option<MacroSeriesTarget> { None };
|
|
|
|
// 1. Fresh directory with empty input
|
|
let fresh_empty = TempDirGuard::new("fresh-empty");
|
|
let report = curate_and_write_macro(
|
|
fresh_empty.path(),
|
|
std::iter::empty::<TeDataPoint<'static>>(),
|
|
never_map,
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect("empty input succeeds");
|
|
assert_stats_conserved(&report.curate_stats);
|
|
assert_eq!(report.curate_stats.points_in, 0);
|
|
assert_eq!(report.curate_stats.rows_out, 0);
|
|
assert_eq!(report.curate_stats.series_out, 0);
|
|
assert_eq!(report.write_stats, MacroWriteStats::default());
|
|
assert!(!fresh_empty.path().join("macro").exists());
|
|
|
|
// 2. Fresh directory with all-unmapped input
|
|
let fresh_unmapped = TempDirGuard::new("fresh-unmapped");
|
|
let unmapped = [TeDataPoint {
|
|
te_symbol: "UNKNOWN",
|
|
country: "Nowhere",
|
|
category: "Mystery",
|
|
period_date: day(2024, 1, 1),
|
|
value: 1.0,
|
|
}];
|
|
let report = curate_and_write_macro(
|
|
fresh_unmapped.path(),
|
|
unmapped,
|
|
never_map,
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect("all-unmapped input succeeds");
|
|
assert_stats_conserved(&report.curate_stats);
|
|
assert_eq!(report.curate_stats.points_in, 1);
|
|
assert_eq!(report.curate_stats.dropped_unmapped_series, 1);
|
|
assert_eq!(report.curate_stats.rows_out, 0);
|
|
assert_eq!(report.curate_stats.series_out, 0);
|
|
assert_eq!(report.write_stats, MacroWriteStats::default());
|
|
assert!(!fresh_unmapped.path().join("macro").exists());
|
|
|
|
// 3. Pre-existing part.parquet is preserved byte-identical on all-unmapped input
|
|
let existing = TempDirGuard::new("existing-unmapped");
|
|
let (part, before_bytes, before_entries) = seed_existing_parquet(existing.path());
|
|
let report = curate_and_write_macro(
|
|
existing.path(),
|
|
unmapped,
|
|
never_map,
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect("all-unmapped against existing succeeds");
|
|
assert_eq!(report.write_stats, MacroWriteStats::default());
|
|
assert_eq!(fs::read(&part).expect("read after"), before_bytes);
|
|
assert_eq!(
|
|
sorted_dir_entries(&existing.path().join("macro")),
|
|
before_entries
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn conflicting_duplicate_and_signed_zero_propagate_macro_error() {
|
|
let map_cpi =
|
|
|_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease));
|
|
|
|
// Unequal finite values at same (country_iso, indicator, period_date)
|
|
let unequal = [
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 3.1,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 1, 31),
|
|
value: 3.2,
|
|
},
|
|
];
|
|
let err = curate_macro(unequal, map_cpi).expect_err("unequal duplicate must fail");
|
|
assert_eq!(
|
|
err,
|
|
CurateMacroError::Macro(MacroError::ConflictingDuplicate {
|
|
country_iso: "US".to_owned(),
|
|
indicator: "cpi_yoy".to_owned(),
|
|
period_date: day(2024, 1, 31),
|
|
})
|
|
);
|
|
assert!(err.source().is_some());
|
|
|
|
// Opposite signed zeros (+0.0 vs -0.0) at same (country_iso, indicator, period_date)
|
|
let signed_zeros = [
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 2, 29),
|
|
value: 0.0,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "USCPIYOY",
|
|
country: "United States",
|
|
category: "Inflation Rate",
|
|
period_date: day(2024, 2, 29),
|
|
value: -0.0,
|
|
},
|
|
];
|
|
let err = curate_macro(signed_zeros, map_cpi).expect_err("signed zero conflict must fail");
|
|
assert_eq!(
|
|
err,
|
|
CurateMacroError::Macro(MacroError::ConflictingDuplicate {
|
|
country_iso: "US".to_owned(),
|
|
indicator: "cpi_yoy".to_owned(),
|
|
period_date: day(2024, 2, 29),
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn conflicting_lag_class_is_order_independent_and_checks_before_non_finite_filtering() {
|
|
// Two distinct provider aliases targeting the same (country_iso, indicator) on different dates
|
|
// with different lag classes, including one non-finite point.
|
|
let p_gdp65 = TeDataPoint {
|
|
te_symbol: "USGDP_FAST",
|
|
country: "United States",
|
|
category: "GDP Growth Rate",
|
|
period_date: day(2024, 3, 31),
|
|
value: 1.4,
|
|
};
|
|
let p_gdp90_nan = TeDataPoint {
|
|
te_symbol: "USGDP_SLOW",
|
|
country: "United States",
|
|
category: "GDP Growth Rate Revised",
|
|
period_date: day(2024, 6, 30),
|
|
value: f64::NAN,
|
|
};
|
|
|
|
let alias_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)),
|
|
"USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)),
|
|
_ => None,
|
|
};
|
|
|
|
let err_ab = curate_macro([p_gdp65, p_gdp90_nan], alias_map).expect_err("order A must fail");
|
|
let err_ba = curate_macro([p_gdp90_nan, p_gdp65], alias_map).expect_err("order B must fail");
|
|
|
|
let expected = CurateMacroError::ConflictingLagClass {
|
|
country_iso: "US".to_owned(),
|
|
indicator: "gdp_qoq".to_owned(),
|
|
first_lag_class: MacroLagClass::Gdp65,
|
|
second_lag_class: MacroLagClass::Gdp90,
|
|
};
|
|
assert_eq!(err_ab, expected);
|
|
assert_eq!(err_ba, expected);
|
|
assert!(err_ab.source().is_none());
|
|
|
|
// Multiple conflicting targets: always report the lowest (country_iso, indicator) in key order.
|
|
let ca_rate_a = TeDataPoint {
|
|
te_symbol: "CA_A",
|
|
country: "Canada",
|
|
category: "Rate",
|
|
period_date: day(2024, 1, 1),
|
|
value: 5.0,
|
|
};
|
|
let ca_rate_b = TeDataPoint {
|
|
te_symbol: "CA_B",
|
|
country: "Canada",
|
|
category: "Rate",
|
|
period_date: day(2024, 2, 1),
|
|
value: 5.0,
|
|
};
|
|
let multi_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"USGDP_FAST" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)),
|
|
"USGDP_SLOW" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)),
|
|
"CA_A" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)),
|
|
"CA_B" => Some(target("CA", "policy_rate", MacroLagClass::MonthlyRelease)),
|
|
_ => None,
|
|
};
|
|
|
|
let err_multi_1 = curate_macro([p_gdp65, p_gdp90_nan, ca_rate_a, ca_rate_b], multi_map)
|
|
.expect_err("multi 1 must fail");
|
|
let err_multi_2 = curate_macro([ca_rate_b, p_gdp90_nan, ca_rate_a, p_gdp65], multi_map)
|
|
.expect_err("multi 2 must fail");
|
|
assert_eq!(
|
|
err_multi_1,
|
|
CurateMacroError::ConflictingLagClass {
|
|
country_iso: "CA".to_owned(),
|
|
indicator: "policy_rate".to_owned(),
|
|
first_lag_class: MacroLagClass::PolicyRate,
|
|
second_lag_class: MacroLagClass::MonthlyRelease,
|
|
}
|
|
);
|
|
assert_eq!(err_multi_1, err_multi_2);
|
|
}
|
|
|
|
#[test]
|
|
fn known_at_overflow_and_invalid_write_options_and_single_line_display() {
|
|
// 1. KnownAtOverflow propagated from build_macro_rows
|
|
let overflow_pt = [TeDataPoint {
|
|
te_symbol: "EXTREME",
|
|
country: "United States",
|
|
category: "GDP",
|
|
period_date: i32::MAX,
|
|
value: 1.0,
|
|
}];
|
|
let map_gdp90 = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90));
|
|
let err = curate_macro(overflow_pt, map_gdp90).expect_err("overflow must fail");
|
|
assert_eq!(
|
|
err,
|
|
CurateMacroError::Macro(MacroError::KnownAtOverflow {
|
|
period_date: i32::MAX,
|
|
lag_class: MacroLagClass::Gdp90,
|
|
})
|
|
);
|
|
assert!(err.source().is_some());
|
|
let msg = err.to_string();
|
|
assert!(
|
|
!msg.contains('\n') && !msg.contains('\r'),
|
|
"multi-line: {msg:?}"
|
|
);
|
|
|
|
// 2. InvalidRowGroupRows wrapped in CurateMacroWriteError::Parquet
|
|
let tmp = TempDirGuard::new("invalid-opts");
|
|
let valid_pt = [TeDataPoint {
|
|
te_symbol: "CABOCRATE",
|
|
country: "Canada",
|
|
category: "Interest Rate",
|
|
period_date: day(2024, 1, 24),
|
|
value: 5.0,
|
|
}];
|
|
let map_rate =
|
|
|_: &str, _: &str, _: &str| Some(target("CA", "policy_rate", MacroLagClass::PolicyRate));
|
|
let write_err = curate_and_write_macro(
|
|
tmp.path(),
|
|
valid_pt,
|
|
map_rate,
|
|
MacroWriteOptions {
|
|
row_group_rows: 0,
|
|
..MacroWriteOptions::default()
|
|
},
|
|
)
|
|
.expect_err("row_group_rows=0 must fail");
|
|
assert!(matches!(
|
|
write_err,
|
|
CurateMacroWriteError::Parquet(ParquetMacroError::InvalidRowGroupRows)
|
|
));
|
|
assert!(write_err.source().is_some());
|
|
let msg = write_err.to_string();
|
|
assert!(
|
|
!msg.contains('\n') && !msg.contains('\r'),
|
|
"multi-line: {msg:?}"
|
|
);
|
|
|
|
// 3. Newline-bearing diagnostic labels stay single-line in both CurateMacroError and
|
|
// CurateMacroWriteError (covering ConflictingLagClass, ConflictingDuplicate, and Parquet).
|
|
let nl_lag_err = CurateMacroWriteError::from(CurateMacroError::ConflictingLagClass {
|
|
country_iso: "US\nline2".to_owned(),
|
|
indicator: "cpi\r\nyoy".to_owned(),
|
|
first_lag_class: MacroLagClass::PolicyRate,
|
|
second_lag_class: MacroLagClass::MonthlyRelease,
|
|
});
|
|
let nl_lag_msg = nl_lag_err.to_string();
|
|
assert!(
|
|
!nl_lag_msg.contains('\n') && !nl_lag_msg.contains('\r'),
|
|
"ConflictingLagClass display must be single-line: {nl_lag_msg:?}"
|
|
);
|
|
assert!(nl_lag_msg.contains("US\\nline2"));
|
|
assert!(nl_lag_msg.contains("cpi\\r\\nyoy"));
|
|
|
|
let nl_dup_err =
|
|
CurateMacroWriteError::from(CurateMacroError::from(MacroError::ConflictingDuplicate {
|
|
country_iso: "CA\n2".to_owned(),
|
|
indicator: "gdp\r3".to_owned(),
|
|
period_date: day(2024, 1, 1),
|
|
}));
|
|
let nl_dup_msg = nl_dup_err.to_string();
|
|
assert!(
|
|
!nl_dup_msg.contains('\n') && !nl_dup_msg.contains('\r'),
|
|
"ConflictingDuplicate display must be single-line: {nl_dup_msg:?}"
|
|
);
|
|
|
|
// ParquetMacroError::EmptyCountryIso displays `indicator` with `{indicator}`, so newlines
|
|
// would leak unless CurateMacroWriteError escapes them.
|
|
let nl_pq_err = curate_and_write_macro(
|
|
tmp.path(),
|
|
valid_pt,
|
|
|_: &str, _: &str, _: &str| {
|
|
Some(target(
|
|
" ",
|
|
"bad\nindicator\rname",
|
|
MacroLagClass::PolicyRate,
|
|
))
|
|
},
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect_err("blank country_iso must fail in writer");
|
|
assert!(matches!(
|
|
nl_pq_err,
|
|
CurateMacroWriteError::Parquet(ParquetMacroError::EmptyCountryIso { .. })
|
|
));
|
|
let nl_pq_msg = nl_pq_err.to_string();
|
|
assert!(
|
|
!nl_pq_msg.contains('\n') && !nl_pq_msg.contains('\r'),
|
|
"Parquet display must be single-line: {nl_pq_msg:?}"
|
|
);
|
|
assert!(nl_pq_msg.contains("bad\\nindicator\\rname"));
|
|
}
|
|
|
|
#[test]
|
|
fn curation_errors_never_write_or_modify_out_dir() {
|
|
// 1. ConflictingLagClass
|
|
let lag_conflict_points = [
|
|
TeDataPoint {
|
|
te_symbol: "A",
|
|
country: "US",
|
|
category: "GDP",
|
|
period_date: day(2024, 3, 31),
|
|
value: 1.4,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "B",
|
|
country: "US",
|
|
category: "GDP",
|
|
period_date: day(2024, 6, 30),
|
|
value: 1.8,
|
|
},
|
|
];
|
|
let lag_conflict_map = |sym: &str, _: &str, _: &str| match sym {
|
|
"A" => Some(target("US", "gdp", MacroLagClass::Gdp65)),
|
|
"B" => Some(target("US", "gdp", MacroLagClass::Gdp90)),
|
|
_ => None,
|
|
};
|
|
|
|
// 2. ConflictingDuplicate
|
|
let dup_conflict_points = [
|
|
TeDataPoint {
|
|
te_symbol: "A",
|
|
country: "US",
|
|
category: "CPI",
|
|
period_date: day(2024, 1, 31),
|
|
value: 3.1,
|
|
},
|
|
TeDataPoint {
|
|
te_symbol: "A",
|
|
country: "US",
|
|
category: "CPI",
|
|
period_date: day(2024, 1, 31),
|
|
value: 3.2,
|
|
},
|
|
];
|
|
let cpi_map =
|
|
|_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease));
|
|
|
|
// 3. KnownAtOverflow
|
|
let overflow_points = [TeDataPoint {
|
|
te_symbol: "A",
|
|
country: "US",
|
|
category: "GDP",
|
|
period_date: i32::MAX,
|
|
value: 1.0,
|
|
}];
|
|
let gdp_map = |_: &str, _: &str, _: &str| Some(target("US", "gdp", MacroLagClass::Gdp90));
|
|
|
|
// Fresh destination checks
|
|
for (label, result, dir) in [
|
|
{
|
|
let dir = TempDirGuard::new("err-fresh-lag");
|
|
let res = curate_and_write_macro(
|
|
dir.path(),
|
|
lag_conflict_points,
|
|
lag_conflict_map,
|
|
MacroWriteOptions::default(),
|
|
);
|
|
("ConflictingLagClass", res, dir)
|
|
},
|
|
{
|
|
let dir = TempDirGuard::new("err-fresh-dup");
|
|
let res = curate_and_write_macro(
|
|
dir.path(),
|
|
dup_conflict_points,
|
|
cpi_map,
|
|
MacroWriteOptions::default(),
|
|
);
|
|
("ConflictingDuplicate", res, dir)
|
|
},
|
|
{
|
|
let dir = TempDirGuard::new("err-fresh-overflow");
|
|
let res = curate_and_write_macro(
|
|
dir.path(),
|
|
overflow_points,
|
|
gdp_map,
|
|
MacroWriteOptions::default(),
|
|
);
|
|
("KnownAtOverflow", res, dir)
|
|
},
|
|
] {
|
|
let err = result.expect_err(&format!("{label} must fail"));
|
|
assert!(
|
|
matches!(err, CurateMacroWriteError::Curate(_)),
|
|
"{label} should be Curate error: {err}"
|
|
);
|
|
assert!(
|
|
!dir.path().join("macro").exists(),
|
|
"{label} must not create macro/ dir"
|
|
);
|
|
assert!(
|
|
sorted_dir_entries(dir.path()).is_empty(),
|
|
"{label} must leave fresh out_dir empty"
|
|
);
|
|
}
|
|
|
|
// Existing valid macro/part.parquet preservation checks
|
|
for (label, result, part, before_bytes, before_entries, dir) in [
|
|
{
|
|
let dir = TempDirGuard::new("err-existing-lag");
|
|
let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path());
|
|
let res = curate_and_write_macro(
|
|
dir.path(),
|
|
lag_conflict_points,
|
|
lag_conflict_map,
|
|
MacroWriteOptions::default(),
|
|
);
|
|
(
|
|
"ConflictingLagClass",
|
|
res,
|
|
part,
|
|
before_bytes,
|
|
before_entries,
|
|
dir,
|
|
)
|
|
},
|
|
{
|
|
let dir = TempDirGuard::new("err-existing-dup");
|
|
let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path());
|
|
let res = curate_and_write_macro(
|
|
dir.path(),
|
|
dup_conflict_points,
|
|
cpi_map,
|
|
MacroWriteOptions::default(),
|
|
);
|
|
(
|
|
"ConflictingDuplicate",
|
|
res,
|
|
part,
|
|
before_bytes,
|
|
before_entries,
|
|
dir,
|
|
)
|
|
},
|
|
{
|
|
let dir = TempDirGuard::new("err-existing-overflow");
|
|
let (part, before_bytes, before_entries) = seed_existing_parquet(dir.path());
|
|
let res = curate_and_write_macro(
|
|
dir.path(),
|
|
overflow_points,
|
|
gdp_map,
|
|
MacroWriteOptions::default(),
|
|
);
|
|
(
|
|
"KnownAtOverflow",
|
|
res,
|
|
part,
|
|
before_bytes,
|
|
before_entries,
|
|
dir,
|
|
)
|
|
},
|
|
] {
|
|
let err = result.expect_err(&format!("{label} must fail"));
|
|
assert!(
|
|
matches!(err, CurateMacroWriteError::Curate(_)),
|
|
"{label} should be Curate error: {err}"
|
|
);
|
|
assert_eq!(
|
|
fs::read(&part).expect("read existing parquet"),
|
|
before_bytes,
|
|
"{label} must leave existing part.parquet byte-identical"
|
|
);
|
|
assert_eq!(
|
|
sorted_dir_entries(&dir.path().join("macro")),
|
|
before_entries,
|
|
"{label} must leave macro/ directory entries unchanged"
|
|
);
|
|
}
|
|
}
|
|
|
|
fn te_point(
|
|
te_symbol: &'static str,
|
|
country: &'static str,
|
|
category: &'static str,
|
|
period_date: i32,
|
|
value: f64,
|
|
) -> TeDataPoint<'static> {
|
|
TeDataPoint {
|
|
te_symbol,
|
|
country,
|
|
category,
|
|
period_date,
|
|
value,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn mapped_target_with_only_non_finite_values_does_not_count_as_emitted_series() {
|
|
let points = vec![
|
|
te_point(
|
|
"USCPIYOY",
|
|
"United States",
|
|
"Inflation Rate",
|
|
day(2024, 1, 31),
|
|
3.1,
|
|
),
|
|
te_point(
|
|
"CABOCRATE",
|
|
"Canada",
|
|
"Interest Rate",
|
|
day(2024, 1, 24),
|
|
5.0,
|
|
),
|
|
te_point(
|
|
"DEGDP",
|
|
"Germany",
|
|
"GDP Growth Rate",
|
|
day(2024, 3, 31),
|
|
f64::NAN,
|
|
),
|
|
te_point(
|
|
"DEGDP",
|
|
"Germany",
|
|
"GDP Growth Rate",
|
|
day(2024, 6, 30),
|
|
f64::INFINITY,
|
|
),
|
|
te_point(
|
|
"DEGDP",
|
|
"Germany",
|
|
"GDP Growth Rate",
|
|
day(2024, 9, 30),
|
|
f64::NEG_INFINITY,
|
|
),
|
|
];
|
|
let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"USCPIYOY" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)),
|
|
"CABOCRATE" => Some(target("CA", "policy_rate", MacroLagClass::PolicyRate)),
|
|
"DEGDP" => Some(target("DE", "gdp_qoq", MacroLagClass::Gdp65)),
|
|
_ => None,
|
|
};
|
|
|
|
let mut reversed = points.clone();
|
|
reversed.reverse();
|
|
let rotated: Vec<_> = points[2..]
|
|
.iter()
|
|
.chain(points[..2].iter())
|
|
.copied()
|
|
.collect();
|
|
|
|
let mut outputs = Vec::new();
|
|
for perm in [points, reversed, rotated] {
|
|
let out = curate_macro(perm, series_map).expect("curation succeeds");
|
|
assert_stats_conserved(&out.stats);
|
|
assert_eq!(out.stats.points_in, 5);
|
|
assert_eq!(out.stats.dropped_unmapped_series, 0);
|
|
assert_eq!(out.stats.builder.input, 5);
|
|
assert_eq!(out.stats.builder.skipped_non_finite_value, 3);
|
|
assert_eq!(out.stats.builder.emitted, 2);
|
|
assert_eq!(out.stats.rows_out, 2);
|
|
assert_eq!(
|
|
out.stats.series_out, 2,
|
|
"non-finite-only target must not count"
|
|
);
|
|
assert!(out.rows.iter().all(|r| r.country_iso != "DE"));
|
|
outputs.push(out);
|
|
}
|
|
assert_eq!(outputs[0].stats, outputs[1].stats);
|
|
assert_eq!(outputs[0].stats, outputs[2].stats);
|
|
assert_rows_bitwise_eq(&outputs[0].rows, &outputs[1].rows);
|
|
assert_rows_bitwise_eq(&outputs[0].rows, &outputs[2].rows);
|
|
}
|
|
|
|
#[test]
|
|
fn lookup_receives_verbatim_provider_labels_once_per_point() {
|
|
use std::cell::RefCell;
|
|
|
|
let points = [
|
|
te_point(
|
|
" USCPIYOY",
|
|
"United States ",
|
|
"Inflation\tRate",
|
|
day(2024, 1, 31),
|
|
3.1,
|
|
),
|
|
te_point(
|
|
"cabocrate",
|
|
"CANADA",
|
|
"Interest Rate",
|
|
day(2024, 1, 24),
|
|
5.0,
|
|
),
|
|
te_point(
|
|
"ÜMLAUT",
|
|
"Österreich",
|
|
"Kategorie",
|
|
day(2024, 2, 1),
|
|
f64::NAN,
|
|
),
|
|
];
|
|
let calls: RefCell<Vec<(String, String, String)>> = RefCell::new(Vec::new());
|
|
let out = curate_macro(points, |s: &str, c: &str, k: &str| {
|
|
calls
|
|
.borrow_mut()
|
|
.push((s.to_owned(), c.to_owned(), k.to_owned()));
|
|
None
|
|
})
|
|
.expect("all-unmapped succeeds");
|
|
|
|
assert_eq!(
|
|
calls.into_inner(),
|
|
vec![
|
|
(
|
|
" USCPIYOY".into(),
|
|
"United States ".into(),
|
|
"Inflation\tRate".into()
|
|
),
|
|
("cabocrate".into(), "CANADA".into(), "Interest Rate".into()),
|
|
("ÜMLAUT".into(), "Österreich".into(), "Kategorie".into()),
|
|
]
|
|
);
|
|
assert_stats_conserved(&out.stats);
|
|
assert_eq!(out.stats.dropped_unmapped_series, 3);
|
|
assert_eq!(out.stats.builder.input, 0);
|
|
// Unmapped non-finite points never reach the builder's non-finite counter.
|
|
assert_eq!(out.stats.builder.skipped_non_finite_value, 0);
|
|
assert!(out.rows.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn unmapped_points_never_trigger_builder_errors() {
|
|
// Unmapped points that would overflow known_at or conflict with a mapped value are dropped
|
|
// before build_macro_rows, so they cannot fail the stage.
|
|
let points = [
|
|
te_point(
|
|
"USCPIYOY",
|
|
"United States",
|
|
"Inflation Rate",
|
|
day(2024, 1, 31),
|
|
3.1,
|
|
),
|
|
te_point(
|
|
"USCPIYOY_ALT",
|
|
"United States",
|
|
"Inflation Rate",
|
|
day(2024, 1, 31),
|
|
9.9,
|
|
),
|
|
te_point("EXTREME", "United States", "GDP", i32::MAX, 1.0),
|
|
];
|
|
let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"USCPIYOY" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)),
|
|
_ => None,
|
|
};
|
|
let out = curate_macro(points, series_map).expect("unmapped points must be ignored");
|
|
assert_stats_conserved(&out.stats);
|
|
assert_eq!(out.stats.dropped_unmapped_series, 2);
|
|
assert_rows_bitwise_eq(
|
|
&out.rows,
|
|
&[expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 1, 31),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.1,
|
|
)],
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn aliases_with_same_lag_class_merge_into_one_series_and_cross_alias_duplicates_collapse() {
|
|
let points = [
|
|
te_point(
|
|
"USCPIYOY",
|
|
"United States",
|
|
"Inflation Rate",
|
|
day(2024, 1, 31),
|
|
3.1,
|
|
),
|
|
te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 1, 31), 3.1),
|
|
te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 2, 29), 3.2),
|
|
];
|
|
let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"USCPIYOY" | "USCPI_ALT" => Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)),
|
|
_ => None,
|
|
};
|
|
let out = curate_macro(points, series_map).expect("same lag class is not a conflict");
|
|
assert_stats_conserved(&out.stats);
|
|
assert_eq!(out.stats.builder.skipped_duplicate, 1);
|
|
assert_eq!(out.stats.series_out, 1);
|
|
assert_rows_bitwise_eq(
|
|
&out.rows,
|
|
&[
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 1, 31),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.1,
|
|
),
|
|
expected_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
day(2024, 2, 29),
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
3.2,
|
|
),
|
|
],
|
|
);
|
|
|
|
// Cross-alias conflicting values on the same target/date are rejected by the builder.
|
|
let conflicting = [
|
|
te_point(
|
|
"USCPIYOY",
|
|
"United States",
|
|
"Inflation Rate",
|
|
day(2024, 1, 31),
|
|
3.1,
|
|
),
|
|
te_point("USCPI_ALT", "USA", "CPI YoY", day(2024, 1, 31), 3.0),
|
|
];
|
|
assert_eq!(
|
|
curate_macro(conflicting, series_map).expect_err("cross-alias conflict"),
|
|
CurateMacroError::Macro(MacroError::ConflictingDuplicate {
|
|
country_iso: "US".to_owned(),
|
|
indicator: "cpi_yoy".to_owned(),
|
|
period_date: day(2024, 1, 31),
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn same_indicator_in_different_countries_may_use_different_lag_classes() {
|
|
let points = [
|
|
te_point("USGDP", "United States", "GDP", day(2024, 3, 31), 1.4),
|
|
te_point("CAGDP", "Canada", "GDP", day(2024, 3, 31), 0.5),
|
|
];
|
|
let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"USGDP" => Some(target("US", "gdp_qoq", MacroLagClass::Gdp65)),
|
|
"CAGDP" => Some(target("CA", "gdp_qoq", MacroLagClass::Gdp90)),
|
|
_ => None,
|
|
};
|
|
let out = curate_macro(points, series_map).expect("per-country lag classes are independent");
|
|
assert_eq!(out.stats.series_out, 2);
|
|
assert_rows_bitwise_eq(
|
|
&out.rows,
|
|
&[
|
|
expected_row("CA", "gdp_qoq", day(2024, 3, 31), GDP90_LAG_DAYS, 0.5),
|
|
expected_row("US", "gdp_qoq", day(2024, 3, 31), GDP65_LAG_DAYS, 1.4),
|
|
],
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn three_way_lag_conflict_reports_min_and_max_class_for_every_order() {
|
|
let a = te_point("A", "X", "Y", day(2024, 1, 31), 1.0);
|
|
let b = te_point("B", "X", "Y", day(2024, 2, 29), 2.0);
|
|
let c = te_point("C", "X", "Y", day(2024, 3, 31), 3.0);
|
|
let series_map = |te_symbol: &str, _: &str, _: &str| match te_symbol {
|
|
"A" => Some(target("US", "mix", MacroLagClass::MonthlyRelease)),
|
|
"B" => Some(target("US", "mix", MacroLagClass::Gdp90)),
|
|
"C" => Some(target("US", "mix", MacroLagClass::PolicyRate)),
|
|
_ => None,
|
|
};
|
|
let expected = CurateMacroError::ConflictingLagClass {
|
|
country_iso: "US".to_owned(),
|
|
indicator: "mix".to_owned(),
|
|
first_lag_class: MacroLagClass::PolicyRate,
|
|
second_lag_class: MacroLagClass::Gdp90,
|
|
};
|
|
for perm in [
|
|
[a, b, c],
|
|
[a, c, b],
|
|
[b, a, c],
|
|
[b, c, a],
|
|
[c, a, b],
|
|
[c, b, a],
|
|
] {
|
|
assert_eq!(
|
|
curate_macro(perm, series_map).expect_err("conflict"),
|
|
expected
|
|
);
|
|
}
|
|
let msg = expected.to_string();
|
|
assert!(msg.contains("+1d") && msg.contains("+90d"), "{msg}");
|
|
}
|
|
|
|
#[test]
|
|
fn write_error_source_chain_reaches_macro_error() {
|
|
let points = [
|
|
te_point("A", "US", "CPI", day(2024, 1, 31), 3.1),
|
|
te_point("A", "US", "CPI", day(2024, 1, 31), 3.2),
|
|
];
|
|
let tmp = TempDirGuard::new("source-chain");
|
|
let err = curate_and_write_macro(
|
|
tmp.path(),
|
|
points,
|
|
|_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)),
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect_err("duplicate conflict");
|
|
let lvl1 = err.source().expect("curate error source");
|
|
assert!(lvl1.downcast_ref::<CurateMacroError>().is_some());
|
|
let lvl2 = lvl1.source().expect("macro error source");
|
|
assert!(lvl2.downcast_ref::<MacroError<String>>().is_some());
|
|
assert!(err.to_string().starts_with("macro curation failed: "));
|
|
}
|
|
|
|
#[test]
|
|
fn successful_write_replaces_existing_part_parquet_with_curated_rows() {
|
|
let tmp = TempDirGuard::new("replace-existing");
|
|
let (part, before_bytes, _) = seed_existing_parquet(tmp.path());
|
|
|
|
let points = [te_point(
|
|
"USGDP",
|
|
"United States",
|
|
"GDP",
|
|
day(2024, 6, 30),
|
|
2.8,
|
|
)];
|
|
let report = curate_and_write_macro(
|
|
tmp.path(),
|
|
points,
|
|
|_: &str, _: &str, _: &str| Some(target("US", "gdp_qoq", MacroLagClass::Gdp90)),
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect("write succeeds");
|
|
assert_eq!(report.write_stats.rows_written, 1);
|
|
assert_ne!(fs::read(&part).expect("read after"), before_bytes);
|
|
assert_eq!(
|
|
sorted_dir_entries(&tmp.path().join("macro")),
|
|
vec!["part.parquet"]
|
|
);
|
|
assert_rows_bitwise_eq(
|
|
&read_parquet_rows(&part),
|
|
&[expected_row(
|
|
"US",
|
|
"gdp_qoq",
|
|
day(2024, 6, 30),
|
|
GDP90_LAG_DAYS,
|
|
2.8,
|
|
)],
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn extreme_finite_values_and_pre_epoch_dates_round_trip_bitwise_through_write() {
|
|
// Arrange: one Monthly1 series with pre-1970 and extreme-but-finite values.
|
|
let subnormal = f64::from_bits(1);
|
|
let neg_subnormal = -f64::from_bits(1);
|
|
let cases: [(i32, f64); 6] = [
|
|
(day(1950, 1, 31), -0.0),
|
|
(day(1969, 12, 31), subnormal),
|
|
(day(1970, 1, 1), neg_subnormal),
|
|
(day(1999, 12, 31), f64::MAX),
|
|
(day(2000, 1, 31), f64::MIN),
|
|
(day(2024, 2, 29), -f64::MIN_POSITIVE),
|
|
];
|
|
// Feed in reverse so the stage must rely on the builder's ordering.
|
|
let points: Vec<TeDataPoint<'static>> = cases
|
|
.iter()
|
|
.rev()
|
|
.map(|&(d, v)| te_point("USCPI", "United States", "Inflation Rate", d, v))
|
|
.collect();
|
|
let tmp = TempDirGuard::new("extreme-values");
|
|
|
|
// Act
|
|
let report = curate_and_write_macro(
|
|
tmp.path(),
|
|
points,
|
|
|_: &str, _: &str, _: &str| Some(target("US", "cpi_yoy", MacroLagClass::MonthlyRelease)),
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.expect("extreme finite values are valid");
|
|
|
|
// Assert
|
|
assert_eq!(report.curate_stats.points_in, cases.len());
|
|
assert_eq!(report.curate_stats.rows_out, cases.len());
|
|
assert_eq!(report.curate_stats.series_out, 1);
|
|
assert_eq!(report.curate_stats.builder.skipped_non_finite_value, 0);
|
|
assert_stats_conserved(&report.curate_stats);
|
|
let expected: Vec<MacroParquetRow> = cases
|
|
.iter()
|
|
.map(|&(d, v)| expected_row("US", "cpi_yoy", d, MONTHLY_RELEASE_LAG_DAYS, v))
|
|
.collect();
|
|
let actual = read_parquet_rows(&tmp.path().join("macro").join("part.parquet"));
|
|
assert_rows_bitwise_eq(&actual, &expected);
|
|
assert_eq!(actual[0].value.to_bits(), (-0.0f64).to_bits());
|
|
assert!(
|
|
actual[0].known_at_micros < 0,
|
|
"pre-epoch known_at stays negative"
|
|
);
|
|
}
|