From 056268e945fc92631c69d867d51738ebc32458bc Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 14:58:34 -0500 Subject: [PATCH] =?UTF-8?q?T-173:=20M2.2o=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20Zstd=20Parquet=20writer=20for=20`macro/part.parquet`=20(`Ma?= =?UTF-8?q?croRow`=20=E2=86=92=20`MacroParquetRow`=20=E2=86=92=20`write=5F?= =?UTF-8?q?macro=5Fdataset`,=206-column=20contract=20schema,=20atomic=20pu?= =?UTF-8?q?blish)=20in=20`parquet=5Fmacro.rs`=20with=20round-trip=20tests?= =?UTF-8?q?=20(no=20new=20crates,=20no=20CLI/bench/stream=20changes,=20no?= =?UTF-8?q?=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 2 +- tools/curate-etl/src/lib.rs | 5 + tools/curate-etl/src/parquet_macro.rs | 776 ++++++++++++++ tools/curate-etl/src/parquet_macro_tests.rs | 1060 +++++++++++++++++++ 4 files changed, 1842 insertions(+), 1 deletion(-) create mode 100644 tools/curate-etl/src/parquet_macro.rs create mode 100644 tools/curate-etl/src/parquet_macro_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index bbaaa394..46ab00fb 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1673,4 +1673,4 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`). - **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`). - **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`. -- **Deferred:** `teData` BSON decoding, `macro/part.parquet` writer, 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>`) atomically to `/macro/part.parquet` (6-column Zstd contract schema); deferred: `teData` BSON decoding, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access. diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a561edc3..98e1a8ce 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -30,6 +30,7 @@ pub mod parquet_corporate_actions; pub mod parquet_events; pub mod parquet_fundamentals; pub mod parquet_fx; +pub mod parquet_macro; pub mod parquet_posts; mod parquet_publish; pub mod parquet_shorts; @@ -194,6 +195,10 @@ pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, }; +pub use parquet_macro::{ + macro_parquet_schema, write_macro_dataset, MacroParquetRow, MacroWriteOptions, MacroWriteStats, + ParquetMacroError, +}; pub use parquet_posts::{ posts_to_event_rows, EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, diff --git a/tools/curate-etl/src/parquet_macro.rs b/tools/curate-etl/src/parquet_macro.rs new file mode 100644 index 00000000..d2a21f3e --- /dev/null +++ b/tools/curate-etl/src/parquet_macro.rs @@ -0,0 +1,776 @@ +//! Streaming, atomic Zstd Parquet writer for `macro`. +//! +//! Writes `/macro/part.parquet` matching the 6-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `country_iso` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 2. `indicator` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 3. `period_date` (`INT32`, `REQUIRED`, `DATE`) +//! 4. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 5. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 6. `value` (`DOUBLE`, `REQUIRED`) +//! +//! ## Timestamp Units & Provenance +//! [`crate::macro_series::MacroRow::known_at`] is already in UTC microseconds since +//! `1970-01-01T00:00:00Z` (`00:00:00 UTC` of `period_date + lag_days`), so +//! `From<&MacroRow>` copies it directly into [`MacroParquetRow::known_at_micros`] +//! without unit conversion and preserves `known_at_source` and `value` bit-for-bit. + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::macro_series::MacroRow; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_f64_col, write_i32_col, write_i64_col, write_interned_str_col, DatasetFileLock, + PublishIoError, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, + FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; + +/// Single `macro` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct MacroParquetRow { + pub country_iso: Cow<'static, str>, + pub indicator: Cow<'static, str>, + /// Observation period date as days since `1970-01-01` (UTC Gregorian). + pub period_date: i32, + /// Estimated point-in-time availability timestamp in UTC microseconds since + /// `1970-01-01T00:00:00Z`. + pub known_at_micros: i64, + pub known_at_source: Cow<'static, str>, + pub value: f64, +} + +impl> From<&MacroRow> for MacroParquetRow { + #[inline] + fn from(row: &MacroRow) -> Self { + Self { + country_iso: Cow::Owned(row.country_iso.as_ref().to_owned()), + indicator: Cow::Owned(row.indicator.as_ref().to_owned()), + period_date: row.period_date, + // MacroRow.known_at is already UTC epoch microseconds. + known_at_micros: row.known_at, + known_at_source: Cow::Borrowed(row.known_at_source), + value: row.value, + } + } +} + +/// Configuration for [`write_macro_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MacroWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for MacroWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_macro_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MacroWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed error returned by [`write_macro_dataset`]. +#[derive(Debug)] +pub enum ParquetMacroError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_country_iso: String, + prev_indicator: String, + prev_period_date: i32, + country_iso: String, + indicator: String, + period_date: i32, + }, + DuplicateKey { + country_iso: String, + indicator: String, + period_date: i32, + }, + EmptyCountryIso { + indicator: String, + period_date: i32, + }, + EmptyIndicator { + country_iso: String, + period_date: i32, + }, + EmptyKnownAtSource { + country_iso: String, + indicator: String, + period_date: i32, + }, + InvalidValue { + country_iso: String, + indicator: String, + period_date: i32, + value: f64, + }, + LockTimeout { + path: PathBuf, + waited: Duration, + }, + RollbackFailed { + cause: Box, + failures: Vec, + }, + Io { + path: PathBuf, + source: io::Error, + }, + Parquet { + path: PathBuf, + source: ParquetError, + }, +} + +impl fmt::Display for ParquetMacroError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_country_iso, + prev_indicator, + prev_period_date, + country_iso, + indicator, + period_date, + } => write!( + f, + "unsorted input: ({country_iso}, {indicator}, {period_date}) follows ({prev_country_iso}, {prev_indicator}, {prev_period_date})" + ), + Self::DuplicateKey { + country_iso, + indicator, + period_date, + } => write!( + f, + "duplicate (country_iso, indicator, period_date) key: ({country_iso}, {indicator}, {period_date})" + ), + Self::EmptyCountryIso { + indicator, + period_date, + } => write!( + f, + "empty country_iso for ({indicator}, {period_date}): must be non-empty" + ), + Self::EmptyIndicator { + country_iso, + period_date, + } => write!( + f, + "empty indicator for ({country_iso}, {period_date}): must be non-empty" + ), + Self::EmptyKnownAtSource { + country_iso, + indicator, + period_date, + } => write!( + f, + "empty known_at_source for ({country_iso}, {indicator}, {period_date}): must be non-empty" + ), + Self::InvalidValue { + country_iso, + indicator, + period_date, + value, + } => write!( + f, + "invalid value ({value}) for ({country_iso}, {indicator}, {period_date}): must be finite" + ), + Self::LockTimeout { path, waited } => write!( + f, + "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", + waited.as_millis(), + path.display() + ), + Self::RollbackFailed { cause, failures } => { + write!( + f, + "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", + failures.len() + )?; + for failure in failures { + write!(f, " [{failure}]")?; + } + Ok(()) + } + Self::Io { path, source } => { + write!(f, "I/O error at '{}': {source}", path.display()) + } + Self::Parquet { path, source } => { + write!(f, "Parquet error at '{}': {source}", path.display()) + } + } + } +} + +impl Error for ParquetMacroError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), + Self::Io { source, .. } => Some(source), + Self::Parquet { source, .. } => Some(source), + _ => None, + } + } +} + +impl From for ParquetMacroError { + fn from(err: PublishIoError) -> Self { + match err { + PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, + PublishIoError::Io { path, source } => Self::Io { path, source }, + } + } +} + +/// Builds the exact 6-column Parquet schema for `macro` per `design/DATA-CONTRACTS.md` (§3A). +pub fn macro_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("country_iso", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("indicator", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("period_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("value", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("macro") + .with_fields(fields) + .build()?, + )) +} + +fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { + Arc::new( + WriterProperties::builder() + .set_compression(Compression::ZSTD(zstd_level)) + .set_column_dictionary_enabled(ColumnPath::from("country_iso"), true) + .set_column_dictionary_enabled(ColumnPath::from("indicator"), true) + .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn validate_row(row: &MacroParquetRow) -> Result<(), ParquetMacroError> { + if row.country_iso.trim().is_empty() { + return Err(ParquetMacroError::EmptyCountryIso { + indicator: row.indicator.as_ref().to_owned(), + period_date: row.period_date, + }); + } + if row.indicator.trim().is_empty() { + return Err(ParquetMacroError::EmptyIndicator { + country_iso: row.country_iso.as_ref().to_owned(), + period_date: row.period_date, + }); + } + if row.known_at_source.trim().is_empty() { + return Err(ParquetMacroError::EmptyKnownAtSource { + country_iso: row.country_iso.as_ref().to_owned(), + indicator: row.indicator.as_ref().to_owned(), + period_date: row.period_date, + }); + } + if !row.value.is_finite() { + return Err(ParquetMacroError::InvalidValue { + country_iso: row.country_iso.as_ref().to_owned(), + indicator: row.indicator.as_ref().to_owned(), + period_date: row.period_date, + value: row.value, + }); + } + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + country_iso_ids: Vec, + country_iso_interner: StringInterner, + indicator_ids: Vec, + indicator_interner: StringInterner, + period_date: Vec, + known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, + value: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.period_date.len() + } + + fn push(&mut self, row: &MacroParquetRow) { + let country_iso_id = self.country_iso_interner.intern(row.country_iso.as_ref()); + self.country_iso_ids.push(country_iso_id); + let indicator_id = self.indicator_interner.intern(row.indicator.as_ref()); + self.indicator_ids.push(indicator_id); + self.period_date.push(row.period_date); + self.known_at_micros.push(row.known_at_micros); + let known_at_source_id = self + .known_at_source_interner + .intern(row.known_at_source.as_ref()); + self.known_at_source_ids.push(known_at_source_id); + self.value.push(row.value); + } + + fn clear(&mut self) { + self.country_iso_ids.clear(); + self.country_iso_interner.clear(); + self.indicator_ids.clear(); + self.indicator_interner.clear(); + self.period_date.clear(); + self.known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + self.value.clear(); + } +} + +struct MacroFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl MacroFileWriter { + fn from_file( + tmp_path: PathBuf, + final_path: PathBuf, + file: File, + schema: &TypePtr, + props: &WriterPropertiesPtr, + ) -> Result { + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetMacroError::Parquet { + path: tmp_path.clone(), + source, + }, + )?; + + Ok(Self { + tmp_path, + final_path, + writer, + buf: RowGroupBuffer::default(), + rows_written: 0, + row_groups_written: 0, + }) + } + + fn flush_row_group(&mut self, scratch: &mut Vec) -> Result<(), ParquetMacroError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetMacroError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. country_iso (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.country_iso_ids, + &self.buf.country_iso_interner, + scratch, + ) + .map_err(map_pq)?; + // 2. indicator (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.indicator_ids, + &self.buf.indicator_interner, + scratch, + ) + .map_err(map_pq)?; + // 3. period_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.period_date).map_err(map_pq)?; + // 4. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + // 5. known_at_source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.known_at_source_ids, + &self.buf.known_at_source_interner, + scratch, + ) + .map_err(map_pq)?; + // 6. value (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.value, None).map_err(map_pq)?; + + rg_writer.close().map_err(map_pq)?; + + self.rows_written += row_count; + self.row_groups_written += 1; + self.buf.clear(); + Ok(()) + } + + fn finish_and_sync( + mut self, + scratch: &mut Vec, + ) -> Result { + self.flush_row_group(scratch)?; + + let mut buf_writer = + self.writer + .into_inner() + .map_err(|source| ParquetMacroError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetMacroError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetMacroError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetMacroError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetMacroError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedMacroFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedMacroFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams strictly ascending `(country_iso, indicator, period_date)` rows into a single Zstd +/// Parquet file at `/macro/part.parquet`. +/// +/// # Empty Input +/// Empty input (with valid options) returns `Ok(MacroWriteStats::default())` without creating +/// `/macro` and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/macro` directory are serialized via an +/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is +/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive +/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a +/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run +/// is cleaned up (reporting cleanup failures via [`ParquetMacroError::RollbackFailed`]), and +/// only staging files owned by this run are unlinked. +pub fn write_macro_dataset( + out_dir: P, + rows: I, + options: MacroWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_macro_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + |path| fs::remove_file(path), + ) +} + +fn write_macro_dataset_with_hooks( + out_dir: P, + rows: I, + options: MacroWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, + mut remove_backup: Rm, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), + Rm: FnMut(&Path) -> io::Result<()>, +{ + if options.row_group_rows == 0 { + return Err(ParquetMacroError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetMacroError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(MacroWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let macro_dir = out_dir.join("macro"); + let schema = macro_parquet_schema().map_err(|source| ParquetMacroError::Parquet { + path: macro_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(¯o_dir).map_err(|source| ParquetMacroError::Io { + path: macro_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(¯o_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(¯o_dir, lock_timeout)?; + + let run_id = next_run_id(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(¯o_dir, &run_id)?; + // Declared before `file_writer` so Rust's reverse drop order closes the file handle + // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` + // and `_in_process_guard` are still held. + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(MacroFileWriter::from_file( + tmp_path, + macro_dir.join("part.parquet"), + tmp_file, + &schema, + &props, + )?); + + let synced = { + let mut has_prev = false; + let mut prev_country_iso = String::new(); + let mut prev_indicator = String::new(); + let mut prev_period_date = 0i32; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + // Validate row fields before checking sort order so e.g. an empty country_iso + // or indicator is reported as EmptyCountryIso/EmptyIndicator rather than UnsortedInput. + validate_row(row)?; + let country_iso = row.country_iso.as_ref(); + let indicator = row.indicator.as_ref(); + if has_prev { + match (country_iso, indicator, row.period_date).cmp(&( + prev_country_iso.as_str(), + prev_indicator.as_str(), + prev_period_date, + )) { + Ordering::Equal => { + return Err(ParquetMacroError::DuplicateKey { + country_iso: country_iso.to_owned(), + indicator: indicator.to_owned(), + period_date: row.period_date, + }); + } + Ordering::Less => { + return Err(ParquetMacroError::UnsortedInput { + prev_country_iso, + prev_indicator, + prev_period_date, + country_iso: country_iso.to_owned(), + indicator: indicator.to_owned(), + period_date: row.period_date, + }); + } + Ordering::Greater => {} + } + } + if !has_prev || country_iso != prev_country_iso.as_str() { + prev_country_iso.clear(); + prev_country_iso.push_str(country_iso); + } + if !has_prev || indicator != prev_indicator.as_str() { + prev_indicator.clear(); + prev_indicator.push_str(indicator); + } + prev_period_date = row.period_date; + has_prev = true; + + writer.buf.push(row); + if writer.buf.len() == options.row_group_rows { + writer.flush_row_group(&mut scratch)?; + } + } + + let writer = file_writer.take().expect("writer still present"); + writer.finish_and_sync(&mut scratch)? + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + Some(create_backup_preserving_live(&synced.final_path, &run_id)?) + } + // Directory occupying final_path: leave it in place so the rename below fails cleanly. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetMacroError::Io { + path: synced.final_path, + source, + }); + } + }; + + on_after_backup(&synced.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { + // `synced.final_path` was never moved during backup creation, so it remains intact; + // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: synced.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetMacroError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetMacroError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + if let Err(remove_err) = remove_backup(&bak) { + let cause = ParquetMacroError::Io { + path: bak.clone(), + source: remove_err, + }; + return match fs::rename(&bak, &synced.final_path) { + Ok(()) => Err(cause), + Err(restore_err) => Err(ParquetMacroError::RollbackFailed { + cause: Box::new(cause), + failures: vec![RollbackFailure { + final_path: synced.final_path, + backup_path: Some(bak), + source: restore_err, + }], + }), + }; + } + } + + Ok(MacroWriteStats { + rows_written: synced.rows_written, + files_written: 1, + row_groups_written: synced.row_groups_written, + bytes_written: synced.bytes, + }) +} + +#[cfg(test)] +#[path = "parquet_macro_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/parquet_macro_tests.rs b/tools/curate-etl/src/parquet_macro_tests.rs new file mode 100644 index 00000000..922ab479 --- /dev/null +++ b/tools/curate-etl/src/parquet_macro_tests.rs @@ -0,0 +1,1060 @@ +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 { + 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 { + 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 { + 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 { + 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 { + 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) { + 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> { + 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, + 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 = 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 = 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 = (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 = (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::>() + ); + } +} + +#[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::(), + 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::(), + 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::(), + 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")); +}