From 42d82469a4998ea3f3f9b77d1fd353b33adf80f2 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 01:36:18 -0500 Subject: [PATCH] =?UTF-8?q?T-156:=20M2.2e=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20Zstd=20Parquet=20writer=20for=20`fundamentals=5Fpit/year=3D?= =?UTF-8?q?YYYY/part.parquet`=20(`FundamentalsSnapshot`=20=E2=86=92?= =?UTF-8?q?=20flat=20row=20matching=20the=20DuckDB=20`fundamentalsAsOf`=20?= =?UTF-8?q?reader=20columns)=20with=20tests=20(no=20new=20crates,=20no=20C?= =?UTF-8?q?LI/bench=20changes,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/lib.rs | 5 + tools/curate-etl/src/parquet_fundamentals.rs | 1508 ++++++++++++++++ .../src/parquet_fundamentals_tests.rs | 1537 +++++++++++++++++ 3 files changed, 3050 insertions(+) create mode 100644 tools/curate-etl/src/parquet_fundamentals.rs create mode 100644 tools/curate-etl/src/parquet_fundamentals_tests.rs diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 5d412354..fb59f375 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -25,6 +25,7 @@ pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; pub mod parquet_events; +pub mod parquet_fundamentals; pub mod parquet_fx; mod parquet_publish; pub mod parquet_shorts; @@ -162,6 +163,10 @@ pub use parquet_events::{ events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, }; +pub use parquet_fundamentals::{ + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitParquetRow, + FundamentalsPitWriteOptions, FundamentalsPitWriteStats, ParquetFundamentalsError, +}; pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs new file mode 100644 index 00000000..f833350d --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -0,0 +1,1508 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. +//! +//! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column +//! contract schema read by `planFundamentalsAsOfQuery` in +//! `libs/research/src/market-data-store-duckdb.ts`: +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `effective_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 3. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 4. `has_estimated_lag` (`BOOLEAN`, `REQUIRED`) +//! 5. `period_end` (`INT32`, `REQUIRED`, `DATE`) +//! 6. `fiscal_period` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 7. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 8. `period_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 9. `revenue` (`DOUBLE`, `OPTIONAL`) +//! 10. `net_income` (`DOUBLE`, `OPTIONAL`) +//! 11. `operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`) +//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`) +//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`) +//! 15. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) +//! 16. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) +//! 17. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) +//! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::collections::BTreeMap; +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::column::writer::ColumnWriter; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::{SerializedFileWriter, SerializedRowGroupWriter}; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::events::partition_year_utc; +use crate::fundamentals::FundamentalsSnapshot; +pub 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, + rollback_published, write_i32_col, write_i64_col, write_interned_str_col, + write_optional_f64_col, write_optional_i32_col, write_optional_interned_str_col, + DatasetFileLock, PublishIoError, PublishedPartition, 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 flat `fundamentals_pit` row keyed by `(listing_id, effective_known_at_micros)`. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPitParquetRow { + pub listing_id: i32, + pub effective_known_at_micros: i64, + pub known_at_source: Cow<'static, str>, + pub has_estimated_lag: bool, + pub period_end: i32, + pub fiscal_period: Cow<'static, str>, + pub currency: Cow<'static, str>, + pub period_known_at_micros: i64, + pub revenue: Option, + pub net_income: Option, + pub operating_cash_flow: Option, + pub total_assets: Option, + pub total_equity: Option, + pub shares_outstanding: Option, + pub ttm_revenue: Option, + pub ttm_net_income: Option, + pub ttm_operating_cash_flow: Option, + pub ttm_period_end: Option, + pub ttm_currency: Option>, + pub ttm_has_estimated_lag: Option, +} + +impl TryFrom<&FundamentalsSnapshot> for FundamentalsPitParquetRow { + type Error = ParquetFundamentalsError; + + fn try_from(snapshot: &FundamentalsSnapshot) -> Result { + let latest = snapshot.periods.first().ok_or( + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + }, + )?; + + let ( + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + ) = match &snapshot.ttm { + Some(ttm) => ( + ttm.flows.revenue, + ttm.flows.net_income, + ttm.flows.operating_cash_flow, + Some(ttm.ending_period_end), + Some(Cow::Owned(ttm.currency.clone())), + Some(ttm.has_estimated_lag), + ), + None => (None, None, None, None, None, None), + }; + + Ok(Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: Cow::Borrowed(latest.fiscal_period.as_str()), + currency: Cow::Owned(latest.currency.clone()), + period_known_at_micros: latest.known_at_utc_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + }) + } +} + +impl TryFrom> for FundamentalsPitParquetRow { + type Error = ParquetFundamentalsError; + + fn try_from(snapshot: FundamentalsSnapshot) -> Result { + let mut periods = snapshot.periods.into_iter(); + let latest = periods.next().ok_or( + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + }, + )?; + + let ( + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + ) = match snapshot.ttm { + Some(ttm) => ( + ttm.flows.revenue, + ttm.flows.net_income, + ttm.flows.operating_cash_flow, + Some(ttm.ending_period_end), + Some(Cow::Owned(ttm.currency)), + Some(ttm.has_estimated_lag), + ), + None => (None, None, None, None, None, None), + }; + + Ok(Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: Cow::Borrowed(latest.fiscal_period.as_str()), + currency: Cow::Owned(latest.currency), + period_known_at_micros: latest.known_at_utc_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_revenue, + ttm_net_income, + ttm_operating_cash_flow, + ttm_period_end, + ttm_currency, + ttm_has_estimated_lag, + }) + } +} + +/// Configuration for [`write_fundamentals_pit_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FundamentalsPitWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for FundamentalsPitWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_fundamentals_pit_dataset`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FundamentalsPitWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub rows_by_year: BTreeMap, +} + +/// Typed error returned by [`FundamentalsPitParquetRow::try_from`] and +/// [`write_fundamentals_pit_dataset`]. +#[derive(Debug)] +pub enum ParquetFundamentalsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + EmptySnapshotPeriods { + listing_id: i32, + effective_known_at_micros: i64, + }, + UnsortedInput { + row_index: usize, + prev_listing_id: i32, + prev_effective_known_at_micros: i64, + listing_id: i32, + effective_known_at_micros: i64, + }, + DuplicateRow { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + PartitionYearOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + year: i32, + min_year: i32, + max_year: i32, + }, + PeriodEndOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + period_end: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + TtmPeriodEndOutOfRange { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + ttm_period_end: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + PeriodKnownAtAfterEffectiveKnownAt { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + period_known_at_micros: i64, + }, + EmptyKnownAtSource { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyFiscalPeriod { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyCurrency { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + EmptyTtmCurrency { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + InconsistentTtmMetadata { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + }, + NonFiniteValue { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + field: &'static str, + 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 ParquetFundamentalsError { + 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::EmptySnapshotPeriods { + listing_id, + effective_known_at_micros, + } => write!( + f, + "snapshot for (listing_id={listing_id}, effective_known_at={effective_known_at_micros}) has no visible periods" + ), + Self::UnsortedInput { + row_index, + prev_listing_id, + prev_effective_known_at_micros, + listing_id, + effective_known_at_micros, + } => write!( + f, + "unsorted input at row {row_index}: ({listing_id}, {effective_known_at_micros}) follows ({prev_listing_id}, {prev_effective_known_at_micros})" + ), + Self::DuplicateRow { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "duplicate fundamentals_pit row at row {row_index}: (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" + ), + Self::PartitionYearOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + year, + min_year, + max_year, + } => write!( + f, + "partition year {year} (effective_known_at {effective_known_at_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" + ), + Self::PeriodEndOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + period_end, + year, + min_year, + max_year, + } => write!( + f, + "period_end {period_end} (year {year}) at row {row_index} for ({listing_id}, {effective_known_at_micros}) is outside allowed range {min_year}..={max_year}" + ), + Self::TtmPeriodEndOutOfRange { + row_index, + listing_id, + effective_known_at_micros, + ttm_period_end, + year, + min_year, + max_year, + } => write!( + f, + "ttm_period_end {ttm_period_end} (year {year}) at row {row_index} for ({listing_id}, {effective_known_at_micros}) is outside allowed range {min_year}..={max_year}" + ), + Self::PeriodKnownAtAfterEffectiveKnownAt { + row_index, + listing_id, + effective_known_at_micros, + period_known_at_micros, + } => write!( + f, + "period_known_at {period_known_at_micros} is after effective_known_at {effective_known_at_micros} at row {row_index} for listing_id {listing_id}" + ), + Self::EmptyKnownAtSource { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyFiscalPeriod { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty fiscal_period at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyCurrency { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" + ), + Self::EmptyTtmCurrency { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty when present" + ), + Self::InconsistentTtmMetadata { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "inconsistent TTM columns at row {row_index} for ({listing_id}, {effective_known_at_micros}): ttm_period_end, ttm_currency, and ttm_has_estimated_lag must all be Some or all be None, and TTM flow values require TTM metadata" + ), + Self::NonFiniteValue { + row_index, + listing_id, + effective_known_at_micros, + field, + value, + } => write!( + f, + "non-finite value {value} in field '{field}' at row {row_index} for ({listing_id}, {effective_known_at_micros})" + ), + 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 ParquetFundamentalsError { + 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 ParquetFundamentalsError { + 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 20-column Parquet schema for `fundamentals_pit` matching +/// `FUNDAMENTALS_BASE_SCHEMA`, `FUNDAMENTALS_PIT_VALUE_FIELDS`, and +/// `FUNDAMENTALS_TTM_META_SCHEMA` in `libs/research/src/market-data-store-duckdb.ts`. +pub fn fundamentals_pit_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("effective_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("has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("period_end", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("period_known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("revenue", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("net_income", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("operating_cash_flow", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("total_assets", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("total_equity", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("shares_outstanding", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_net_income", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_operating_cash_flow", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("fundamentals_pit") + .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("known_at_source"), true) + .set_column_dictionary_enabled(ColumnPath::from("fiscal_period"), true) + .set_column_dictionary_enabled(ColumnPath::from("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("ttm_currency"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn compare_row_keys(a: &FundamentalsPitParquetRow, b: &FundamentalsPitParquetRow) -> Ordering { + a.listing_id + .cmp(&b.listing_id) + .then_with(|| a.effective_known_at_micros.cmp(&b.effective_known_at_micros)) +} + +#[inline] +fn check_opt_finite( + row: &FundamentalsPitParquetRow, + row_index: usize, + field: &'static str, + value: Option, +) -> Result<(), ParquetFundamentalsError> { + if let Some(v) = value { + if !v.is_finite() { + return Err(ParquetFundamentalsError::NonFiniteValue { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + field, + value: v, + }); + } + } + Ok(()) +} + +fn validate_row( + row: &FundamentalsPitParquetRow, + row_index: usize, +) -> Result { + let year = partition_year_utc(row.effective_known_at_micros); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetFundamentalsError::PartitionYearOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + let (period_year, _, _) = epoch_days_to_ymd(row.period_end); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&period_year) { + return Err(ParquetFundamentalsError::PeriodEndOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + period_end: row.period_end, + year: period_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + if row.period_known_at_micros > row.effective_known_at_micros { + return Err( + ParquetFundamentalsError::PeriodKnownAtAfterEffectiveKnownAt { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + period_known_at_micros: row.period_known_at_micros, + }, + ); + } + + if row.known_at_source.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyKnownAtSource { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + if row.fiscal_period.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyFiscalPeriod { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + if row.currency.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + + check_opt_finite(row, row_index, "revenue", row.revenue)?; + check_opt_finite(row, row_index, "net_income", row.net_income)?; + check_opt_finite( + row, + row_index, + "operating_cash_flow", + row.operating_cash_flow, + )?; + check_opt_finite(row, row_index, "total_assets", row.total_assets)?; + check_opt_finite(row, row_index, "total_equity", row.total_equity)?; + check_opt_finite(row, row_index, "shares_outstanding", row.shares_outstanding)?; + check_opt_finite(row, row_index, "ttm_revenue", row.ttm_revenue)?; + check_opt_finite(row, row_index, "ttm_net_income", row.ttm_net_income)?; + check_opt_finite( + row, + row_index, + "ttm_operating_cash_flow", + row.ttm_operating_cash_flow, + )?; + + let has_ttm_period_end = row.ttm_period_end.is_some(); + let has_ttm_currency = row.ttm_currency.is_some(); + let has_ttm_lag = row.ttm_has_estimated_lag.is_some(); + let all_ttm_meta = has_ttm_period_end && has_ttm_currency && has_ttm_lag; + let no_ttm_meta = !has_ttm_period_end && !has_ttm_currency && !has_ttm_lag; + let has_any_ttm_flow = row.ttm_revenue.is_some() + || row.ttm_net_income.is_some() + || row.ttm_operating_cash_flow.is_some(); + + if (!all_ttm_meta && !no_ttm_meta) || (no_ttm_meta && has_any_ttm_flow) { + return Err(ParquetFundamentalsError::InconsistentTtmMetadata { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + + if let Some(ttm_end) = row.ttm_period_end { + let (ttm_year, _, _) = epoch_days_to_ymd(ttm_end); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&ttm_year) { + return Err(ParquetFundamentalsError::TtmPeriodEndOutOfRange { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + ttm_period_end: ttm_end, + year: ttm_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + if let Some(ttm_ccy) = row.ttm_currency.as_deref() { + if ttm_ccy.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyTtmCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + } + + Ok(year) +} + +fn write_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], +) -> Result<(), ParquetError> { + let mut col = match rg_writer.next_column()? { + Some(col) => col, + None => { + return Err(ParquetError::General( + "unexpected end of Parquet schema columns".to_string(), + )); + } + }; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, None, None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + +fn write_optional_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], + def_levels: &[i16], +) -> Result<(), ParquetError> { + let mut col = match rg_writer.next_column()? { + Some(col) => col, + None => { + return Err(ParquetError::General( + "unexpected end of Parquet schema columns".to_string(), + )); + } + }; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, Some(def_levels), None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + +#[derive(Default)] +struct OptionalF64Column { + values: Vec, + def_levels: Vec, +} + +impl OptionalF64Column { + #[inline] + fn push(&mut self, value: Option) { + match value { + Some(v) => { + self.values.push(v); + self.def_levels.push(1); + } + None => { + self.def_levels.push(0); + } + } + } + + fn clear(&mut self) { + self.values.clear(); + self.def_levels.clear(); + } +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + effective_known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, + has_estimated_lag: Vec, + period_end: Vec, + fiscal_period_ids: Vec, + fiscal_period_interner: StringInterner, + currency_ids: Vec, + currency_interner: StringInterner, + period_known_at_micros: Vec, + revenue: OptionalF64Column, + net_income: OptionalF64Column, + operating_cash_flow: OptionalF64Column, + total_assets: OptionalF64Column, + total_equity: OptionalF64Column, + shares_outstanding: OptionalF64Column, + ttm_revenue: OptionalF64Column, + ttm_net_income: OptionalF64Column, + ttm_operating_cash_flow: OptionalF64Column, + ttm_period_end_values: Vec, + ttm_period_end_defs: Vec, + ttm_currency_ids: Vec, + ttm_currency_defs: Vec, + ttm_currency_interner: StringInterner, + ttm_has_estimated_lag_values: Vec, + ttm_has_estimated_lag_defs: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &FundamentalsPitParquetRow) { + self.listing_id.push(row.listing_id); + self.effective_known_at_micros + .push(row.effective_known_at_micros); + let kas_id = self + .known_at_source_interner + .intern(row.known_at_source.as_ref()); + self.known_at_source_ids.push(kas_id); + self.has_estimated_lag.push(row.has_estimated_lag); + self.period_end.push(row.period_end); + let fp_id = self + .fiscal_period_interner + .intern(row.fiscal_period.as_ref()); + self.fiscal_period_ids.push(fp_id); + let ccy_id = self.currency_interner.intern(row.currency.as_ref()); + self.currency_ids.push(ccy_id); + self.period_known_at_micros + .push(row.period_known_at_micros); + + self.revenue.push(row.revenue); + self.net_income.push(row.net_income); + self.operating_cash_flow.push(row.operating_cash_flow); + self.total_assets.push(row.total_assets); + self.total_equity.push(row.total_equity); + self.shares_outstanding.push(row.shares_outstanding); + self.ttm_revenue.push(row.ttm_revenue); + self.ttm_net_income.push(row.ttm_net_income); + self.ttm_operating_cash_flow + .push(row.ttm_operating_cash_flow); + + match row.ttm_period_end { + Some(day) => { + self.ttm_period_end_values.push(day); + self.ttm_period_end_defs.push(1); + } + None => { + self.ttm_period_end_defs.push(0); + } + } + match row.ttm_currency.as_deref() { + Some(ccy) => { + let id = self.ttm_currency_interner.intern(ccy); + self.ttm_currency_ids.push(id); + self.ttm_currency_defs.push(1); + } + None => { + self.ttm_currency_defs.push(0); + } + } + match row.ttm_has_estimated_lag { + Some(flag) => { + self.ttm_has_estimated_lag_values.push(flag); + self.ttm_has_estimated_lag_defs.push(1); + } + None => { + self.ttm_has_estimated_lag_defs.push(0); + } + } + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.effective_known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + self.has_estimated_lag.clear(); + self.period_end.clear(); + self.fiscal_period_ids.clear(); + self.fiscal_period_interner.clear(); + self.currency_ids.clear(); + self.currency_interner.clear(); + self.period_known_at_micros.clear(); + self.revenue.clear(); + self.net_income.clear(); + self.operating_cash_flow.clear(); + self.total_assets.clear(); + self.total_equity.clear(); + self.shares_outstanding.clear(); + self.ttm_revenue.clear(); + self.ttm_net_income.clear(); + self.ttm_operating_cash_flow.clear(); + self.ttm_period_end_values.clear(); + self.ttm_period_end_defs.clear(); + self.ttm_currency_ids.clear(); + self.ttm_currency_defs.clear(); + self.ttm_currency_interner.clear(); + self.ttm_has_estimated_lag_values.clear(); + self.ttm_has_estimated_lag_defs.clear(); + } +} + +struct PartitionWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl PartitionWriter { + fn open( + dataset_dir: &Path, + year: i32, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + staging_guards: &mut BTreeMap, + ) -> Result { + let year_dir = dataset_dir.join(format!("year={year:04}")); + fs::create_dir_all(&year_dir).map_err(|source| ParquetFundamentalsError::Io { + path: year_dir.clone(), + source, + })?; + + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); + let final_path = year_dir.join("part.parquet"); + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetFundamentalsError::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<(), ParquetFundamentalsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetFundamentalsError::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. effective_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.effective_known_at_micros).map_err(map_pq)?; + // 3. 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)?; + // 4. has_estimated_lag (BOOLEAN, REQUIRED) + write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag).map_err(map_pq)?; + // 5. period_end (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.period_end).map_err(map_pq)?; + // 6. fiscal_period (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.fiscal_period_ids, + &self.buf.fiscal_period_interner, + scratch, + ) + .map_err(map_pq)?; + // 7. currency (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 8. period_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.period_known_at_micros).map_err(map_pq)?; + // 9. revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.revenue.values, + &self.buf.revenue.def_levels, + ) + .map_err(map_pq)?; + // 10. net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.net_income.values, + &self.buf.net_income.def_levels, + ) + .map_err(map_pq)?; + // 11. operating_cash_flow (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.operating_cash_flow.values, + &self.buf.operating_cash_flow.def_levels, + ) + .map_err(map_pq)?; + // 12. total_assets (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.total_assets.values, + &self.buf.total_assets.def_levels, + ) + .map_err(map_pq)?; + // 13. total_equity (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.total_equity.values, + &self.buf.total_equity.def_levels, + ) + .map_err(map_pq)?; + // 14. shares_outstanding (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.shares_outstanding.values, + &self.buf.shares_outstanding.def_levels, + ) + .map_err(map_pq)?; + // 15. ttm_revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_revenue.values, + &self.buf.ttm_revenue.def_levels, + ) + .map_err(map_pq)?; + // 16. ttm_net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_net_income.values, + &self.buf.ttm_net_income.def_levels, + ) + .map_err(map_pq)?; + // 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_operating_cash_flow.values, + &self.buf.ttm_operating_cash_flow.def_levels, + ) + .map_err(map_pq)?; + // 18. ttm_period_end (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.ttm_period_end_values, + &self.buf.ttm_period_end_defs, + ) + .map_err(map_pq)?; + // 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.ttm_currency_ids, + &self.buf.ttm_currency_defs, + &self.buf.ttm_currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) + write_optional_bool_col( + &mut rg_writer, + &self.buf.ttm_has_estimated_lag_values, + &self.buf.ttm_has_estimated_lag_defs, + ) + .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| ParquetFundamentalsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer + .flush() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetFundamentalsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedPartitionFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedPartitionFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +fn finish_with_rollback( + cause: ParquetFundamentalsError, + published: &[PublishedPartition], + extra_failure: Option, +) -> ParquetFundamentalsError { + let mut failures = Vec::new(); + if let Some(failure) = extra_failure { + failures.push(failure); + } + failures.extend(rollback_published(published)); + if failures.is_empty() { + cause + } else { + ParquetFundamentalsError::RollbackFailed { + cause: Box::new(cause), + failures, + } + } +} + +/// Streams strictly ascending `fundamentals_pit` rows into year-partitioned Zstd Parquet files at +/// `/fundamentals_pit/year=YYYY/part.parquet`, partitioned by the UTC year of +/// `effective_known_at`. +/// +/// # Sort Order & Validation +/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at_micros)`. +/// Out-of-order rows, duplicates, non-finite numeric fields, out-of-range dates/years, +/// `period_known_at_micros > effective_known_at_micros`, empty required strings, or inconsistent +/// TTM metadata return typed [`ParquetFundamentalsError`] variants with nothing published. Empty +/// input returns `Ok(FundamentalsPitWriteStats::default())` without creating +/// `/fundamentals_pit` or touching pre-existing partitions. +pub fn write_fundamentals_pit_dataset( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_fundamentals_pit_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _, _| {}, + ) +} + +fn write_fundamentals_pit_dataset_with_hooks( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, + lock_timeout: Duration, + on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(i32, &Path, Option<&Path>), +{ + write_fundamentals_pit_dataset_with_lock_and_backup_hooks( + out_dir, + rows, + options, + lock_timeout, + || {}, + on_after_backup, + ) +} + +fn write_fundamentals_pit_dataset_with_lock_and_backup_hooks( + out_dir: P, + rows: I, + options: FundamentalsPitWriteOptions, + lock_timeout: Duration, + mut on_lock_contended: G, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + G: FnMut(), + F: FnMut(i32, &Path, Option<&Path>), +{ + if options.row_group_rows == 0 { + return Err(ParquetFundamentalsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetFundamentalsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(FundamentalsPitWriteStats::default()); + }; + validate_row(first_item.borrow(), 0)?; + + let out_dir = out_dir.as_ref(); + let dataset_dir = out_dir.join("fundamentals_pit"); + let schema = + fundamentals_pit_parquet_schema().map_err(|source| ParquetFundamentalsError::Parquet { + path: dataset_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&dataset_dir).map_err(|source| ParquetFundamentalsError::Io { + path: dataset_dir.clone(), + source, + })?; + + let dataset_mu = dataset_mutex(&dataset_dir); + let _in_process_guard = match dataset_mu.try_lock() { + Ok(guard) => guard, + Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + on_lock_contended(); + dataset_mu.lock().unwrap_or_else(|err| err.into_inner()) + } + }; + let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; + + let run_id = next_run_id(); + // Declared before `writers` so reverse drop order closes file handles before unlinking `.tmp`. + let mut staging_guards: BTreeMap = BTreeMap::new(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let synced_files: Vec<(i32, SyncedPartitionFile)> = { + let mut prev_item: Option = None; + + for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { + let row = item.borrow(); + if let Some(prev) = prev_item.as_ref() { + let prev_row = prev.borrow(); + match compare_row_keys(row, prev_row) { + Ordering::Equal => { + return Err(ParquetFundamentalsError::DuplicateRow { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Less => { + return Err(ParquetFundamentalsError::UnsortedInput { + row_index, + prev_listing_id: prev_row.listing_id, + prev_effective_known_at_micros: prev_row.effective_known_at_micros, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Greater => {} + } + } + let year = validate_row(row, row_index)?; + + let pw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = PartitionWriter::open( + &dataset_dir, + year, + &run_id, + &schema, + &props, + &mut staging_guards, + )?; + entry.insert(opened) + } + }; + + pw.buf.push(row); + if pw.buf.len() == options.row_group_rows { + pw.flush_row_group(&mut scratch)?; + } + prev_item = Some(item); + } + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, PartitionWriter)> = + std::mem::take(&mut writers).into_iter().collect(); + for (year, pw) in drained { + let file = pw.finish_and_sync(&mut scratch)?; + synced.push((year, file)); + } + synced + }; + + let mut stats = FundamentalsPitWriteStats::default(); + let mut published: Vec = Vec::with_capacity(synced_files.len()); + for (year, file) in synced_files { + let backup_path = match fs::symlink_metadata(&file.final_path) { + Ok(meta) if !meta.is_dir() => { + match create_backup_preserving_live(&file.final_path, &run_id) { + Ok(bak) => Some(bak), + Err(err) => { + return Err(finish_with_rollback(err.into(), &published, None)); + } + } + } + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + let err = ParquetFundamentalsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, None)); + } + }; + + on_after_backup(year, &file.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { + let extra_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: file.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let err = ParquetFundamentalsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, extra_failure)); + } + + if let Some(guard) = staging_guards.get_mut(&year) { + guard.disarm(); + } + + published.push(PublishedPartition { + final_path: file.final_path, + backup_path, + }); + stats.rows_written += file.rows_written; + stats.files_written += 1; + stats.row_groups_written += file.row_groups_written; + stats.bytes_written += file.bytes; + stats.rows_by_year.insert(year, file.rows_written); + } + + for part in &published { + if let Some(bak) = &part.backup_path { + let _ = fs::remove_file(bak); + } + } + + Ok(stats) +} + +#[cfg(test)] +#[path = "parquet_fundamentals_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs new file mode 100644 index 00000000..eedf655e --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -0,0 +1,1537 @@ +//! Schema, round-trip, PIT restatement replay, partitioning, validation, and atomic-rollback +//! tests for `parquet_fundamentals`. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use parquet::basic::{ + Compression, ConvertedType, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, + write_fundamentals_pit_dataset_with_hooks, FundamentalsPitParquetRow, + FundamentalsPitWriteOptions, FundamentalsPitWriteStats, ParquetFundamentalsError, + DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +use crate::events::{ + partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, + FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, StatutoryLagVenue, +}; +use crate::parquet_publish::DEFAULT_LOCK_TIMEOUT; +use crate::split::ymd_to_epoch_days; + +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-fundamentals-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(year: i32, month: u32, day: u32) -> i32 { + ymd_to_epoch_days(year, month, day).expect("valid test date") +} + +fn utc_micros( + year: i32, + month: u32, + day_of_month: u32, + hour: u8, + minute: u8, + second: u8, + micro: i64, +) -> i64 { + let epoch_day = day(year, month, day_of_month); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 + micro +} + +fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + fn walk(dir: &Path) { + for entry in fs::read_dir(dir).expect("read_dir") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(&path); + } else { + let name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or_default(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file left behind: {}", + path.display() + ); + } + } + } + walk(dir); +} + +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 meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_rows = meta.row_group(rg_idx).num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_opt_i32_col = |col_idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read optional i32 records"); + assert!(n > 0, "unexpected short read in opt INT32 column {col_idx}"); + read += n; + } + } + _ => panic!("expected optional INT32 column at index {col_idx}"), + } + let mut val_iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_bool_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read bool records"); + assert!(n > 0, "unexpected short read in BOOLEAN column {col_idx}"); + read += n; + } + } + _ => panic!("expected BOOLEAN column at index {col_idx}"), + } + vals + }; + + let read_opt_bool_col = |col_idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read optional bool records"); + assert!(n > 0, "unexpected short read in opt BOOLEAN column {col_idx}"); + read += n; + } + } + _ => panic!("expected optional BOOLEAN column at index {col_idx}"), + } + let mut val_iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + let read_opt_f64_col = |col_idx: usize| -> Vec> { + let mut vals = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .expect("read optional f64 records"); + assert!(n > 0, "unexpected short read in DOUBLE column {col_idx}"); + read += n; + } + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + let mut val_iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}"); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let read_opt_str_col = |col_idx: usize| -> Vec> { + let mut raw = Vec::new(); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut raw) + .expect("read optional byte_array records"); + assert!( + n > 0, + "unexpected short read in opt BYTE_ARRAY column {col_idx}" + ); + read += n; + } + } + _ => panic!("expected optional BYTE_ARRAY column at index {col_idx}"), + } + let mut val_iter = raw.into_iter().map(|b| { + std::str::from_utf8(b.data()) + .expect("valid utf8") + .to_string() + }); + defs.into_iter() + .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .collect() + }; + + // Positional 20-column decode matching fundamentals_pit_parquet_schema(). + let listing_ids = read_i32_col(0); + let effective_known_at = read_i64_col(1); + let known_at_source = read_str_col(2); + let has_estimated_lag = read_bool_col(3); + let period_end = read_i32_col(4); + let fiscal_period = read_str_col(5); + let currency = read_str_col(6); + let period_known_at = read_i64_col(7); + let revenue = read_opt_f64_col(8); + let net_income = read_opt_f64_col(9); + let operating_cash_flow = read_opt_f64_col(10); + let total_assets = read_opt_f64_col(11); + let total_equity = read_opt_f64_col(12); + let shares_outstanding = read_opt_f64_col(13); + let ttm_revenue = read_opt_f64_col(14); + let ttm_net_income = read_opt_f64_col(15); + let ttm_operating_cash_flow = read_opt_f64_col(16); + let ttm_period_end = read_opt_i32_col(17); + let ttm_currency = read_opt_str_col(18); + let ttm_has_estimated_lag = read_opt_bool_col(19); + + for i in 0..rg_rows { + out.push(FundamentalsPitParquetRow { + listing_id: listing_ids[i], + effective_known_at_micros: effective_known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: Cow::Owned(fiscal_period[i].clone()), + currency: Cow::Owned(currency[i].clone()), + period_known_at_micros: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone().map(Cow::Owned), + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + + out +} + +fn assert_row_matches_snapshot_bit_for_bit( + actual: &FundamentalsPitParquetRow, + snapshot: &FundamentalsSnapshot, +) { + let latest = snapshot + .periods + .first() + .expect("snapshot must have at least one period"); + assert_eq!(actual.listing_id, snapshot.key); + assert_eq!( + actual.effective_known_at_micros, + snapshot.effective_known_at_utc_micros + ); + assert_eq!(actual.known_at_source.as_ref(), snapshot.known_at_source); + assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag); + assert_eq!(actual.period_end, latest.period_end); + assert_eq!(actual.fiscal_period.as_ref(), latest.fiscal_period.as_str()); + assert_eq!(actual.currency.as_ref(), latest.currency.as_str()); + assert_eq!(actual.period_known_at_micros, latest.known_at_utc_micros); + + assert_eq!( + actual.revenue.map(f64::to_bits), + latest.fields.revenue.map(f64::to_bits) + ); + assert_eq!( + actual.net_income.map(f64::to_bits), + latest.fields.net_income.map(f64::to_bits) + ); + assert_eq!( + actual.operating_cash_flow.map(f64::to_bits), + latest.fields.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!( + actual.total_assets.map(f64::to_bits), + latest.fields.total_assets.map(f64::to_bits) + ); + assert_eq!( + actual.total_equity.map(f64::to_bits), + latest.fields.total_equity.map(f64::to_bits) + ); + assert_eq!( + actual.shares_outstanding.map(f64::to_bits), + latest.fields.shares_outstanding.map(f64::to_bits) + ); + + match &snapshot.ttm { + Some(ttm) => { + assert_eq!( + actual.ttm_revenue.map(f64::to_bits), + ttm.flows.revenue.map(f64::to_bits) + ); + assert_eq!( + actual.ttm_net_income.map(f64::to_bits), + ttm.flows.net_income.map(f64::to_bits) + ); + assert_eq!( + actual.ttm_operating_cash_flow.map(f64::to_bits), + ttm.flows.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!(actual.ttm_period_end, Some(ttm.ending_period_end)); + assert_eq!(actual.ttm_currency.as_deref(), Some(ttm.currency.as_str())); + assert_eq!(actual.ttm_has_estimated_lag, Some(ttm.has_estimated_lag)); + } + None => { + assert_eq!(actual.ttm_revenue, None); + assert_eq!(actual.ttm_net_income, None); + assert_eq!(actual.ttm_operating_cash_flow, None); + assert_eq!(actual.ttm_period_end, None); + assert_eq!(actual.ttm_currency, None); + assert_eq!(actual.ttm_has_estimated_lag, None); + } + } +} + +fn assert_row_bit_eq(a: &FundamentalsPitParquetRow, b: &FundamentalsPitParquetRow) { + assert_eq!(a.listing_id, b.listing_id); + assert_eq!(a.effective_known_at_micros, b.effective_known_at_micros); + assert_eq!(a.known_at_source, b.known_at_source); + assert_eq!(a.has_estimated_lag, b.has_estimated_lag); + assert_eq!(a.period_end, b.period_end); + assert_eq!(a.fiscal_period, b.fiscal_period); + assert_eq!(a.currency, b.currency); + assert_eq!(a.period_known_at_micros, b.period_known_at_micros); + assert_eq!(a.revenue.map(f64::to_bits), b.revenue.map(f64::to_bits)); + assert_eq!( + a.net_income.map(f64::to_bits), + b.net_income.map(f64::to_bits) + ); + assert_eq!( + a.operating_cash_flow.map(f64::to_bits), + b.operating_cash_flow.map(f64::to_bits) + ); + assert_eq!( + a.total_assets.map(f64::to_bits), + b.total_assets.map(f64::to_bits) + ); + assert_eq!( + a.total_equity.map(f64::to_bits), + b.total_equity.map(f64::to_bits) + ); + assert_eq!( + a.shares_outstanding.map(f64::to_bits), + b.shares_outstanding.map(f64::to_bits) + ); + assert_eq!( + a.ttm_revenue.map(f64::to_bits), + b.ttm_revenue.map(f64::to_bits) + ); + assert_eq!( + a.ttm_net_income.map(f64::to_bits), + b.ttm_net_income.map(f64::to_bits) + ); + assert_eq!( + a.ttm_operating_cash_flow.map(f64::to_bits), + b.ttm_operating_cash_flow.map(f64::to_bits) + ); + assert_eq!(a.ttm_period_end, b.ttm_period_end); + assert_eq!(a.ttm_currency, b.ttm_currency); + assert_eq!(a.ttm_has_estimated_lag, b.ttm_has_estimated_lag); +} + +fn sample_row(listing_id: i32, effective_known_at_micros: i64) -> FundamentalsPitParquetRow { + FundamentalsPitParquetRow { + listing_id, + effective_known_at_micros, + known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + has_estimated_lag: false, + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: Cow::Borrowed("USD"), + period_known_at_micros: effective_known_at_micros, + revenue: Some(100.0), + net_income: Some(15.0), + operating_cash_flow: Some(22.0), + total_assets: Some(500.0), + total_equity: Some(250.0), + shares_outstanding: Some(10_000_000.0), + ttm_revenue: Some(400.0), + ttm_net_income: Some(60.0), + ttm_operating_cash_flow: Some(88.0), + ttm_period_end: Some(day(2024, 3, 31)), + ttm_currency: Some(Cow::Borrowed("USD")), + ttm_has_estimated_lag: Some(false), + } +} + +#[test] +fn schema_matches_contract_columns_types_nullability_and_order() { + let schema = fundamentals_pit_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "fundamentals_pit"); + + let fields = schema.get_fields(); + assert_eq!(fields.len(), 20); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 20] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "effective_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, + ), + ( + "has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "period_end", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "fiscal_period", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "period_known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "revenue", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "net_income", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "operating_cash_flow", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "total_assets", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "total_equity", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "shares_outstanding", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_revenue", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_net_income", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_operating_cash_flow", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "ttm_period_end", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ttm_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "ttm_has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let field = &fields[idx]; + assert_eq!(field.name(), name, "column {idx} name"); + assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); + assert_eq!( + field.get_basic_info().repetition(), + rep, + "column {idx} repetition" + ); + assert_eq!( + field.get_basic_info().logical_type_ref().cloned(), + logical, + "column {idx} logical type" + ); + assert_eq!( + field.get_basic_info().converted_type(), + converted, + "column {idx} converted type" + ); + } +} + +#[test] +fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() { + let tmp = TempDirGuard::new("builder-roundtrip"); + + let venues = BTreeMap::from([ + (10_i32, StatutoryLagVenue::UsTsx), + (20_i32, StatutoryLagVenue::TsxvCse), + ]); + + let observations = vec![ + // Listing 10: 4 consecutive quarters (Q2 2023 .. Q1 2024), with distinct flow values + // and a missing operating_cash_flow in Q4 2023 so TTM operating_cash_flow is None while + // ttm_revenue and ttm_net_income are populated. + FinancialObservation { + key: 10_i32, + period_end: day(2023, 6, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 8, 2)), + fields: FundamentalsFields { + revenue: Some(101.25), + net_income: Some(11.5), + operating_cash_flow: Some(19.75), + total_assets: Some(1_000.0), + total_equity: Some(400.0), + shares_outstanding: Some(50_000_000.0), + }, + }, + FinancialObservation { + key: 10_i32, + period_end: day(2023, 9, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 11, 3)), + fields: FundamentalsFields { + revenue: Some(110.5), + net_income: Some(12.25), + operating_cash_flow: Some(21.0), + total_assets: None, + total_equity: Some(415.0), + shares_outstanding: Some(50_100_000.0), + }, + }, + FinancialObservation { + key: 10_i32, + period_end: day(2023, 12, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 2, 14)), + fields: FundamentalsFields { + revenue: Some(125.0), + net_income: Some(14.0), + operating_cash_flow: None, + total_assets: Some(1_120.0), + total_equity: None, + shares_outstanding: Some(50_200_000.0), + }, + }, + FinancialObservation { + key: 10_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 5, 1)), + fields: FundamentalsFields { + revenue: Some(130.75), + net_income: Some(16.5), + operating_cash_flow: Some(24.25), + total_assets: Some(1_150.0), + total_equity: Some(440.0), + shares_outstanding: None, + }, + }, + // Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE), ttm == None. + FinancialObservation { + key: 20_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "CAD".to_string(), + report_date: None, + fields: FundamentalsFields { + revenue: Some(-0.0), + net_income: Some(-3.5), + operating_cash_flow: None, + total_assets: Some(25.0), + total_equity: Some(12.5), + shares_outstanding: Some(8_000_000.0), + }, + }, + ]; + + let filings = vec![ + QmFiling { + key: 10_i32, + timefiled: "2023-08-02T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2023Q2".to_string()), + url: None, + }, + QmFiling { + key: 10_i32, + timefiled: "2023-11-03T16:05:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2023Q3".to_string()), + url: None, + }, + QmFiling { + key: 10_i32, + timefiled: "2024-02-14T16:15:00 EST".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2023Q4".to_string()), + url: None, + }, + QmFiling { + key: 10_i32, + timefiled: "2024-05-01T16:20:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-10-2024Q1".to_string()), + url: None, + }, + ]; + + let built = build_fundamentals_rows(observations, filings, &venues); + let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots"); + assert_eq!(snapshots.len(), 5); + + // Append a direct snapshot carrying signed negative zero (-0.0) in a statement field so we + // verify the Parquet writer preserves exact IEEE-754 bit patterns without altering them. + snapshots.push(FundamentalsSnapshot { + key: 30_i32, + effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), + known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, + has_estimated_lag: true, + periods: vec![FundamentalsPeriodSlot { + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "CAD".to_string(), + known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), + known_at_source: KNOWN_AT_SOURCE_STATUTORY_LAG, + has_estimated_lag: true, + fields: FundamentalsFields { + revenue: Some(-0.0_f64), + net_income: Some(0.0_f64), + operating_cash_flow: None, + total_assets: Some(10.0), + total_equity: None, + shares_outstanding: Some(1_000_000.0), + }, + }], + ttm: None, + }); + + let rows_from_ref: Vec = snapshots + .iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .expect("convert snapshots by ref"); + let rows_from_owned: Vec = snapshots + .clone() + .into_iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .expect("convert snapshots owned"); + assert_eq!(rows_from_ref.len(), rows_from_owned.len()); + for (a, b) in rows_from_ref.iter().zip(rows_from_owned.iter()) { + assert_row_bit_eq(a, b); + } + + let opts = FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + let stats = write_fundamentals_pit_dataset(tmp.path(), &rows_from_ref, opts) + .expect("write fundamentals_pit"); + + let expected_by_year = BTreeMap::from([(2023, 2), (2024, 4)]); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 2); + assert_eq!(stats.row_groups_written, 3); + assert_eq!(stats.rows_by_year, expected_by_year); + + let expected_schema = fundamentals_pit_parquet_schema().unwrap(); + let mut total_bytes = 0u64; + for (&year, &expected_count) in &expected_by_year { + let path = tmp + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + assert!(path.is_file(), "missing {}", path.display()); + total_bytes += fs::metadata(&path).unwrap().len(); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + assert_eq!(meta.file_metadata().num_rows() as usize, expected_count); + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "year {year} column {} must be ZSTD", + col.column_path() + ); + } + } + + let decoded = read_parquet_rows(&path); + let expected_snapshots: Vec<&FundamentalsSnapshot> = snapshots + .iter() + .filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year) + .collect(); + assert_eq!(decoded.len(), expected_snapshots.len()); + for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) { + assert_row_matches_snapshot_bit_for_bit(actual_row, snap); + } + + if year == 2024 { + // Verify signed negative zero (-0.0) survived bit-for-bit on listing 30. + let signed_zero_row = decoded + .iter() + .find(|r| r.listing_id == 30) + .expect("listing 30 row"); + assert_eq!( + signed_zero_row.revenue.map(f64::to_bits), + Some((-0.0_f64).to_bits()) + ); + assert_ne!( + signed_zero_row.revenue.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + assert_eq!( + signed_zero_row.net_income.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + + // Verify listing 10 Q1 2024 snapshot has TTM revenue & net_income populated, + // TTM operating_cash_flow None, and distinct flow values. + let ttm_row = decoded + .iter() + .find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31)) + .expect("listing 10 Q1 2024 row"); + assert_eq!(ttm_row.ttm_revenue, Some(467.5)); + assert_eq!(ttm_row.ttm_net_income, Some(54.25)); + assert_eq!(ttm_row.ttm_operating_cash_flow, None); + assert_eq!(ttm_row.ttm_period_end, Some(day(2024, 3, 31))); + assert_eq!(ttm_row.ttm_currency.as_deref(), Some("USD")); + assert_eq!(ttm_row.ttm_has_estimated_lag, Some(false)); + } + } + assert_eq!(stats.bytes_written, total_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn restated_q1_after_q2_preserves_earlier_snapshots_and_keeps_q2_as_latest_period() { + let venues = BTreeMap::from([(42_i32, StatutoryLagVenue::UsTsx)]); + + let base_observations = vec![ + FinancialObservation { + key: 42_i32, + period_end: day(2023, 6, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 8, 1)), + fields: FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(15.0), + total_assets: Some(900.0), + total_equity: Some(400.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + FinancialObservation { + key: 42_i32, + period_end: day(2023, 9, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2023, 11, 1)), + fields: FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: Some(16.0), + total_assets: Some(920.0), + total_equity: Some(410.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + FinancialObservation { + key: 42_i32, + period_end: day(2023, 12, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 2, 1)), + fields: FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(17.0), + total_assets: Some(950.0), + total_equity: Some(420.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + // Q1 2024 original filing on 2024-05-01 + FinancialObservation { + key: 42_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 5, 1)), + fields: FundamentalsFields { + revenue: Some(130.0), + net_income: Some(13.0), + operating_cash_flow: Some(18.0), + total_assets: Some(980.0), + total_equity: Some(430.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + // Q2 2024 filing on 2024-08-01 + FinancialObservation { + key: 42_i32, + period_end: day(2024, 6, 30), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 8, 1)), + fields: FundamentalsFields { + revenue: Some(140.0), + net_income: Some(14.0), + operating_cash_flow: Some(19.0), + total_assets: Some(1_010.0), + total_equity: Some(445.0), + shares_outstanding: Some(10_000_000.0), + }, + }, + ]; + + let base_filings = vec![ + QmFiling { + key: 42_i32, + timefiled: "2023-08-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q2-2023".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2023-11-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q3-2023".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2024-02-01T16:10:00 EST".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q4-2023".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2024-05-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q1-2024".to_string()), + url: None, + }, + QmFiling { + key: 42_i32, + timefiled: "2024-08-01T16:10:00 EDT".to_string(), + form_type: "10-Q".to_string(), + filing_id: Some("F-Q2-2024".to_string()), + url: None, + }, + ]; + + // Baseline run (pre-amendment) + let tmp_base = TempDirGuard::new("restatement-base"); + let base_built = build_fundamentals_rows( + base_observations.clone(), + base_filings.clone(), + &venues, + ); + let base_snaps = build_fundamentals_snapshots(&base_built.rows, 4).expect("build base snaps"); + let base_rows: Vec = base_snaps + .iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .unwrap(); + write_fundamentals_pit_dataset( + tmp_base.path(), + &base_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write baseline"); + + let mut base_decoded = read_parquet_rows( + &tmp_base + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + base_decoded.extend(read_parquet_rows( + &tmp_base + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(base_decoded.len(), 5); + + // Amended run: append Q1 2024 restatement filed on 2024-09-15 (after Q2's 2024-08-01 filing) + let mut amended_observations = base_observations; + amended_observations.push(FinancialObservation { + key: 42_i32, + period_end: day(2024, 3, 31), + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + report_date: Some(day(2024, 9, 15)), + fields: FundamentalsFields { + revenue: Some(125.0), // restated -5.0 + net_income: Some(9.0), // restated -4.0 + operating_cash_flow: None, // carried forward from Q1 original (18.0) + total_assets: Some(975.0), + total_equity: Some(426.0), + shares_outstanding: Some(10_000_000.0), + }, + }); + let mut amended_filings = base_filings; + amended_filings.push(QmFiling { + key: 42_i32, + timefiled: "2024-09-15T16:30:00 EDT".to_string(), + form_type: "10-Q/A".to_string(), + filing_id: Some("F-Q1-2024-A".to_string()), + url: None, + }); + + let tmp_amended = TempDirGuard::new("restatement-amended"); + let amended_built = build_fundamentals_rows(amended_observations, amended_filings, &venues); + let amended_snaps = + build_fundamentals_snapshots(&amended_built.rows, 4).expect("build amended snaps"); + let amended_rows: Vec = amended_snaps + .iter() + .map(FundamentalsPitParquetRow::try_from) + .collect::>() + .unwrap(); + write_fundamentals_pit_dataset( + tmp_amended.path(), + &amended_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write amended"); + + let mut amended_decoded = read_parquet_rows( + &tmp_amended + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + amended_decoded.extend(read_parquet_rows( + &tmp_amended + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(amended_decoded.len(), 6); + + // Every earlier snapshot (including Q2 on 2024-08-01) must remain bit-for-bit identical. + for i in 0..5 { + assert_row_bit_eq(&amended_decoded[i], &base_decoded[i]); + } + + let q2_row = &amended_decoded[4]; + let restatement_row = &amended_decoded[5]; + // Restatement appears as its own later effective_known_at row (2024-09-15 16:30 EDT = 20:30 UTC). + assert_eq!( + restatement_row.effective_known_at_micros, + utc_micros(2024, 9, 15, 20, 30, 0, 0) + ); + assert!(restatement_row.effective_known_at_micros > q2_row.effective_known_at_micros); + + // Q2 remains the latest period_end and period_known_at — restated Q1 never replaces Q2. + assert_eq!(restatement_row.period_end, day(2024, 6, 30)); + assert_eq!(restatement_row.period_known_at_micros, q2_row.period_known_at_micros); + assert_eq!(restatement_row.revenue, q2_row.revenue); + assert_eq!(restatement_row.net_income, q2_row.net_income); + assert_eq!( + restatement_row.operating_cash_flow, + q2_row.operating_cash_flow + ); + + // TTM flows reflect the restated Q1 (Q3 2023 + Q4 2023 + Q1 2024 restated + Q2 2024): + // baseline Q2 TTM: rev = 110+120+130+140 = 500, ni = 11+12+13+14 = 50, ocf = 16+17+18+19 = 70 + assert_eq!(q2_row.ttm_revenue, Some(500.0)); + assert_eq!(q2_row.ttm_net_income, Some(50.0)); + assert_eq!(q2_row.ttm_operating_cash_flow, Some(70.0)); + // after Q1 restatement: rev = 495, ni = 46, ocf unchanged = 70 + assert_eq!(restatement_row.ttm_revenue, Some(495.0)); + assert_eq!(restatement_row.ttm_net_income, Some(46.0)); + assert_eq!(restatement_row.ttm_operating_cash_flow, Some(70.0)); + assert_eq!(restatement_row.ttm_period_end, Some(day(2024, 6, 30))); +} + +#[test] +fn partitions_by_effective_known_at_utc_year_with_boundary_and_stats() { + let tmp_a = TempDirGuard::new("partition-boundary-a"); + let tmp_b = TempDirGuard::new("partition-boundary-b"); + + let rows = vec![ + sample_row(1, utc_micros(2023, 5, 1, 12, 0, 0, 0)), + sample_row(1, utc_micros(2023, 12, 31, 23, 59, 59, 999_999)), + sample_row(1, utc_micros(2024, 1, 1, 0, 0, 0, 0)), + sample_row(2, utc_micros(2023, 11, 15, 21, 5, 0, 0)), + sample_row(2, utc_micros(2024, 2, 10, 14, 0, 0, 0)), + ]; + + let opts = FundamentalsPitWriteOptions::default(); + let stats_a = write_fundamentals_pit_dataset(tmp_a.path(), &rows, opts).unwrap(); + let stats_b = write_fundamentals_pit_dataset(tmp_b.path(), &rows, opts).unwrap(); + assert_eq!(stats_a, stats_b); + + let expected_by_year = BTreeMap::from([(2023, 3), (2024, 2)]); + assert_eq!(stats_a.rows_written, 5); + assert_eq!(stats_a.files_written, 2); + assert_eq!(stats_a.row_groups_written, 2); + assert_eq!(stats_a.rows_by_year, expected_by_year); + + let dataset_dir = tmp_a.path().join("fundamentals_pit"); + let mut year_dirs: Vec = fs::read_dir(&dataset_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + year_dirs.sort(); + assert_eq!(year_dirs, vec!["year=2023", "year=2024"]); + + let mut total_bytes = 0u64; + for year in [2023, 2024] { + let pa = tmp_a + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + let pb = tmp_b + .path() + .join(format!("fundamentals_pit/year={year:04}/part.parquet")); + assert!(pa.is_file()); + let bytes_a = fs::read(&pa).unwrap(); + let bytes_b = fs::read(&pb).unwrap(); + assert_eq!( + bytes_a, bytes_b, + "year {year} output must be deterministic across runs" + ); + total_bytes += bytes_a.len() as u64; + + let decoded = read_parquet_rows(&pa); + assert_eq!(decoded.len(), expected_by_year[&year]); + for pair in decoded.windows(2) { + let k0 = (pair[0].listing_id, pair[0].effective_known_at_micros); + let k1 = (pair[1].listing_id, pair[1].effective_known_at_micros); + assert!(k0 < k1, "keys must be strictly increasing: {k0:?} vs {k1:?}"); + } + for row in &decoded { + assert_eq!(partition_year_utc(row.effective_known_at_micros), year); + } + } + assert_eq!(stats_a.bytes_written, total_bytes); + assert_no_transient_files(&dataset_dir); +} + +#[test] +fn empty_input_creates_no_directory_and_preserves_existing_dataset() { + let tmp_fresh = TempDirGuard::new("empty-fresh"); + let stats = write_fundamentals_pit_dataset( + tmp_fresh.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, FundamentalsPitWriteStats::default()); + assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); + + let tmp_existing = TempDirGuard::new("empty-existing"); + let seed = vec![sample_row(1, utc_micros(2024, 5, 1, 20, 0, 0, 0))]; + write_fundamentals_pit_dataset( + tmp_existing.path(), + &seed, + FundamentalsPitWriteOptions::default(), + ) + .unwrap(); + let part = tmp_existing + .path() + .join("fundamentals_pit/year=2024/part.parquet"); + let before = fs::read(&part).unwrap(); + + let stats2 = write_fundamentals_pit_dataset( + tmp_existing.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats2, FundamentalsPitWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn rejects_empty_snapshot_periods() { + let empty_snapshot = FundamentalsSnapshot:: { + key: 7, + effective_known_at_utc_micros: utc_micros(2024, 5, 1, 20, 0, 0, 0), + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + periods: Vec::new(), + ttm: None, + }; + + let err_ref = FundamentalsPitParquetRow::try_from(&empty_snapshot).unwrap_err(); + assert!(matches!( + err_ref, + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: 7, + .. + } + )); + + let err_owned = FundamentalsPitParquetRow::try_from(empty_snapshot).unwrap_err(); + assert!(matches!( + err_owned, + ParquetFundamentalsError::EmptySnapshotPeriods { + listing_id: 7, + .. + } + )); +} + +#[test] +fn rejects_duplicate_and_unsorted_keys_without_leaving_partial_output() { + let ts1 = utc_micros(2023, 8, 1, 20, 0, 0, 0); + let ts2 = utc_micros(2024, 5, 1, 20, 0, 0, 0); + + // Duplicate (listing_id, effective_known_at) + let tmp_dup = TempDirGuard::new("reject-dup"); + let dup_rows = vec![sample_row(1, ts1), sample_row(1, ts1)]; + let err = write_fundamentals_pit_dataset( + tmp_dup.path(), + &dup_rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetFundamentalsError::DuplicateRow { + row_index: 1, + listing_id: 1, + .. + } + )); + assert!(!tmp_dup + .path() + .join("fundamentals_pit/year=2023/part.parquet") + .exists()); + assert_no_transient_files(&tmp_dup.path().join("fundamentals_pit")); + + // Unsorted keys (later row has smaller effective_known_at for same listing) + let tmp_unsorted = TempDirGuard::new("reject-unsorted"); + let unsorted_rows = vec![sample_row(1, ts2), sample_row(1, ts1)]; + let err = write_fundamentals_pit_dataset( + tmp_unsorted.path(), + &unsorted_rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 1, + listing_id: 1, + .. + } + )); + assert!(!tmp_unsorted + .path() + .join("fundamentals_pit/year=2024/part.parquet") + .exists()); + assert_no_transient_files(&tmp_unsorted.path().join("fundamentals_pit")); +} + +#[test] +fn rejects_non_finite_statement_and_ttm_values_without_leaving_partial_output() { + let ts_2023 = utc_micros(2023, 8, 1, 20, 0, 0, 0); + let ts_2024 = utc_micros(2024, 5, 1, 20, 0, 0, 0); + + type RowMutator = fn(&mut FundamentalsPitParquetRow); + let cases: [(&str, RowMutator); 4] = [ + ("revenue", |r| r.revenue = Some(f64::NAN)), + ("total_assets", |r| r.total_assets = Some(f64::INFINITY)), + ("ttm_revenue", |r| r.ttm_revenue = Some(f64::NEG_INFINITY)), + ("ttm_operating_cash_flow", |r| { + r.ttm_operating_cash_flow = Some(f64::NAN) + }), + ]; + + for (expected_field, mutate) in cases { + let tmp = TempDirGuard::new(&format!("reject-nonfinite-{expected_field}")); + let good = sample_row(1, ts_2023); + let mut bad = sample_row(1, ts_2024); + mutate(&mut bad); + + let err = write_fundamentals_pit_dataset( + tmp.path(), + &[good, bad], + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + match err { + ParquetFundamentalsError::NonFiniteValue { + row_index: 1, + field, + .. + } => assert_eq!(field, expected_field), + other => panic!("expected NonFiniteValue({expected_field}), got {other:?}"), + } + assert!(!tmp + .path() + .join("fundamentals_pit/year=2023/part.parquet") + .exists()); + assert!(!tmp + .path() + .join("fundamentals_pit/year=2024/part.parquet") + .exists()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + } +} + +#[test] +fn rejects_invalid_options_dates_strings_and_inconsistent_ttm_metadata() { + let tmp = TempDirGuard::new("reject-validation"); + let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); + + // row_group_rows == 0 + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[sample_row(1, ts)], + FundamentalsPitWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ), + Err(ParquetFundamentalsError::InvalidRowGroupRows) + )); + + // Invalid Zstd level + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[sample_row(1, ts)], + FundamentalsPitWriteOptions { + row_group_rows: 10, + zstd_level: 999, + }, + ), + Err(ParquetFundamentalsError::InvalidZstdLevel { level: 999 }) + )); + + // Partition year out of range + let mut bad_year = sample_row(1, utc_micros(MIN_PARQUET_YEAR - 1, 6, 1, 0, 0, 0, 0)); + bad_year.period_known_at_micros = bad_year.effective_known_at_micros; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[bad_year], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::PartitionYearOutOfRange { .. }) + )); + + // period_end out of range + let mut bad_period = sample_row(1, ts); + bad_period.period_end = day(MAX_PARQUET_YEAR + 1, 1, 1); + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[bad_period], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::PeriodEndOutOfRange { .. }) + )); + + // period_known_at > effective_known_at + let mut future_period_known = sample_row(1, ts); + future_period_known.period_known_at_micros = ts + 1; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[future_period_known], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::PeriodKnownAtAfterEffectiveKnownAt { .. }) + )); + + // Empty required strings + let mut empty_source = sample_row(1, ts); + empty_source.known_at_source = Cow::Borrowed(" "); + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[empty_source], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::EmptyKnownAtSource { .. }) + )); + + // Partial TTM metadata (ttm_currency missing while ttm_period_end present) + let mut partial_ttm = sample_row(1, ts); + partial_ttm.ttm_currency = None; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[partial_ttm], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::InconsistentTtmMetadata { .. }) + )); + + // TTM flow present while all TTM metadata is None + let mut orphan_ttm_flow = sample_row(1, ts); + orphan_ttm_flow.ttm_period_end = None; + orphan_ttm_flow.ttm_currency = None; + orphan_ttm_flow.ttm_has_estimated_lag = None; + assert!(matches!( + write_fundamentals_pit_dataset( + tmp.path(), + &[orphan_ttm_flow], + FundamentalsPitWriteOptions::default(), + ), + Err(ParquetFundamentalsError::InconsistentTtmMetadata { .. }) + )); + + assert!(!tmp.path().join("fundamentals_pit").exists()); +} + +#[test] +fn failed_later_year_publish_rolls_back_and_preserves_existing_partitions_byte_for_byte() { + let tmp = TempDirGuard::new("rollback-existing"); + + // Seed an existing 2023 partition. + let initial_rows = vec![sample_row(1, utc_micros(2023, 8, 1, 20, 0, 0, 0))]; + write_fundamentals_pit_dataset( + tmp.path(), + &initial_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("seed initial 2023 partition"); + + let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let original_2023_bytes = fs::read(&part_2023).unwrap(); + + // Attempt a 2-year write (2023 update + 2024 new) where publishing 2024 fails because a + // directory occupies `year=2024/part.parquet` right before rename. + let mut updated_2023 = sample_row(1, utc_micros(2023, 8, 1, 20, 0, 0, 0)); + updated_2023.revenue = Some(999.0); + let new_2024 = sample_row(1, utc_micros(2024, 5, 1, 20, 0, 0, 0)); + + let err = write_fundamentals_pit_dataset_with_hooks( + tmp.path(), + &[updated_2023, new_2024], + FundamentalsPitWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, final_path, _bak| { + if year == 2024 { + fs::create_dir_all(final_path).expect("inject directory conflict at 2024 target"); + } + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetFundamentalsError::Io { .. })); + + // 2023 must be restored byte-for-byte; 2024 must not contain a published file. + assert_eq!(fs::read(&part_2023).unwrap(), original_2023_bytes); + assert!(part_2024.is_dir(), "injected blocker dir remains untouched"); + fs::remove_dir(&part_2024).unwrap(); + assert!(!part_2024.exists()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +}