stock-bot/tools/curate-etl/src/parquet_adj.rs

1315 lines
45 KiB
Rust

//! Streaming, atomic Zstd Parquet writer for `adj_factors`.
//!
//! Writes `<out_dir>/adj_factors/part.parquet` matching the 8-column contract schema in
//! `design/DATA-CONTRACTS.md` (§3A):
//!
//! 1. `listing_id` (`INT32`, `REQUIRED`)
//! 2. `ex_date` (`INT32`, `REQUIRED`, `DATE`)
//! 3. `split_factor` (`DOUBLE`, `REQUIRED`)
//! 4. `div_cash` (`DOUBLE`, `REQUIRED`)
//! 5. `div_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`)
//! 6. `cum_split_factor` (`DOUBLE`, `REQUIRED`)
//! 7. `cum_total_factor` (`DOUBLE`, `REQUIRED`)
//! 8. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
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::adj::AdjFactorRow;
use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR};
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_optional_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};
use crate::shorts::epoch_days_to_ymd;
/// Single `adj_factors` row matching the `design/DATA-CONTRACTS.md` Parquet schema.
#[derive(Debug, Clone, PartialEq)]
pub struct AdjFactorsParquetRow {
pub listing_id: i32,
pub ex_date: i32,
pub split_factor: f64,
pub div_cash: f64,
pub div_currency: Option<Cow<'static, str>>,
pub cum_split_factor: f64,
pub cum_total_factor: f64,
pub known_at_micros: i64,
}
impl AdjFactorsParquetRow {
/// Builds an [`AdjFactorsParquetRow`] from a curated [`AdjFactorRow<i32>`] and a
/// caller-supplied UTC microsecond `known_at` timestamp.
#[inline]
pub fn from_adj_row(row: &AdjFactorRow<i32>, known_at_micros: i64) -> Self {
Self {
listing_id: row.key,
ex_date: row.ex_date,
split_factor: row.split_factor,
div_cash: row.div_cash,
div_currency: row.div_currency.clone().map(Cow::Owned),
cum_split_factor: row.cum_split_factor,
cum_total_factor: row.cum_total_factor,
known_at_micros,
}
}
}
/// Configuration for [`write_adj_factors_dataset`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AdjFactorsWriteOptions {
pub row_group_rows: usize,
pub zstd_level: i32,
}
impl Default for AdjFactorsWriteOptions {
fn default() -> Self {
Self {
row_group_rows: DEFAULT_ROW_GROUP_ROWS,
zstd_level: DEFAULT_ZSTD_LEVEL,
}
}
}
/// Accounting summary returned by [`write_adj_factors_dataset`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AdjFactorsWriteStats {
pub rows_written: usize,
pub files_written: usize,
pub row_groups_written: usize,
pub bytes_written: u64,
}
/// Typed error returned by [`write_adj_factors_dataset`].
#[derive(Debug)]
pub enum ParquetAdjError {
InvalidRowGroupRows,
InvalidZstdLevel {
level: i32,
},
UnsortedInput {
prev_listing_id: i32,
prev_ex_date: i32,
listing_id: i32,
ex_date: i32,
},
DuplicateKey {
listing_id: i32,
ex_date: i32,
},
ExDateOutOfRange {
listing_id: i32,
ex_date: i32,
year: i32,
min_year: i32,
max_year: i32,
},
InvalidSplitFactor {
listing_id: i32,
ex_date: i32,
value: f64,
},
InvalidDivCash {
listing_id: i32,
ex_date: i32,
value: f64,
},
InvalidDivCurrency {
listing_id: i32,
ex_date: i32,
},
InvalidCumSplitFactor {
listing_id: i32,
ex_date: i32,
value: f64,
},
InvalidCumTotalFactor {
listing_id: i32,
ex_date: i32,
value: f64,
},
LockTimeout {
path: PathBuf,
waited: Duration,
},
RollbackFailed {
cause: Box<ParquetAdjError>,
failures: Vec<RollbackFailure>,
},
Io {
path: PathBuf,
source: io::Error,
},
Parquet {
path: PathBuf,
source: ParquetError,
},
}
impl fmt::Display for ParquetAdjError {
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_listing_id,
prev_ex_date,
listing_id,
ex_date,
} => write!(
f,
"unsorted input: ({listing_id}, {ex_date}) follows ({prev_listing_id}, {prev_ex_date})"
),
Self::DuplicateKey {
listing_id,
ex_date,
} => write!(
f,
"duplicate (listing_id, ex_date) key: ({listing_id}, {ex_date})"
),
Self::ExDateOutOfRange {
listing_id,
ex_date,
year,
min_year,
max_year,
} => write!(
f,
"ex_date {ex_date} (year {year}) for listing_id {listing_id} is outside supported range [{min_year}, {max_year}]"
),
Self::InvalidSplitFactor {
listing_id,
ex_date,
value,
} => write!(
f,
"invalid split_factor {value} for ({listing_id}, {ex_date}): must be finite and > 0"
),
Self::InvalidDivCash {
listing_id,
ex_date,
value,
} => write!(
f,
"invalid div_cash {value} for ({listing_id}, {ex_date}): must be finite and >= 0"
),
Self::InvalidDivCurrency {
listing_id,
ex_date,
} => write!(
f,
"invalid div_currency for ({listing_id}, {ex_date}): must be non-empty when div_cash > 0 and never empty/whitespace when Some"
),
Self::InvalidCumSplitFactor {
listing_id,
ex_date,
value,
} => write!(
f,
"invalid cum_split_factor {value} for ({listing_id}, {ex_date}): must be finite and > 0"
),
Self::InvalidCumTotalFactor {
listing_id,
ex_date,
value,
} => write!(
f,
"invalid cum_total_factor {value} for ({listing_id}, {ex_date}): must be finite and > 0"
),
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 ParquetAdjError {
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 ParquetAdjError {
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 8-column Parquet schema for `adj_factors` per `design/DATA-CONTRACTS.md` (§3A).
pub fn adj_factors_parquet_schema() -> Result<TypePtr, ParquetError> {
let fields: Vec<TypePtr> = vec![
Arc::new(
Type::primitive_type_builder("listing_id", PhysicalType::INT32)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("ex_date", PhysicalType::INT32)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
Arc::new(
Type::primitive_type_builder("split_factor", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("div_cash", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("div_currency", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::OPTIONAL)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("cum_split_factor", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("cum_total_factor", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.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()?,
),
];
Ok(Arc::new(
Type::group_type_builder("adj_factors")
.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("div_currency"), true)
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
.build(),
)
}
#[inline]
fn is_valid_positive_factor(value: f64) -> bool {
value.is_finite() && value > 0.0
}
#[inline]
fn validate_row(row: &AdjFactorsParquetRow) -> Result<(), ParquetAdjError> {
let (year, _, _) = epoch_days_to_ymd(row.ex_date);
if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) {
return Err(ParquetAdjError::ExDateOutOfRange {
listing_id: row.listing_id,
ex_date: row.ex_date,
year,
min_year: MIN_PARQUET_YEAR,
max_year: MAX_PARQUET_YEAR,
});
}
if !is_valid_positive_factor(row.split_factor) {
return Err(ParquetAdjError::InvalidSplitFactor {
listing_id: row.listing_id,
ex_date: row.ex_date,
value: row.split_factor,
});
}
if !row.div_cash.is_finite() || row.div_cash < 0.0 {
return Err(ParquetAdjError::InvalidDivCash {
listing_id: row.listing_id,
ex_date: row.ex_date,
value: row.div_cash,
});
}
match row.div_currency.as_deref() {
Some(currency) if currency.trim().is_empty() => {
return Err(ParquetAdjError::InvalidDivCurrency {
listing_id: row.listing_id,
ex_date: row.ex_date,
});
}
None if row.div_cash > 0.0 => {
return Err(ParquetAdjError::InvalidDivCurrency {
listing_id: row.listing_id,
ex_date: row.ex_date,
});
}
_ => {}
}
if !is_valid_positive_factor(row.cum_split_factor) {
return Err(ParquetAdjError::InvalidCumSplitFactor {
listing_id: row.listing_id,
ex_date: row.ex_date,
value: row.cum_split_factor,
});
}
if !is_valid_positive_factor(row.cum_total_factor) {
return Err(ParquetAdjError::InvalidCumTotalFactor {
listing_id: row.listing_id,
ex_date: row.ex_date,
value: row.cum_total_factor,
});
}
Ok(())
}
#[derive(Default)]
struct RowGroupBuffer {
listing_id: Vec<i32>,
ex_date: Vec<i32>,
split_factor: Vec<f64>,
div_cash: Vec<f64>,
div_currency_ids: Vec<u32>,
div_currency_def_levels: Vec<i16>,
div_currency_interner: StringInterner,
cum_split_factor: Vec<f64>,
cum_total_factor: Vec<f64>,
known_at_micros: Vec<i64>,
}
impl RowGroupBuffer {
#[inline]
fn len(&self) -> usize {
self.listing_id.len()
}
fn push(&mut self, row: &AdjFactorsParquetRow) {
self.listing_id.push(row.listing_id);
self.ex_date.push(row.ex_date);
self.split_factor.push(row.split_factor);
self.div_cash.push(row.div_cash);
match row.div_currency.as_deref() {
Some(currency) => {
let id = self.div_currency_interner.intern(currency);
self.div_currency_ids.push(id);
self.div_currency_def_levels.push(1);
}
None => {
self.div_currency_def_levels.push(0);
}
}
self.cum_split_factor.push(row.cum_split_factor);
self.cum_total_factor.push(row.cum_total_factor);
self.known_at_micros.push(row.known_at_micros);
}
fn clear(&mut self) {
self.listing_id.clear();
self.ex_date.clear();
self.split_factor.clear();
self.div_cash.clear();
self.div_currency_ids.clear();
self.div_currency_def_levels.clear();
self.div_currency_interner.clear();
self.cum_split_factor.clear();
self.cum_total_factor.clear();
self.known_at_micros.clear();
}
}
struct AdjFactorsFileWriter {
tmp_path: PathBuf,
final_path: PathBuf,
writer: SerializedFileWriter<BufWriter<File>>,
buf: RowGroupBuffer,
rows_written: usize,
row_groups_written: usize,
}
impl AdjFactorsFileWriter {
fn from_file(
tmp_path: PathBuf,
final_path: PathBuf,
file: File,
schema: &TypePtr,
props: &WriterPropertiesPtr,
) -> Result<Self, ParquetAdjError> {
let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file);
let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err(
|source| ParquetAdjError::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<(), ParquetAdjError> {
let row_count = self.buf.len();
if row_count == 0 {
return Ok(());
}
let map_pq = |source: ParquetError| ParquetAdjError::Parquet {
path: self.tmp_path.clone(),
source,
};
let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?;
// 1. listing_id (INT32, REQUIRED)
write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?;
// 2. ex_date (INT32, REQUIRED, DATE)
write_i32_col(&mut rg_writer, &self.buf.ex_date).map_err(map_pq)?;
// 3. split_factor (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.split_factor, None).map_err(map_pq)?;
// 4. div_cash (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.div_cash, None).map_err(map_pq)?;
// 5. div_currency (BYTE_ARRAY, OPTIONAL, STRING)
write_optional_interned_str_col(
&mut rg_writer,
&self.buf.div_currency_ids,
&self.buf.div_currency_def_levels,
&self.buf.div_currency_interner,
scratch,
)
.map_err(map_pq)?;
// 6. cum_split_factor (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.cum_split_factor, None).map_err(map_pq)?;
// 7. cum_total_factor (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.cum_total_factor, None).map_err(map_pq)?;
// 8. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC)
write_i64_col(&mut rg_writer, &self.buf.known_at_micros).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<SyncedAdjFactorsFile, ParquetAdjError> {
self.flush_row_group(scratch)?;
let mut buf_writer =
self.writer
.into_inner()
.map_err(|source| ParquetAdjError::Parquet {
path: self.tmp_path.clone(),
source,
})?;
buf_writer.flush().map_err(|source| ParquetAdjError::Io {
path: self.tmp_path.clone(),
source,
})?;
let file = buf_writer
.into_inner()
.map_err(|err| ParquetAdjError::Io {
path: self.tmp_path.clone(),
source: err.into_error(),
})?;
file.sync_all().map_err(|source| ParquetAdjError::Io {
path: self.tmp_path.clone(),
source,
})?;
let bytes = file
.metadata()
.map_err(|source| ParquetAdjError::Io {
path: self.tmp_path.clone(),
source,
})?
.len();
drop(file);
Ok(SyncedAdjFactorsFile {
tmp_path: self.tmp_path,
final_path: self.final_path,
rows_written: self.rows_written,
row_groups_written: self.row_groups_written,
bytes,
})
}
}
struct SyncedAdjFactorsFile {
tmp_path: PathBuf,
final_path: PathBuf,
rows_written: usize,
row_groups_written: usize,
bytes: u64,
}
/// Streams strictly ascending `(listing_id, ex_date)` rows into a single Zstd Parquet file
/// at `<out_dir>/adj_factors/part.parquet`.
///
/// # Empty Input
/// Empty input returns `Ok(AdjFactorsWriteStats::default())` without creating `<out_dir>/adj_factors`
/// and without modifying or removing any pre-existing `part.parquet`.
///
/// # Concurrency & Atomicity
/// Concurrent writers targeting the same `<out_dir>/adj_factors` 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 [`ParquetAdjError::RollbackFailed`]), and
/// only staging files owned by this run are unlinked.
pub fn write_adj_factors_dataset<P, I, R>(
out_dir: P,
rows: I,
options: AdjFactorsWriteOptions,
) -> Result<AdjFactorsWriteStats, ParquetAdjError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<AdjFactorsParquetRow>,
{
write_adj_factors_dataset_with_hooks(
out_dir,
rows,
options,
DEFAULT_LOCK_TIMEOUT,
|_, _| {},
|path| fs::remove_file(path),
)
}
fn write_adj_factors_dataset_with_hooks<P, I, R, F, Rm>(
out_dir: P,
rows: I,
options: AdjFactorsWriteOptions,
lock_timeout: Duration,
mut on_after_backup: F,
mut remove_backup: Rm,
) -> Result<AdjFactorsWriteStats, ParquetAdjError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<AdjFactorsParquetRow>,
F: FnMut(&Path, Option<&Path>),
Rm: FnMut(&Path) -> io::Result<()>,
{
if options.row_group_rows == 0 {
return Err(ParquetAdjError::InvalidRowGroupRows);
}
let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| {
ParquetAdjError::InvalidZstdLevel {
level: options.zstd_level,
}
})?;
let mut row_iter = rows.into_iter();
let Some(first_item) = row_iter.next() else {
return Ok(AdjFactorsWriteStats::default());
};
validate_row(first_item.borrow())?;
let out_dir = out_dir.as_ref();
let adj_dir = out_dir.join("adj_factors");
let schema = adj_factors_parquet_schema().map_err(|source| ParquetAdjError::Parquet {
path: adj_dir.clone(),
source,
})?;
let props = build_writer_properties(zstd_level);
fs::create_dir_all(&adj_dir).map_err(|source| ParquetAdjError::Io {
path: adj_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(&adj_dir);
let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner());
let _file_lock = DatasetFileLock::acquire_with_timeout(&adj_dir, lock_timeout)?;
let run_id = next_run_id();
let (tmp_path, tmp_file) = create_exclusive_tmp_file(&adj_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(AdjFactorsFileWriter::from_file(
tmp_path,
adj_dir.join("part.parquet"),
tmp_file,
&schema,
&props,
)?);
let synced = {
let mut prev_key: Option<(i32, i32)> = None;
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 out-of-range
// ex_date is reported as ExDateOutOfRange rather than UnsortedInput.
validate_row(row)?;
let key = (row.listing_id, row.ex_date);
if let Some((prev_listing_id, prev_ex_date)) = prev_key {
match key.cmp(&(prev_listing_id, prev_ex_date)) {
Ordering::Equal => {
return Err(ParquetAdjError::DuplicateKey {
listing_id: row.listing_id,
ex_date: row.ex_date,
});
}
Ordering::Less => {
return Err(ParquetAdjError::UnsortedInput {
prev_listing_id,
prev_ex_date,
listing_id: row.listing_id,
ex_date: row.ex_date,
});
}
Ordering::Greater => {}
}
}
prev_key = Some(key);
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(ParquetAdjError::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 = ParquetAdjError::Io {
path: synced.final_path,
source,
};
return match backup_remove_failure {
Some(failure) => Err(ParquetAdjError::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 = ParquetAdjError::Io {
path: bak.clone(),
source: remove_err,
};
return match fs::rename(&bak, &synced.final_path) {
Ok(()) => Err(cause),
Err(restore_err) => Err(ParquetAdjError::RollbackFailed {
cause: Box::new(cause),
failures: vec![RollbackFailure {
final_path: synced.final_path,
backup_path: Some(bak),
source: restore_err,
}],
}),
};
}
}
Ok(AdjFactorsWriteStats {
rows_written: synced.rows_written,
files_written: 1,
row_groups_written: synced.row_groups_written,
bytes_written: synced.bytes,
})
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use parquet::basic::ConvertedType;
use parquet::column::reader::ColumnReader;
use parquet::file::reader::{FileReader, SerializedFileReader};
use super::*;
use crate::adj::{build_adj_factors, DividendEvent};
use crate::split::{ymd_to_epoch_days, SplitEvent};
static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
pub(super) struct TempDirGuard {
path: PathBuf,
}
impl TempDirGuard {
pub(super) 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-adj-test-{label}-{pid}-{seq}"));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create test temp dir");
Self { path }
}
pub(super) fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempDirGuard {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
pub(super) fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
pub(super) fn declared_known_at_micros(ex_date: i32) -> i64 {
// Declared 14 days before ex_date at 13:30 UTC.
i64::from(ex_date - 14) * 86_400_000_000 + 13 * 3_600_000_000 + 30 * 60_000_000
}
pub(super) fn make_split_row(
listing_id: i32,
ex_date: i32,
split_factor: f64,
cum_split_factor: f64,
cum_total_factor: f64,
) -> AdjFactorsParquetRow {
AdjFactorsParquetRow {
listing_id,
ex_date,
split_factor,
div_cash: 0.0,
div_currency: None,
cum_split_factor,
cum_total_factor,
known_at_micros: declared_known_at_micros(ex_date),
}
}
pub(super) fn make_div_row(
listing_id: i32,
ex_date: i32,
div_cash: f64,
div_currency: &'static str,
cum_split_factor: f64,
cum_total_factor: f64,
) -> AdjFactorsParquetRow {
AdjFactorsParquetRow {
listing_id,
ex_date,
split_factor: 1.0,
div_cash,
div_currency: Some(Cow::Borrowed(div_currency)),
cum_split_factor,
cum_total_factor,
known_at_micros: declared_known_at_micros(ex_date),
}
}
pub(super) fn read_parquet_rows(path: &Path) -> Vec<AdjFactorsParquetRow> {
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_opt_str = |col_idx: usize| -> Vec<Option<String>> {
let mut vals = Vec::with_capacity(num_rows);
let mut def_levels = Vec::with_capacity(num_rows);
match rg_reader.get_column_reader(col_idx).expect("col reader") {
ColumnReader::ByteArrayColumnReader(mut r) => {
let (read, _, levels_read) = r
.read_records(num_rows, Some(&mut def_levels), None, &mut vals)
.expect("read optional utf8");
assert_eq!(read, num_rows);
assert_eq!(levels_read, num_rows);
}
_ => panic!("expected BYTE_ARRAY column at index {col_idx}"),
}
let mut val_idx = 0usize;
let mut result = Vec::with_capacity(num_rows);
for def in def_levels {
match def {
0 => result.push(None),
1 => {
let text = std::str::from_utf8(vals[val_idx].data())
.expect("valid utf8")
.to_owned();
val_idx += 1;
result.push(Some(text));
}
other => panic!("unexpected definition level {other}"),
}
}
assert_eq!(val_idx, vals.len());
result
};
let listing_id = read_i32(0);
let ex_date = read_i32(1);
let split_factor = read_f64(2);
let div_cash = read_f64(3);
let div_currency = read_opt_str(4);
let cum_split_factor = read_f64(5);
let cum_total_factor = read_f64(6);
let known_at_micros = read_i64(7);
for i in 0..num_rows {
out.push(AdjFactorsParquetRow {
listing_id: listing_id[i],
ex_date: ex_date[i],
split_factor: split_factor[i],
div_cash: div_cash[i],
div_currency: div_currency[i].clone().map(Cow::Owned),
cum_split_factor: cum_split_factor[i],
cum_total_factor: cum_total_factor[i],
known_at_micros: known_at_micros[i],
});
}
}
out
}
pub(super) fn assert_row_bitwise_eq(
actual: &AdjFactorsParquetRow,
expected: &AdjFactorsParquetRow,
) {
assert_eq!(actual.listing_id, expected.listing_id);
assert_eq!(actual.ex_date, expected.ex_date);
assert_eq!(
actual.split_factor.to_bits(),
expected.split_factor.to_bits()
);
assert_eq!(actual.div_cash.to_bits(), expected.div_cash.to_bits());
assert_eq!(actual.div_currency, expected.div_currency);
assert_eq!(
actual.cum_split_factor.to_bits(),
expected.cum_split_factor.to_bits()
);
assert_eq!(
actual.cum_total_factor.to_bits(),
expected.cum_total_factor.to_bits()
);
assert_eq!(actual.known_at_micros, expected.known_at_micros);
}
pub(super) 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()
);
}
}
#[test]
fn schema_matches_contract_names_types_nullability_and_order() {
let schema = adj_factors_parquet_schema().expect("build schema");
assert_eq!(schema.name(), "adj_factors");
let fields = schema.get_fields();
assert_eq!(fields.len(), 8);
let expected: [(
&str,
PhysicalType,
Repetition,
Option<LogicalType>,
ConvertedType,
); 8] = [
(
"listing_id",
PhysicalType::INT32,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"ex_date",
PhysicalType::INT32,
Repetition::REQUIRED,
Some(LogicalType::Date),
ConvertedType::DATE,
),
(
"split_factor",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"div_cash",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"div_currency",
PhysicalType::BYTE_ARRAY,
Repetition::OPTIONAL,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"cum_split_factor",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"cum_total_factor",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"known_at",
PhysicalType::INT64,
Repetition::REQUIRED,
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
ConvertedType::TIMESTAMP_MICROS,
),
];
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_adj_factors_round_trip_bitwise_and_zstd_on_every_column_chunk() {
let tmp = TempDirGuard::new("round-trip");
let d0 = day(1969, 12, 31); // pre-1970 split-only
let d1 = day(2021, 7, 20); // split-only
let d2 = day(2024, 3, 6); // dividend-only USD
let d3 = day(2024, 6, 10); // combined split + dividend USD
let d4 = day(2025, 1, 15); // dividend-only CAD on listing 2
let splits = vec![
(
101i32,
SplitEvent {
ex_date: d0,
ratio: 2.0,
},
),
(
101i32,
SplitEvent {
ex_date: d1,
ratio: 4.0,
},
),
(
101i32,
SplitEvent {
ex_date: d3,
ratio: 10.0,
},
),
];
let dividends = vec![
(
101i32,
DividendEvent {
ex_date: d2,
cash: 0.04,
currency: "USD".to_string(),
prev_close: Some(850.0),
prev_close_currency: Some("USD".to_string()),
},
),
(
101i32,
DividendEvent {
ex_date: d3,
cash: 0.10,
currency: "USD".to_string(),
prev_close: Some(1200.0),
prev_close_currency: Some("USD".to_string()),
},
),
(
202i32,
DividendEvent {
ex_date: d4,
cash: 0.90,
currency: "CAD".to_string(),
prev_close: Some(100.0),
prev_close_currency: Some("CAD".to_string()),
},
),
];
let built = build_adj_factors(splits, dividends).unwrap();
let rows: Vec<AdjFactorsParquetRow> = built
.rows
.iter()
.map(|r| AdjFactorsParquetRow::from_adj_row(r, declared_known_at_micros(r.ex_date)))
.collect();
assert_eq!(rows.len(), 5);
assert!(rows[0].div_currency.is_none());
assert!(rows[1].div_currency.is_none());
assert_eq!(rows[2].div_currency.as_deref(), Some("USD"));
assert_eq!(rows[3].div_currency.as_deref(), Some("USD"));
assert_eq!(rows[4].div_currency.as_deref(), Some("CAD"));
let opts = AdjFactorsWriteOptions {
row_group_rows: 2,
..AdjFactorsWriteOptions::default()
};
let stats = write_adj_factors_dataset(tmp.path(), &rows, opts).unwrap();
assert_eq!(stats.rows_written, 5);
assert_eq!(stats.files_written, 1);
assert_eq!(stats.row_groups_written, 3);
assert!(stats.bytes_written > 0);
let path = tmp.path().join("adj_factors/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);
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(), rows.len());
for (a, e) in actual.iter().zip(&rows) {
assert_row_bitwise_eq(a, e);
}
assert_eq!(actual[0].ex_date, -1);
assert!(actual[0].div_currency.is_none());
assert_no_transient_files(&tmp.path().join("adj_factors"));
}
#[test]
fn empty_input_creates_nothing_and_preserves_existing_part_parquet() {
let tmp = TempDirGuard::new("empty");
let fresh = tmp.path().join("fresh");
let stats = write_adj_factors_dataset(
&fresh,
std::iter::empty::<AdjFactorsParquetRow>(),
AdjFactorsWriteOptions::default(),
)
.unwrap();
assert_eq!(stats, AdjFactorsWriteStats::default());
assert!(!fresh.exists(), "empty input must not create out_dir");
let seeded = tmp.path().join("seeded");
let seed_rows = vec![make_div_row(10, day(2024, 3, 15), 0.25, "USD", 1.0, 1.005)];
write_adj_factors_dataset(&seeded, &seed_rows, AdjFactorsWriteOptions::default()).unwrap();
let part = seeded.join("adj_factors/part.parquet");
let before = fs::read(&part).unwrap();
let empty_stats = write_adj_factors_dataset(
&seeded,
std::iter::empty::<AdjFactorsParquetRow>(),
AdjFactorsWriteOptions::default(),
)
.unwrap();
assert_eq!(empty_stats, AdjFactorsWriteStats::default());
assert_eq!(fs::read(&part).unwrap(), before);
assert_no_transient_files(&seeded.join("adj_factors"));
}
#[test]
fn determinism_identical_rows_produce_byte_identical_files() {
let tmp = TempDirGuard::new("determinism");
let rows = vec![
make_split_row(1, day(2021, 7, 20), 4.0, 40.0, 40.08),
make_div_row(1, day(2024, 3, 6), 0.04, "USD", 10.0, 10.02),
make_div_row(2, day(2025, 1, 15), 0.90, "CAD", 1.0, 1.009),
];
let out_a = tmp.path().join("a");
let out_b = tmp.path().join("b");
let opts = AdjFactorsWriteOptions {
row_group_rows: 2,
..AdjFactorsWriteOptions::default()
};
write_adj_factors_dataset(&out_a, &rows, opts).unwrap();
write_adj_factors_dataset(&out_b, &rows, opts).unwrap();
let bytes_a = fs::read(out_a.join("adj_factors/part.parquet")).unwrap();
let bytes_b = fs::read(out_b.join("adj_factors/part.parquet")).unwrap();
assert_eq!(bytes_a, bytes_b);
}
}
#[cfg(test)]
#[path = "parquet_adj_tests.rs"]
mod edge_case_tests;