T-173: M2.2o — tools/curate-etl: Zstd Parquet writer for macro/part.parquet (MacroRow → MacroParquetRow → write_macro_dataset, 6-column contract schema, atomic publish) in parquet_macro.rs with round-trip tests (no new crates, no CLI/bench/stream changes, no live Mongo)

This commit is contained in:
Studio 2026-12-02 14:58:34 -05:00
parent b6b9d310dc
commit 056268e945
4 changed files with 1842 additions and 1 deletions

View file

@ -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<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: `teData` BSON decoding, runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access.

View file

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

View file

@ -0,0 +1,776 @@
//! Streaming, atomic Zstd Parquet writer for `macro`.
//!
//! Writes `<out_dir>/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<K>>` 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<K: AsRef<str>> From<&MacroRow<K>> for MacroParquetRow {
#[inline]
fn from(row: &MacroRow<K>) -> 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<ParquetMacroError>,
failures: Vec<RollbackFailure>,
},
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<PublishIoError> 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<TypePtr, ParquetError> {
let fields: Vec<TypePtr> = 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<u32>,
country_iso_interner: StringInterner,
indicator_ids: Vec<u32>,
indicator_interner: StringInterner,
period_date: Vec<i32>,
known_at_micros: Vec<i64>,
known_at_source_ids: Vec<u32>,
known_at_source_interner: StringInterner,
value: Vec<f64>,
}
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<BufWriter<File>>,
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<Self, ParquetMacroError> {
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<ByteArray>) -> 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<ByteArray>,
) -> Result<SyncedMacroFile, ParquetMacroError> {
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 `<out_dir>/macro/part.parquet`.
///
/// # Empty Input
/// Empty input (with valid options) returns `Ok(MacroWriteStats::default())` without creating
/// `<out_dir>/macro` and without modifying or removing any pre-existing `part.parquet`.
///
/// # Concurrency & Atomicity
/// Concurrent writers targeting the same `<out_dir>/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.<run>.tmp`), flushed,
/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists,
/// a live-preserving backup (`part.parquet.<run>.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<P, I, R>(
out_dir: P,
rows: I,
options: MacroWriteOptions,
) -> Result<MacroWriteStats, ParquetMacroError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<MacroParquetRow>,
{
write_macro_dataset_with_hooks(
out_dir,
rows,
options,
DEFAULT_LOCK_TIMEOUT,
|_, _| {},
|path| fs::remove_file(path),
)
}
fn write_macro_dataset_with_hooks<P, I, R, F, Rm>(
out_dir: P,
rows: I,
options: MacroWriteOptions,
lock_timeout: Duration,
mut on_after_backup: F,
mut remove_backup: Rm,
) -> Result<MacroWriteStats, ParquetMacroError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<MacroParquetRow>,
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(&macro_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(&macro_dir);
let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner());
let _file_lock = DatasetFileLock::acquire_with_timeout(&macro_dir, lock_timeout)?;
let run_id = next_run_id();
let (tmp_path, tmp_file) = create_exclusive_tmp_file(&macro_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<ByteArray> = 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;

File diff suppressed because it is too large Load diff