1391 lines
50 KiB
Rust
1391 lines
50 KiB
Rust
use std::borrow::Cow;
|
|
use std::error::Error as StdError;
|
|
use std::fs::{self, File};
|
|
use std::io;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::Duration;
|
|
|
|
use parquet::basic::{Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType};
|
|
use parquet::column::reader::ColumnReader;
|
|
use parquet::file::reader::{FileReader, SerializedFileReader};
|
|
|
|
use super::{
|
|
macro_parquet_schema, write_macro_dataset, write_macro_dataset_with_hooks, MacroParquetRow,
|
|
MacroWriteOptions, MacroWriteStats, ParquetMacroError,
|
|
};
|
|
use crate::macro_series::{
|
|
build_macro_rows, MacroLagClass, MacroObservation, MacroRow, MACRO_KNOWN_AT_SOURCE,
|
|
MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS,
|
|
};
|
|
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-pq-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_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_row_bitwise_eq(actual: &MacroParquetRow, expected: &MacroParquetRow) {
|
|
assert_eq!(actual.country_iso, expected.country_iso);
|
|
assert_eq!(actual.indicator, expected.indicator);
|
|
assert_eq!(actual.period_date, expected.period_date);
|
|
assert_eq!(actual.known_at_micros, expected.known_at_micros);
|
|
assert_eq!(actual.known_at_source, expected.known_at_source);
|
|
assert_eq!(actual.value.to_bits(), expected.value.to_bits());
|
|
}
|
|
|
|
fn assert_no_transient_files(dir: &Path) {
|
|
if !dir.exists() {
|
|
return;
|
|
}
|
|
for entry in fs::read_dir(dir).expect("read dir") {
|
|
let entry = entry.expect("dir entry");
|
|
let name = entry.file_name().to_string_lossy().into_owned();
|
|
assert!(
|
|
!name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock",
|
|
"unexpected transient file remaining: {}",
|
|
entry.path().display()
|
|
);
|
|
}
|
|
}
|
|
|
|
fn seed_existing(out_dir: &Path) -> (PathBuf, Vec<u8>) {
|
|
let seed = vec![
|
|
make_row("CA", "policy_rate", day(2024, 1, 24), POLICY_RATE_LAG_DAYS, 5.0),
|
|
make_row("US", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 3.1),
|
|
];
|
|
write_macro_dataset(out_dir, &seed, MacroWriteOptions::default()).unwrap();
|
|
let part = out_dir.join("macro/part.parquet");
|
|
let before = fs::read(&part).unwrap();
|
|
(part, before)
|
|
}
|
|
|
|
/// Pinned `build_macro_rows` fixture with 2 countries (`CA`, `US`), 2 indicators
|
|
/// (`cpi_yoy`, `policy_rate`), 2 lag classes (`MonthlyRelease`, `PolicyRate`),
|
|
/// negative values, and both `-0.0` and `+0.0` at distinct keys.
|
|
fn pinned_builder_fixture() -> Vec<MacroRow<String>> {
|
|
let observations = vec![
|
|
// Intentionally unsorted so `build_macro_rows` establishes canonical sort order.
|
|
MacroObservation {
|
|
country_iso: "US".to_string(),
|
|
indicator: "policy_rate".to_string(),
|
|
period_date: day(2024, 3, 20),
|
|
value: 5.5,
|
|
},
|
|
MacroObservation {
|
|
country_iso: "CA".to_string(),
|
|
indicator: "cpi_yoy".to_string(),
|
|
period_date: day(2024, 2, 29),
|
|
value: 0.0_f64,
|
|
},
|
|
MacroObservation {
|
|
country_iso: "CA".to_string(),
|
|
indicator: "cpi_yoy".to_string(),
|
|
period_date: day(2024, 1, 31),
|
|
value: -0.0_f64,
|
|
},
|
|
MacroObservation {
|
|
country_iso: "US".to_string(),
|
|
indicator: "cpi_yoy".to_string(),
|
|
period_date: day(2024, 1, 31),
|
|
value: -0.25,
|
|
},
|
|
MacroObservation {
|
|
country_iso: "CA".to_string(),
|
|
indicator: "policy_rate".to_string(),
|
|
period_date: day(2024, 3, 6),
|
|
value: 5.0,
|
|
},
|
|
];
|
|
|
|
let built = build_macro_rows(observations, |country, indicator| match (
|
|
country.as_str(),
|
|
indicator.as_str(),
|
|
) {
|
|
("CA" | "US", "policy_rate") => Some(MacroLagClass::PolicyRate),
|
|
("CA" | "US", "cpi_yoy") => Some(MacroLagClass::MonthlyRelease),
|
|
_ => None,
|
|
})
|
|
.expect("build_macro_rows fixture");
|
|
|
|
assert_eq!(built.rows.len(), 5);
|
|
assert_eq!(built.stats.emitted, 5);
|
|
built.rows
|
|
}
|
|
|
|
#[test]
|
|
fn schema_matches_contract_names_types_nullability_and_order() {
|
|
let schema = macro_parquet_schema().expect("build schema");
|
|
assert_eq!(schema.name(), "macro");
|
|
let fields = schema.get_fields();
|
|
assert_eq!(fields.len(), 6);
|
|
|
|
let expected: [(
|
|
&str,
|
|
PhysicalType,
|
|
Repetition,
|
|
Option<LogicalType>,
|
|
ConvertedType,
|
|
); 6] = [
|
|
(
|
|
"country_iso",
|
|
PhysicalType::BYTE_ARRAY,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::String),
|
|
ConvertedType::UTF8,
|
|
),
|
|
(
|
|
"indicator",
|
|
PhysicalType::BYTE_ARRAY,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::String),
|
|
ConvertedType::UTF8,
|
|
),
|
|
(
|
|
"period_date",
|
|
PhysicalType::INT32,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::Date),
|
|
ConvertedType::DATE,
|
|
),
|
|
(
|
|
"known_at",
|
|
PhysicalType::INT64,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
|
|
ConvertedType::TIMESTAMP_MICROS,
|
|
),
|
|
(
|
|
"known_at_source",
|
|
PhysicalType::BYTE_ARRAY,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::String),
|
|
ConvertedType::UTF8,
|
|
),
|
|
(
|
|
"value",
|
|
PhysicalType::DOUBLE,
|
|
Repetition::REQUIRED,
|
|
None,
|
|
ConvertedType::NONE,
|
|
),
|
|
];
|
|
|
|
for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() {
|
|
let f = &fields[idx];
|
|
assert_eq!(f.name(), name, "field {idx} name");
|
|
assert_eq!(f.get_physical_type(), phys, "field {name} physical type");
|
|
assert_eq!(
|
|
f.get_basic_info().repetition(),
|
|
rep,
|
|
"field {name} repetition"
|
|
);
|
|
assert_eq!(
|
|
f.get_basic_info().logical_type_ref().cloned(),
|
|
logical,
|
|
"field {name} logical type"
|
|
);
|
|
assert_eq!(
|
|
f.get_basic_info().converted_type(),
|
|
converted,
|
|
"field {name} converted type"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn build_macro_rows_round_trip_bitwise_and_written_file_schema_zstd() {
|
|
let tmp = TempDirGuard::new("round-trip");
|
|
let builder_rows = pinned_builder_fixture();
|
|
|
|
let parquet_rows: Vec<MacroParquetRow> = builder_rows
|
|
.iter()
|
|
.map(|r| {
|
|
let row = MacroParquetRow::from(r);
|
|
assert!(matches!(row.known_at_source, Cow::Borrowed(_)));
|
|
row
|
|
})
|
|
.collect();
|
|
|
|
// Verify `From<&MacroRow<&str>>` compiles and matches as well.
|
|
let borrowed_macro_row = MacroRow {
|
|
country_iso: "US",
|
|
indicator: "policy_rate",
|
|
period_date: day(2024, 3, 20),
|
|
known_at: i64::from(day(2024, 3, 21)) * MICROS_PER_DAY,
|
|
known_at_source: MACRO_KNOWN_AT_SOURCE,
|
|
value: 5.5,
|
|
};
|
|
let converted = MacroParquetRow::from(&borrowed_macro_row);
|
|
assert_eq!(converted.country_iso.as_ref(), "US");
|
|
assert_eq!(converted.known_at_micros, borrowed_macro_row.known_at);
|
|
|
|
let stats = write_macro_dataset(tmp.path(), &parquet_rows, MacroWriteOptions::default()).unwrap();
|
|
assert_eq!(stats.rows_written, 5);
|
|
assert_eq!(stats.files_written, 1);
|
|
assert_eq!(stats.row_groups_written, 1);
|
|
assert!(stats.bytes_written > 0);
|
|
|
|
let path = tmp.path().join("macro/part.parquet");
|
|
assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written);
|
|
|
|
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
|
let meta = reader.metadata();
|
|
assert_eq!(meta.file_metadata().num_rows(), 5);
|
|
assert_eq!(meta.num_row_groups(), 1);
|
|
|
|
// Inspect written file schema directly.
|
|
let file_fields = meta.file_metadata().schema().get_fields();
|
|
assert_eq!(file_fields.len(), 6);
|
|
assert_eq!(file_fields[0].name(), "country_iso");
|
|
assert_eq!(file_fields[1].name(), "indicator");
|
|
assert_eq!(file_fields[2].name(), "period_date");
|
|
assert_eq!(file_fields[3].name(), "known_at");
|
|
assert_eq!(file_fields[4].name(), "known_at_source");
|
|
assert_eq!(file_fields[5].name(), "value");
|
|
for f in file_fields {
|
|
assert_eq!(f.get_basic_info().repetition(), Repetition::REQUIRED);
|
|
}
|
|
assert_eq!(
|
|
file_fields[2].get_basic_info().logical_type_ref().cloned(),
|
|
Some(LogicalType::Date)
|
|
);
|
|
assert_eq!(
|
|
file_fields[3].get_basic_info().logical_type_ref().cloned(),
|
|
Some(LogicalType::timestamp(true, TimeUnit::MICROS))
|
|
);
|
|
assert_eq!(file_fields[5].get_physical_type(), PhysicalType::DOUBLE);
|
|
|
|
// Every column chunk must use Zstd compression.
|
|
for rg in meta.row_groups() {
|
|
for col in rg.columns() {
|
|
assert!(
|
|
matches!(col.compression(), Compression::ZSTD(_)),
|
|
"column {} expected ZSTD, got {:?}",
|
|
col.column_path(),
|
|
col.compression()
|
|
);
|
|
}
|
|
}
|
|
|
|
// Bitwise round-trip against `build_macro_rows` baseline.
|
|
let actual = read_parquet_rows(&path);
|
|
assert_eq!(actual.len(), builder_rows.len());
|
|
for (a, b) in actual.iter().zip(&builder_rows) {
|
|
assert_eq!(a.country_iso.as_ref(), b.country_iso.as_str());
|
|
assert_eq!(a.indicator.as_ref(), b.indicator.as_str());
|
|
assert_eq!(a.period_date, b.period_date);
|
|
assert_eq!(a.known_at_micros, b.known_at);
|
|
assert_eq!(a.known_at_source.as_ref(), MACRO_KNOWN_AT_SOURCE);
|
|
assert_eq!(a.value.to_bits(), b.value.to_bits());
|
|
}
|
|
|
|
// Explicitly verify `-0.0` vs `+0.0` bit preservation in the same row group,
|
|
// and exact UTC microseconds at expected lagged midnights.
|
|
assert_eq!(actual[0].country_iso.as_ref(), "CA");
|
|
assert_eq!(actual[0].indicator.as_ref(), "cpi_yoy");
|
|
assert_eq!(actual[0].value.to_bits(), (-0.0_f64).to_bits());
|
|
assert_eq!(
|
|
actual[0].known_at_micros,
|
|
i64::from(day(2024, 1, 31) + MONTHLY_RELEASE_LAG_DAYS) * MICROS_PER_DAY
|
|
);
|
|
|
|
assert_eq!(actual[1].country_iso.as_ref(), "CA");
|
|
assert_eq!(actual[1].indicator.as_ref(), "cpi_yoy");
|
|
assert_eq!(actual[1].value.to_bits(), (0.0_f64).to_bits());
|
|
assert_eq!(
|
|
actual[1].known_at_micros,
|
|
i64::from(day(2024, 2, 29) + MONTHLY_RELEASE_LAG_DAYS) * MICROS_PER_DAY
|
|
);
|
|
|
|
assert_eq!(actual[2].country_iso.as_ref(), "CA");
|
|
assert_eq!(actual[2].indicator.as_ref(), "policy_rate");
|
|
assert_eq!(
|
|
actual[2].known_at_micros,
|
|
i64::from(day(2024, 3, 6) + POLICY_RATE_LAG_DAYS) * MICROS_PER_DAY
|
|
);
|
|
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn multi_row_group_with_partial_final_group_matches_baseline_and_metadata() {
|
|
let tmp = TempDirGuard::new("multi-rg");
|
|
let builder_rows = pinned_builder_fixture();
|
|
let parquet_rows: Vec<MacroParquetRow> = builder_rows.iter().map(MacroParquetRow::from).collect();
|
|
|
|
// 5 rows with row_group_rows = 2 => 3 row groups: [2, 2, 1]
|
|
let opts = MacroWriteOptions {
|
|
row_group_rows: 2,
|
|
..MacroWriteOptions::default()
|
|
};
|
|
let stats = write_macro_dataset(tmp.path(), &parquet_rows, opts).unwrap();
|
|
assert_eq!(stats.rows_written, 5);
|
|
assert_eq!(stats.files_written, 1);
|
|
assert_eq!(stats.row_groups_written, 3);
|
|
|
|
let path = tmp.path().join("macro/part.parquet");
|
|
assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written);
|
|
|
|
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
|
let meta = reader.metadata();
|
|
assert_eq!(meta.file_metadata().num_rows(), 5);
|
|
assert_eq!(meta.num_row_groups(), 3);
|
|
let rg_sizes: Vec<i64> = (0..meta.num_row_groups())
|
|
.map(|i| meta.row_group(i).num_rows())
|
|
.collect();
|
|
assert_eq!(rg_sizes, vec![2, 2, 1]);
|
|
|
|
for rg in meta.row_groups() {
|
|
for col in rg.columns() {
|
|
assert!(
|
|
matches!(col.compression(), Compression::ZSTD(_)),
|
|
"column {} expected ZSTD, got {:?}",
|
|
col.column_path(),
|
|
col.compression()
|
|
);
|
|
}
|
|
}
|
|
|
|
let actual = read_parquet_rows(&path);
|
|
assert_eq!(actual.len(), parquet_rows.len());
|
|
for (a, e) in actual.iter().zip(&parquet_rows) {
|
|
assert_row_bitwise_eq(a, e);
|
|
}
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn string_columns_use_dictionary_encoding_and_output_is_deterministic() {
|
|
let tmp = TempDirGuard::new("dict-determinism");
|
|
let base = day(2024, 1, 1);
|
|
let rows: Vec<MacroParquetRow> = (0..64_i32)
|
|
.map(|i| {
|
|
let country = if i < 32 { "CA" } else { "US" };
|
|
let indicator = if (i % 32) < 16 { "cpi_yoy" } else { "policy_rate" };
|
|
make_row(
|
|
country,
|
|
indicator,
|
|
base + (i % 16),
|
|
POLICY_RATE_LAG_DAYS,
|
|
f64::from(i) * 0.125,
|
|
)
|
|
})
|
|
.collect();
|
|
|
|
let out_a = tmp.path().join("a");
|
|
let out_b = tmp.path().join("b");
|
|
let opts = MacroWriteOptions {
|
|
row_group_rows: 32,
|
|
..MacroWriteOptions::default()
|
|
};
|
|
write_macro_dataset(&out_a, &rows, opts).unwrap();
|
|
write_macro_dataset(&out_b, &rows, opts).unwrap();
|
|
|
|
let path_a = out_a.join("macro/part.parquet");
|
|
let path_b = out_b.join("macro/part.parquet");
|
|
assert_eq!(fs::read(&path_a).unwrap(), fs::read(&path_b).unwrap());
|
|
|
|
let reader = SerializedFileReader::new(File::open(&path_a).unwrap()).unwrap();
|
|
let rg0 = reader.metadata().row_group(0);
|
|
for (col_idx, name) in [
|
|
(0usize, "country_iso"),
|
|
(1usize, "indicator"),
|
|
(4usize, "known_at_source"),
|
|
] {
|
|
let col = rg0.column(col_idx);
|
|
assert!(
|
|
col.encodings().any(|e| {
|
|
matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)
|
|
}),
|
|
"expected dictionary encoding on {name}, got {:?}",
|
|
col.encodings().collect::<Vec<_>>()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn empty_input_returns_default_stats_and_preserves_fresh_and_seeded_destinations() {
|
|
let tmp = TempDirGuard::new("empty");
|
|
let fresh = tmp.path().join("fresh");
|
|
let stats = write_macro_dataset(
|
|
&fresh,
|
|
std::iter::empty::<MacroParquetRow>(),
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(stats, MacroWriteStats::default());
|
|
assert!(!fresh.exists(), "empty input must not create out_dir");
|
|
|
|
let seeded = tmp.path().join("seeded");
|
|
let (part, before) = seed_existing(&seeded);
|
|
let empty_stats = write_macro_dataset(
|
|
&seeded,
|
|
std::iter::empty::<MacroParquetRow>(),
|
|
MacroWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(empty_stats, MacroWriteStats::default());
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&seeded.join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_options_fail_closed_in_fresh_and_seeded_dirs() {
|
|
let tmp = TempDirGuard::new("bad-opts");
|
|
let fresh = tmp.path().join("fresh");
|
|
let seeded = tmp.path().join("seeded");
|
|
let (part, before) = seed_existing(&seeded);
|
|
let rows = vec![make_row(
|
|
"US",
|
|
"policy_rate",
|
|
day(2024, 3, 20),
|
|
POLICY_RATE_LAG_DAYS,
|
|
5.5,
|
|
)];
|
|
|
|
for (dir, is_fresh) in [(&fresh, true), (&seeded, false)] {
|
|
assert!(matches!(
|
|
write_macro_dataset(
|
|
dir,
|
|
&rows,
|
|
MacroWriteOptions {
|
|
row_group_rows: 0,
|
|
..MacroWriteOptions::default()
|
|
}
|
|
),
|
|
Err(ParquetMacroError::InvalidRowGroupRows)
|
|
));
|
|
// Even with empty input, invalid options must fail before returning default stats.
|
|
assert!(matches!(
|
|
write_macro_dataset(
|
|
dir,
|
|
std::iter::empty::<MacroParquetRow>(),
|
|
MacroWriteOptions {
|
|
row_group_rows: 0,
|
|
..MacroWriteOptions::default()
|
|
}
|
|
),
|
|
Err(ParquetMacroError::InvalidRowGroupRows)
|
|
));
|
|
assert!(matches!(
|
|
write_macro_dataset(
|
|
dir,
|
|
&rows,
|
|
MacroWriteOptions {
|
|
zstd_level: 23,
|
|
..MacroWriteOptions::default()
|
|
}
|
|
),
|
|
Err(ParquetMacroError::InvalidZstdLevel { level: 23 })
|
|
));
|
|
assert!(matches!(
|
|
write_macro_dataset(
|
|
dir,
|
|
&rows,
|
|
MacroWriteOptions {
|
|
zstd_level: 99,
|
|
..MacroWriteOptions::default()
|
|
}
|
|
),
|
|
Err(ParquetMacroError::InvalidZstdLevel { level: 99 })
|
|
));
|
|
|
|
if is_fresh {
|
|
assert!(!dir.exists(), "invalid options must not create out_dir");
|
|
} else {
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&dir.join("macro"));
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_inputs_return_typed_errors_in_fresh_and_seeded_dirs() {
|
|
let tmp = TempDirGuard::new("invalid-inputs");
|
|
let fresh = tmp.path().join("fresh");
|
|
let seeded = tmp.path().join("seeded");
|
|
let (part, before) = seed_existing(&seeded);
|
|
let d1 = day(2024, 1, 31);
|
|
let d2 = day(2024, 2, 29);
|
|
|
|
let check_both = |rows: &[MacroParquetRow], check: &dyn Fn(&ParquetMacroError)| {
|
|
let err_fresh =
|
|
write_macro_dataset(&fresh, rows, MacroWriteOptions::default()).unwrap_err();
|
|
check(&err_fresh);
|
|
assert!(
|
|
!fresh.join("macro/part.parquet").exists(),
|
|
"fresh dir must not contain part.parquet after error: {err_fresh}"
|
|
);
|
|
assert_no_transient_files(&fresh.join("macro"));
|
|
|
|
let err_seeded =
|
|
write_macro_dataset(&seeded, rows, MacroWriteOptions::default()).unwrap_err();
|
|
check(&err_seeded);
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&seeded.join("macro"));
|
|
};
|
|
|
|
// 1. Non-finite values: NaN, +inf, -inf
|
|
for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
|
let rows = vec![make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, bad_val)];
|
|
check_both(&rows, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::InvalidValue {
|
|
country_iso,
|
|
indicator,
|
|
period_date,
|
|
..
|
|
} if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1
|
|
),
|
|
"expected InvalidValue for {bad_val}, got {err:?}"
|
|
);
|
|
});
|
|
}
|
|
|
|
// 2. Empty / whitespace-only country_iso (first row and second row)
|
|
for bad_country in ["", " ", "\t\n"] {
|
|
let first_bad = vec![MacroParquetRow {
|
|
country_iso: Cow::Owned(bad_country.to_string()),
|
|
..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0)
|
|
}];
|
|
check_both(&first_bad, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::EmptyCountryIso { indicator, period_date }
|
|
if indicator == "cpi_yoy" && *period_date == d1
|
|
),
|
|
"expected EmptyCountryIso for {bad_country:?}, got {err:?}"
|
|
);
|
|
});
|
|
|
|
let second_bad = vec![
|
|
make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0),
|
|
MacroParquetRow {
|
|
country_iso: Cow::Owned(bad_country.to_string()),
|
|
..make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1)
|
|
},
|
|
];
|
|
check_both(&second_bad, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::EmptyCountryIso { indicator, period_date }
|
|
if indicator == "cpi_yoy" && *period_date == d2
|
|
),
|
|
"expected EmptyCountryIso on row 2 for {bad_country:?}, got {err:?}"
|
|
);
|
|
});
|
|
}
|
|
|
|
// 3. Empty / whitespace-only indicator (first row and second row)
|
|
for bad_indicator in ["", " ", "\t\n"] {
|
|
let first_bad = vec![MacroParquetRow {
|
|
indicator: Cow::Owned(bad_indicator.to_string()),
|
|
..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0)
|
|
}];
|
|
check_both(&first_bad, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::EmptyIndicator { country_iso, period_date }
|
|
if country_iso == "US" && *period_date == d1
|
|
),
|
|
"expected EmptyIndicator for {bad_indicator:?}, got {err:?}"
|
|
);
|
|
});
|
|
|
|
let second_bad = vec![
|
|
make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0),
|
|
MacroParquetRow {
|
|
indicator: Cow::Owned(bad_indicator.to_string()),
|
|
..make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1)
|
|
},
|
|
];
|
|
check_both(&second_bad, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::EmptyIndicator { country_iso, period_date }
|
|
if country_iso == "US" && *period_date == d2
|
|
),
|
|
"expected EmptyIndicator on row 2 for {bad_indicator:?}, got {err:?}"
|
|
);
|
|
});
|
|
}
|
|
|
|
// 4. Empty / whitespace-only known_at_source
|
|
for bad_source in ["", " ", "\t\n"] {
|
|
let rows = vec![MacroParquetRow {
|
|
known_at_source: Cow::Owned(bad_source.to_string()),
|
|
..make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0)
|
|
}];
|
|
check_both(&rows, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::EmptyKnownAtSource {
|
|
country_iso,
|
|
indicator,
|
|
period_date,
|
|
} if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1
|
|
),
|
|
"expected EmptyKnownAtSource for {bad_source:?}, got {err:?}"
|
|
);
|
|
});
|
|
}
|
|
|
|
// 5. Descending country_iso
|
|
let unsorted_country = vec![
|
|
make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0),
|
|
make_row("CA", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 2.8),
|
|
];
|
|
check_both(&unsorted_country, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::UnsortedInput {
|
|
prev_country_iso,
|
|
prev_indicator,
|
|
prev_period_date,
|
|
country_iso,
|
|
indicator,
|
|
period_date,
|
|
} if prev_country_iso == "US"
|
|
&& prev_indicator == "cpi_yoy"
|
|
&& *prev_period_date == d1
|
|
&& country_iso == "CA"
|
|
&& indicator == "cpi_yoy"
|
|
&& *period_date == d2
|
|
),
|
|
"expected UnsortedInput for descending country_iso, got {err:?}"
|
|
);
|
|
});
|
|
|
|
// 6. Descending indicator within same country_iso
|
|
let unsorted_indicator = vec![
|
|
make_row("CA", "policy_rate", d1, POLICY_RATE_LAG_DAYS, 5.0),
|
|
make_row("CA", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 2.8),
|
|
];
|
|
check_both(&unsorted_indicator, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::UnsortedInput {
|
|
prev_country_iso,
|
|
prev_indicator,
|
|
prev_period_date,
|
|
country_iso,
|
|
indicator,
|
|
period_date,
|
|
} if prev_country_iso == "CA"
|
|
&& prev_indicator == "policy_rate"
|
|
&& *prev_period_date == d1
|
|
&& country_iso == "CA"
|
|
&& indicator == "cpi_yoy"
|
|
&& *period_date == d2
|
|
),
|
|
"expected UnsortedInput for descending indicator, got {err:?}"
|
|
);
|
|
});
|
|
|
|
// 7. Descending period_date within same (country_iso, indicator)
|
|
let unsorted_date = vec![
|
|
make_row("US", "cpi_yoy", d2, MONTHLY_RELEASE_LAG_DAYS, 3.1),
|
|
make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0),
|
|
];
|
|
check_both(&unsorted_date, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::UnsortedInput {
|
|
prev_country_iso,
|
|
prev_indicator,
|
|
prev_period_date,
|
|
country_iso,
|
|
indicator,
|
|
period_date,
|
|
} if prev_country_iso == "US"
|
|
&& prev_indicator == "cpi_yoy"
|
|
&& *prev_period_date == d2
|
|
&& country_iso == "US"
|
|
&& indicator == "cpi_yoy"
|
|
&& *period_date == d1
|
|
),
|
|
"expected UnsortedInput for descending period_date, got {err:?}"
|
|
);
|
|
});
|
|
|
|
// 8. Duplicate (country_iso, indicator, period_date)
|
|
let duplicate = vec![
|
|
make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0),
|
|
make_row("US", "cpi_yoy", d1, MONTHLY_RELEASE_LAG_DAYS, 3.0),
|
|
];
|
|
check_both(&duplicate, &|err| {
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::DuplicateKey {
|
|
country_iso,
|
|
indicator,
|
|
period_date,
|
|
} if country_iso == "US" && indicator == "cpi_yoy" && *period_date == d1
|
|
),
|
|
"expected DuplicateKey, got {err:?}"
|
|
);
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn mid_stream_failures_after_flushed_row_groups_preserve_state_and_clean_staging() {
|
|
let tmp = TempDirGuard::new("mid-stream-fail");
|
|
let fresh = tmp.path().join("fresh");
|
|
let seeded = tmp.path().join("seeded");
|
|
let (part, before) = seed_existing(&seeded);
|
|
let base = day(2024, 1, 1);
|
|
|
|
let prefix = vec![
|
|
make_row("CA", "cpi_yoy", base, MONTHLY_RELEASE_LAG_DAYS, 2.5),
|
|
make_row("CA", "cpi_yoy", base + 1, MONTHLY_RELEASE_LAG_DAYS, 2.6),
|
|
make_row("CA", "policy_rate", base, POLICY_RATE_LAG_DAYS, 5.0),
|
|
make_row("CA", "policy_rate", base + 1, POLICY_RATE_LAG_DAYS, 5.0),
|
|
];
|
|
|
|
let opts = MacroWriteOptions {
|
|
row_group_rows: 2,
|
|
..MacroWriteOptions::default()
|
|
};
|
|
|
|
// Case A: Non-finite value on row 5 after 2 row groups have flushed.
|
|
let mut bad_val_rows = prefix.clone();
|
|
bad_val_rows.push(make_row(
|
|
"US",
|
|
"cpi_yoy",
|
|
base,
|
|
MONTHLY_RELEASE_LAG_DAYS,
|
|
f64::NAN,
|
|
));
|
|
|
|
// Case B: Descending key across row-group flush boundary.
|
|
let mut unsorted_rows = prefix.clone();
|
|
unsorted_rows.push(make_row(
|
|
"CA",
|
|
"policy_rate",
|
|
base,
|
|
POLICY_RATE_LAG_DAYS,
|
|
4.75,
|
|
));
|
|
|
|
// Case C: Duplicate key across row-group flush boundary.
|
|
let mut dup_rows = prefix;
|
|
dup_rows.push(make_row(
|
|
"CA",
|
|
"policy_rate",
|
|
base + 1,
|
|
POLICY_RATE_LAG_DAYS,
|
|
5.0,
|
|
));
|
|
|
|
for (rows, expected_kind) in [
|
|
(&bad_val_rows, "invalid_value"),
|
|
(&unsorted_rows, "unsorted"),
|
|
(&dup_rows, "duplicate"),
|
|
] {
|
|
let err_fresh = write_macro_dataset(&fresh, rows, opts).unwrap_err();
|
|
let err_seeded = write_macro_dataset(&seeded, rows, opts).unwrap_err();
|
|
|
|
for err in [&err_fresh, &err_seeded] {
|
|
match expected_kind {
|
|
"invalid_value" => assert!(matches!(err, ParquetMacroError::InvalidValue { .. })),
|
|
"unsorted" => assert!(matches!(err, ParquetMacroError::UnsortedInput { .. })),
|
|
"duplicate" => assert!(matches!(err, ParquetMacroError::DuplicateKey { .. })),
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
|
|
assert!(
|
|
!fresh.join("macro/part.parquet").exists(),
|
|
"fresh dir must not publish part.parquet on {expected_kind}"
|
|
);
|
|
assert_no_transient_files(&fresh.join("macro"));
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&seeded.join("macro"));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn overwrite_replaces_existing_part_parquet_and_cleans_backup() {
|
|
let tmp = TempDirGuard::new("overwrite");
|
|
let (part, before) = seed_existing(tmp.path());
|
|
|
|
let replacement = vec![
|
|
make_row("CA", "cpi_yoy", day(2025, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 1.9),
|
|
make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5),
|
|
];
|
|
let stats = write_macro_dataset(tmp.path(), &replacement, MacroWriteOptions::default()).unwrap();
|
|
assert_eq!(stats.rows_written, 2);
|
|
assert_eq!(stats.files_written, 1);
|
|
assert_eq!(stats.row_groups_written, 1);
|
|
|
|
let after = fs::read(&part).unwrap();
|
|
assert_ne!(after, before);
|
|
let actual = read_parquet_rows(&part);
|
|
assert_eq!(actual.len(), replacement.len());
|
|
for (a, e) in actual.iter().zip(&replacement) {
|
|
assert_row_bitwise_eq(a, e);
|
|
}
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn live_part_parquet_stays_readable_between_backup_and_rename() {
|
|
let tmp = TempDirGuard::new("live-readable");
|
|
let (part, before) = seed_existing(tmp.path());
|
|
|
|
let replacement = vec![make_row(
|
|
"US",
|
|
"policy_rate",
|
|
day(2025, 3, 19),
|
|
POLICY_RATE_LAG_DAYS,
|
|
4.25,
|
|
)];
|
|
let observed_live = Arc::new(Mutex::new(false));
|
|
let observed_clone = Arc::clone(&observed_live);
|
|
|
|
write_macro_dataset_with_hooks(
|
|
tmp.path(),
|
|
&replacement,
|
|
MacroWriteOptions::default(),
|
|
Duration::from_secs(5),
|
|
|final_path, backup_path| {
|
|
assert_eq!(final_path, part.as_path());
|
|
let bak = backup_path.expect("backup must be created for existing file");
|
|
assert!(bak.exists());
|
|
assert_eq!(fs::read(final_path).unwrap(), before);
|
|
assert_eq!(fs::read(bak).unwrap(), before);
|
|
*observed_clone.lock().unwrap() = true;
|
|
},
|
|
|path| fs::remove_file(path),
|
|
)
|
|
.unwrap();
|
|
|
|
assert!(*observed_live.lock().unwrap());
|
|
let actual = read_parquet_rows(&part);
|
|
assert_eq!(actual.len(), 1);
|
|
assert_row_bitwise_eq(&actual[0], &replacement[0]);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn stale_lock_times_out_and_backup_cleanup_failure_restores_previous_file() {
|
|
let tmp = TempDirGuard::new("lock-and-rollback");
|
|
let (part, before) = seed_existing(tmp.path());
|
|
let lock_path = tmp.path().join("macro/.write.lock");
|
|
fs::write(&lock_path, b"999999\n").unwrap();
|
|
|
|
let rows = vec![make_row(
|
|
"US",
|
|
"policy_rate",
|
|
day(2025, 5, 7),
|
|
POLICY_RATE_LAG_DAYS,
|
|
4.5,
|
|
)];
|
|
let err = write_macro_dataset_with_hooks(
|
|
tmp.path(),
|
|
&rows,
|
|
MacroWriteOptions::default(),
|
|
Duration::from_millis(30),
|
|
|_, _| {},
|
|
|path| fs::remove_file(path),
|
|
)
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(err, ParquetMacroError::LockTimeout { ref path, .. } if path == &lock_path),
|
|
"expected LockTimeout, got {err:?}"
|
|
);
|
|
assert!(lock_path.exists(), "stale lock must remain untouched");
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
fs::remove_file(&lock_path).unwrap();
|
|
|
|
// Simulate backup removal failure: previous file must be restored from backup.
|
|
let err2 = write_macro_dataset_with_hooks(
|
|
tmp.path(),
|
|
&rows,
|
|
MacroWriteOptions::default(),
|
|
Duration::from_secs(5),
|
|
|_, _| {},
|
|
|_bak| Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected")),
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(err2, ParquetMacroError::Io { .. }));
|
|
assert!(StdError::source(&err2).is_some());
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// QA (T-173) edge cases: builder/writer ordering agreement, extreme values,
|
|
// owned iterators, I/O blockers, rename failure, concurrency, panic unwind,
|
|
// and rollback failure reporting.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// `build_macro_rows` sorts by `K: Ord` (byte order for `String`); the writer must accept
|
|
/// every builder output, including prefix keys (`US` < `USA`), uppercase before lowercase,
|
|
/// and non-ASCII UTF-8, and round-trip it bit-for-bit across all four lag classes.
|
|
#[test]
|
|
fn builder_byte_order_keys_and_all_lag_classes_are_accepted_and_round_trip() {
|
|
let tmp = TempDirGuard::new("builder-order");
|
|
let base = day(2023, 12, 31);
|
|
let obs = |c: &str, i: &str, d: i32, v: f64| MacroObservation {
|
|
country_iso: c.to_string(),
|
|
indicator: i.to_string(),
|
|
period_date: d,
|
|
value: v,
|
|
};
|
|
let observations = vec![
|
|
obs("USA", "gdp_q", base, 1.0),
|
|
obs("US", "gdp_q", base, 2.0),
|
|
obs("US", "Gdp_q", base, 3.0),
|
|
obs("US", "gdp_q_é", base, 4.0),
|
|
obs("US", "gdp_q", base - 1, f64::MIN_POSITIVE / 2.0), // subnormal
|
|
obs("CA", "rate", base, f64::MAX),
|
|
obs("CA", "rate", base + 1, -f64::MAX),
|
|
];
|
|
let built = build_macro_rows(observations, |_, indicator| match indicator.as_str() {
|
|
"gdp_q" => Some(MacroLagClass::Gdp65),
|
|
"Gdp_q" => Some(MacroLagClass::Gdp90),
|
|
"gdp_q_é" => Some(MacroLagClass::MonthlyRelease),
|
|
"rate" => Some(MacroLagClass::PolicyRate),
|
|
_ => None,
|
|
})
|
|
.expect("builder");
|
|
assert_eq!(built.rows.len(), 7);
|
|
|
|
let rows: Vec<MacroParquetRow> = built.rows.iter().map(MacroParquetRow::from).collect();
|
|
// row_group_rows = 3 so ordering is checked across flush boundaries too.
|
|
let opts = MacroWriteOptions {
|
|
row_group_rows: 3,
|
|
..MacroWriteOptions::default()
|
|
};
|
|
let stats = write_macro_dataset(tmp.path(), &rows, opts).expect("builder output accepted");
|
|
assert_eq!(stats.rows_written, 7);
|
|
assert_eq!(stats.row_groups_written, 3);
|
|
|
|
let actual = read_parquet_rows(&tmp.path().join("macro/part.parquet"));
|
|
assert_eq!(actual.len(), built.rows.len());
|
|
for (a, b) in actual.iter().zip(&built.rows) {
|
|
assert_eq!(a.country_iso.as_ref(), b.country_iso.as_str());
|
|
assert_eq!(a.indicator.as_ref(), b.indicator.as_str());
|
|
assert_eq!(a.period_date, b.period_date);
|
|
assert_eq!(a.known_at_micros, b.known_at);
|
|
assert_eq!(a.known_at_source.as_ref(), b.known_at_source);
|
|
assert_eq!(a.value.to_bits(), b.value.to_bits());
|
|
}
|
|
let order: Vec<(&str, &str)> = actual
|
|
.iter()
|
|
.map(|r| (r.country_iso.as_ref(), r.indicator.as_ref()))
|
|
.collect();
|
|
assert_eq!(
|
|
order,
|
|
vec![
|
|
("CA", "rate"),
|
|
("CA", "rate"),
|
|
("US", "Gdp_q"),
|
|
("US", "gdp_q"),
|
|
("US", "gdp_q"),
|
|
("US", "gdp_q_é"),
|
|
("USA", "gdp_q"),
|
|
]
|
|
);
|
|
// Gdp90 lag preserved exactly.
|
|
assert_eq!(
|
|
actual[2].known_at_micros,
|
|
i64::from(base + 90) * MICROS_PER_DAY
|
|
);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
/// The writer stores `period_date`/`known_at` verbatim; it must not reject or alter
|
|
/// pre-1970 or extreme integers (bounds are the builder's job).
|
|
#[test]
|
|
fn extreme_dates_and_timestamps_round_trip_verbatim_with_owned_iterator() {
|
|
let tmp = TempDirGuard::new("extremes");
|
|
let rows = vec![
|
|
MacroParquetRow {
|
|
period_date: i32::MIN,
|
|
known_at_micros: i64::MIN,
|
|
..make_row("AA", "x", 0, 0, 1.5)
|
|
},
|
|
MacroParquetRow {
|
|
known_at_micros: -1,
|
|
..make_row("AA", "x", -1, 0, -1.5)
|
|
},
|
|
MacroParquetRow {
|
|
period_date: i32::MAX,
|
|
known_at_micros: i64::MAX,
|
|
..make_row("AA", "x", 0, 0, 0.1)
|
|
},
|
|
];
|
|
// Owned (by-value) iterator path.
|
|
let stats =
|
|
write_macro_dataset(tmp.path(), rows.clone().into_iter(), MacroWriteOptions::default())
|
|
.unwrap();
|
|
assert_eq!(stats.rows_written, 3);
|
|
let actual = read_parquet_rows(&tmp.path().join("macro/part.parquet"));
|
|
assert_eq!(actual.len(), 3);
|
|
for (a, e) in actual.iter().zip(&rows) {
|
|
assert_row_bitwise_eq(a, e);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn out_dir_or_macro_dir_occupied_by_regular_file_returns_io_error() {
|
|
let tmp = TempDirGuard::new("io-blocker");
|
|
let rows = vec![make_row("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5)];
|
|
|
|
let file_as_out = tmp.path().join("not-a-dir");
|
|
fs::write(&file_as_out, b"sentinel").unwrap();
|
|
let err = write_macro_dataset(&file_as_out, &rows, MacroWriteOptions::default()).unwrap_err();
|
|
assert!(matches!(err, ParquetMacroError::Io { .. }), "got {err:?}");
|
|
assert!(StdError::source(&err).is_some());
|
|
assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel");
|
|
|
|
let out = tmp.path().join("macro-is-file");
|
|
fs::create_dir_all(&out).unwrap();
|
|
let macro_file = out.join("macro");
|
|
fs::write(¯o_file, b"file-not-dir").unwrap();
|
|
let err2 = write_macro_dataset(&out, &rows, MacroWriteOptions::default()).unwrap_err();
|
|
assert!(matches!(err2, ParquetMacroError::Io { .. }), "got {err2:?}");
|
|
assert_eq!(fs::read(¯o_file).unwrap(), b"file-not-dir");
|
|
}
|
|
|
|
#[test]
|
|
fn rename_failure_over_directory_blocker_cleans_up_staging_and_preserves_unowned_tmp() {
|
|
let tmp = TempDirGuard::new("rename-blocker");
|
|
let macro_dir = tmp.path().join("macro");
|
|
let blocking_dir = macro_dir.join("part.parquet");
|
|
fs::create_dir_all(&blocking_dir).unwrap();
|
|
let unowned_tmp = macro_dir.join("part.parquet.unowned-other-run.tmp");
|
|
fs::write(&unowned_tmp, b"keep-me").unwrap();
|
|
|
|
let rows = vec![make_row("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5)];
|
|
let err = write_macro_dataset(tmp.path(), &rows, MacroWriteOptions::default()).unwrap_err();
|
|
assert!(matches!(err, ParquetMacroError::Io { .. }), "got {err:?}");
|
|
assert!(blocking_dir.is_dir(), "directory blocker must remain intact");
|
|
assert_eq!(fs::read(&unowned_tmp).unwrap(), b"keep-me");
|
|
|
|
let mut entries: Vec<String> = fs::read_dir(¯o_dir)
|
|
.unwrap()
|
|
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
|
.collect();
|
|
entries.sort();
|
|
assert_eq!(
|
|
entries,
|
|
vec![
|
|
"part.parquet".to_string(),
|
|
"part.parquet.unowned-other-run.tmp".to_string(),
|
|
]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn concurrent_in_process_writers_serialize_to_one_generation() {
|
|
let tmp = TempDirGuard::new("concurrent");
|
|
let out = Arc::new(tmp.path().to_path_buf());
|
|
let base = day(2024, 1, 31);
|
|
|
|
let out_1 = Arc::clone(&out);
|
|
let h1 = std::thread::spawn(move || {
|
|
let iter = (0..2_i32).map(move |i| {
|
|
if i == 1 {
|
|
std::thread::sleep(Duration::from_millis(30));
|
|
}
|
|
make_row("CA", "cpi_yoy", base + i, MONTHLY_RELEASE_LAG_DAYS, 2.0)
|
|
});
|
|
write_macro_dataset(out_1.as_path(), iter, MacroWriteOptions::default())
|
|
});
|
|
std::thread::sleep(Duration::from_millis(5));
|
|
let out_2 = Arc::clone(&out);
|
|
let h2 = std::thread::spawn(move || {
|
|
let iter = (0..2_i32)
|
|
.map(move |i| make_row("US", "policy_rate", base + i, POLICY_RATE_LAG_DAYS, 5.5));
|
|
write_macro_dataset(out_2.as_path(), iter, MacroWriteOptions::default())
|
|
});
|
|
|
|
assert_eq!(h1.join().unwrap().unwrap().rows_written, 2);
|
|
assert_eq!(h2.join().unwrap().unwrap().rows_written, 2);
|
|
|
|
let got = read_parquet_rows(&tmp.path().join("macro/part.parquet"));
|
|
assert_eq!(got.len(), 2);
|
|
assert!(
|
|
got.iter().all(|r| r.country_iso == "CA") || got.iter().all(|r| r.country_iso == "US"),
|
|
"output must come entirely from one writer generation"
|
|
);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn panicking_iterator_after_flush_cleans_staging_releases_lock_and_preserves_live_file() {
|
|
let tmp = TempDirGuard::new("panic-unwind");
|
|
let (part, before) = seed_existing(tmp.path());
|
|
let out = tmp.path().to_path_buf();
|
|
let opts = MacroWriteOptions {
|
|
row_group_rows: 2,
|
|
..MacroWriteOptions::default()
|
|
};
|
|
let result = std::panic::catch_unwind(move || {
|
|
let base = day(2024, 1, 31);
|
|
let iter = (0..5_i32).map(move |i| {
|
|
if i == 3 {
|
|
panic!("simulated iterator panic after row-group flush");
|
|
}
|
|
make_row("US", "cpi_yoy", base + i, MONTHLY_RELEASE_LAG_DAYS, 3.0)
|
|
});
|
|
let _ = write_macro_dataset(&out, iter, opts);
|
|
});
|
|
assert!(result.is_err(), "iterator must have panicked");
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
|
|
// Next writer proceeds without hitting a stale lock.
|
|
let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)];
|
|
let stats = write_macro_dataset(tmp.path(), &replacement, MacroWriteOptions::default()).unwrap();
|
|
assert_eq!(stats.rows_written, 1);
|
|
let got = read_parquet_rows(&part);
|
|
assert_eq!(got.len(), 1);
|
|
assert_row_bitwise_eq(&got[0], &replacement[0]);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn backup_unlink_and_restore_failure_reports_rollback_failed() {
|
|
let tmp = TempDirGuard::new("rollback-failed");
|
|
let (part, _before) = seed_existing(tmp.path());
|
|
let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)];
|
|
let observed_bak: Arc<Mutex<Option<PathBuf>>> = Arc::new(Mutex::new(None));
|
|
let observed_clone = Arc::clone(&observed_bak);
|
|
|
|
let err = write_macro_dataset_with_hooks(
|
|
tmp.path(),
|
|
&replacement,
|
|
MacroWriteOptions::default(),
|
|
Duration::from_secs(5),
|
|
|_, _| {},
|
|
move |bak| {
|
|
*observed_clone.lock().unwrap() = Some(bak.to_path_buf());
|
|
// Remove the backup so the restore rename also fails.
|
|
let _ = fs::remove_file(bak);
|
|
Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected"))
|
|
},
|
|
)
|
|
.unwrap_err();
|
|
|
|
let expected_bak = observed_bak.lock().unwrap().clone().expect("hook called");
|
|
match err {
|
|
ParquetMacroError::RollbackFailed { cause, failures } => {
|
|
assert!(
|
|
matches!(
|
|
*cause,
|
|
ParquetMacroError::Io { ref path, ref source }
|
|
if path == &expected_bak
|
|
&& source.kind() == io::ErrorKind::PermissionDenied
|
|
),
|
|
"unexpected cause: {cause:?}"
|
|
);
|
|
assert_eq!(failures.len(), 1);
|
|
assert_eq!(failures[0].final_path, part);
|
|
assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path()));
|
|
assert_eq!(failures[0].source.kind(), io::ErrorKind::NotFound);
|
|
}
|
|
other => panic!("expected RollbackFailed, got {other:?}"),
|
|
}
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn backup_unlink_failure_error_names_backup_path_and_restores_live_bytes() {
|
|
let tmp = TempDirGuard::new("bak-unlink-path");
|
|
let (part, before) = seed_existing(tmp.path());
|
|
let replacement = vec![make_row("US", "policy_rate", day(2025, 1, 29), POLICY_RATE_LAG_DAYS, 4.5)];
|
|
let observed_bak: Arc<Mutex<Option<PathBuf>>> = Arc::new(Mutex::new(None));
|
|
let observed_clone = Arc::clone(&observed_bak);
|
|
|
|
let err = write_macro_dataset_with_hooks(
|
|
tmp.path(),
|
|
&replacement,
|
|
MacroWriteOptions::default(),
|
|
Duration::from_secs(5),
|
|
|_, _| {},
|
|
move |bak| {
|
|
*observed_clone.lock().unwrap() = Some(bak.to_path_buf());
|
|
Err(io::Error::new(io::ErrorKind::PermissionDenied, "injected"))
|
|
},
|
|
)
|
|
.unwrap_err();
|
|
let expected_bak = observed_bak.lock().unwrap().clone().expect("hook called");
|
|
assert!(
|
|
matches!(
|
|
err,
|
|
ParquetMacroError::Io { ref path, ref source }
|
|
if path == &expected_bak && source.kind() == io::ErrorKind::PermissionDenied
|
|
),
|
|
"got {err:?}"
|
|
);
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&tmp.path().join("macro"));
|
|
}
|
|
|
|
#[test]
|
|
fn error_display_messages_name_offending_key() {
|
|
let e = ParquetMacroError::DuplicateKey {
|
|
country_iso: "US".into(),
|
|
indicator: "cpi_yoy".into(),
|
|
period_date: 19_753,
|
|
};
|
|
assert!(e.to_string().contains("(US, cpi_yoy, 19753)"), "{e}");
|
|
let e = ParquetMacroError::InvalidValue {
|
|
country_iso: "CA".into(),
|
|
indicator: "rate".into(),
|
|
period_date: 1,
|
|
value: f64::NAN,
|
|
};
|
|
let msg = e.to_string();
|
|
assert!(msg.contains("NaN") && msg.contains("must be finite"), "{msg}");
|
|
assert!(StdError::source(&e).is_none());
|
|
}
|