diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 9f973afe..278c1999 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -217,9 +217,9 @@ Schemas: - **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`. - **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`. - **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, )`. -- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes: +- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes: $$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$ - forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2. + forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted). - **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`. - **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`. - **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`. diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6244dcc7..6b795fef 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -24,6 +24,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; @@ -160,6 +161,11 @@ 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, FundamentalsPitLatestPeriod, + 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..9e804d26 --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -0,0 +1,1327 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. +//! +//! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column +//! contract schema in `design/DATA-CONTRACTS.md` (§3A): +//! +//! 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_period_end` (`INT32`, `OPTIONAL`, `DATE`) +//! 16. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 17. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) +//! 18. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) +//! 19. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) +//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) +//! +//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the +//! builder-provided 4-quarter `ttm` summary from a [`FundamentalsSnapshot`]. Lagged period slots +//! (`periods[1..]`) are intentionally omitted from the flat Parquet representation; TTM values +//! computed by [`crate::fundamentals::build_fundamentals_snapshots`] are preserved as-is. + +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::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::events::partition_year_utc; +use crate::fundamentals::{FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm}; +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_bool_col, 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}; + +/// Latest visible period projection flattened into a [`FundamentalsPitParquetRow`]. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPitLatestPeriod { + pub period_end: i32, + pub fiscal_period: Cow<'static, str>, + pub currency: String, + pub period_known_at_micros: i64, + pub fields: FundamentalsFields, +} + +/// Single `fundamentals_pit` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. +/// +/// Only `periods[0]` (the latest visible period) and `ttm` are stored; lagged slots +/// (`periods[1..]`) are intentionally omitted. +#[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, + latest_period: Option, + pub ttm: Option, +} + +impl FundamentalsPitParquetRow { + /// Constructs a valid `fundamentals_pit` Parquet row with an explicit latest visible period. + pub fn new( + listing_id: i32, + effective_known_at_micros: i64, + known_at_source: Cow<'static, str>, + has_estimated_lag: bool, + latest_period: FundamentalsPitLatestPeriod, + ttm: Option, + ) -> Self { + Self { + listing_id, + effective_known_at_micros, + known_at_source, + has_estimated_lag, + latest_period: Some(latest_period), + ttm, + } + } + + /// Returns the flattened latest visible period (`periods[0]`), or `None` if converted from a + /// malformed snapshot with an empty `periods` vector. + #[inline] + pub fn latest_period(&self) -> Option<&FundamentalsPitLatestPeriod> { + self.latest_period.as_ref() + } +} + +impl From<&FundamentalsSnapshot> for FundamentalsPitParquetRow { + fn from(snapshot: &FundamentalsSnapshot) -> Self { + let latest_period = snapshot.periods.first().map(|slot| FundamentalsPitLatestPeriod { + period_end: slot.period_end, + fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), + currency: slot.currency.clone(), + period_known_at_micros: slot.known_at_utc_micros, + fields: slot.fields, + }); + 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, + latest_period, + ttm: snapshot.ttm.clone(), + } + } +} + +impl From> for FundamentalsPitParquetRow { + fn from(snapshot: FundamentalsSnapshot) -> Self { + let latest_period = snapshot + .periods + .into_iter() + .next() + .map(|slot| FundamentalsPitLatestPeriod { + period_end: slot.period_end, + fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), + currency: slot.currency, + period_known_at_micros: slot.known_at_utc_micros, + fields: slot.fields, + }); + 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, + latest_period, + ttm: snapshot.ttm, + } + } +} + +/// 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 [`write_fundamentals_pit_dataset`]. +#[derive(Debug)] +pub enum ParquetFundamentalsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + EmptyPeriods { + row_index: usize, + 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, + }, + 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, + }, + 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::EmptyPeriods { + row_index, + listing_id, + effective_known_at_micros, + } => write!( + f, + "snapshot has empty periods at row {row_index} for (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" + ), + 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::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" + ), + Self::NonFiniteValue { + row_index, + listing_id, + effective_known_at_micros, + field, + value, + } => write!( + f, + "non-finite {field} value {value} 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` per `design/DATA-CONTRACTS.md` (§3A). +pub fn fundamentals_pit_parquet_schema() -> Result { + let fields: Vec = vec![ + // 1. listing_id INT32 REQUIRED + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + // 2. effective_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) + 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()?, + ), + // 3. known_at_source STRING REQUIRED + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 4. has_estimated_lag BOOLEAN REQUIRED + Arc::new( + Type::primitive_type_builder("has_estimated_lag", PhysicalType::BOOLEAN) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + // 5. period_end INT32 DATE REQUIRED + Arc::new( + Type::primitive_type_builder("period_end", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + // 6. fiscal_period STRING REQUIRED + Arc::new( + Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 7. currency STRING REQUIRED + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 8. period_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) + 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()?, + ), + // 9-14. latest-period financial metrics DOUBLE OPTIONAL + 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()?, + ), + // 15. ttm_period_end INT32 DATE OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + // 16. ttm_currency STRING OPTIONAL + Arc::new( + Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + // 17-19. TTM flow sums DOUBLE OPTIONAL + 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()?, + ), + // 20. ttm_has_estimated_lag BOOLEAN OPTIONAL + 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 check_opt_finite( + row: &FundamentalsPitParquetRow, + row_index: usize, + field: &'static str, + val: Option, +) -> Result<(), ParquetFundamentalsError> { + if let Some(value) = val { + if !value.is_finite() { + return Err(ParquetFundamentalsError::NonFiniteValue { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + field, + value, + }); + } + } + Ok(()) +} + +#[inline] +fn validate_row( + row: &FundamentalsPitParquetRow, + row_index: usize, +) -> Result<(i32, &FundamentalsPitLatestPeriod), ParquetFundamentalsError> { + let Some(latest) = row.latest_period.as_ref() else { + return Err(ParquetFundamentalsError::EmptyPeriods { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + }; + + 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, + }); + } + + 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 latest.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 latest.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", latest.fields.revenue)?; + check_opt_finite(row, row_index, "net_income", latest.fields.net_income)?; + check_opt_finite( + row, + row_index, + "operating_cash_flow", + latest.fields.operating_cash_flow, + )?; + check_opt_finite(row, row_index, "total_assets", latest.fields.total_assets)?; + check_opt_finite(row, row_index, "total_equity", latest.fields.total_equity)?; + check_opt_finite( + row, + row_index, + "shares_outstanding", + latest.fields.shares_outstanding, + )?; + + if let Some(ttm) = row.ttm.as_ref() { + if ttm.currency.trim().is_empty() { + return Err(ParquetFundamentalsError::EmptyTtmCurrency { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + check_opt_finite(row, row_index, "ttm_revenue", ttm.flows.revenue)?; + check_opt_finite(row, row_index, "ttm_net_income", ttm.flows.net_income)?; + check_opt_finite( + row, + row_index, + "ttm_operating_cash_flow", + ttm.flows.operating_cash_flow, + )?; + } + + Ok((year, latest)) +} + +#[inline] +fn push_opt_f64(values: &mut Vec, defs: &mut Vec, val: Option) { + match val { + Some(v) => { + values.push(v); + defs.push(1); + } + None => { + defs.push(0); + } + } +} + +#[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_values: Vec, + revenue_def: Vec, + net_income_values: Vec, + net_income_def: Vec, + operating_cash_flow_values: Vec, + operating_cash_flow_def: Vec, + total_assets_values: Vec, + total_assets_def: Vec, + total_equity_values: Vec, + total_equity_def: Vec, + shares_outstanding_values: Vec, + shares_outstanding_def: Vec, + ttm_period_end_values: Vec, + ttm_period_end_def: Vec, + ttm_currency_ids: Vec, + ttm_currency_def: Vec, + ttm_currency_interner: StringInterner, + ttm_revenue_values: Vec, + ttm_revenue_def: Vec, + ttm_net_income_values: Vec, + ttm_net_income_def: Vec, + ttm_operating_cash_flow_values: Vec, + ttm_operating_cash_flow_def: Vec, + ttm_has_estimated_lag_values: Vec, + ttm_has_estimated_lag_def: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &FundamentalsPitParquetRow, latest: &FundamentalsPitLatestPeriod) { + 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(latest.period_end); + let fp_id = self + .fiscal_period_interner + .intern(latest.fiscal_period.as_ref()); + self.fiscal_period_ids.push(fp_id); + let cur_id = self.currency_interner.intern(latest.currency.as_str()); + self.currency_ids.push(cur_id); + self.period_known_at_micros + .push(latest.period_known_at_micros); + + push_opt_f64( + &mut self.revenue_values, + &mut self.revenue_def, + latest.fields.revenue, + ); + push_opt_f64( + &mut self.net_income_values, + &mut self.net_income_def, + latest.fields.net_income, + ); + push_opt_f64( + &mut self.operating_cash_flow_values, + &mut self.operating_cash_flow_def, + latest.fields.operating_cash_flow, + ); + push_opt_f64( + &mut self.total_assets_values, + &mut self.total_assets_def, + latest.fields.total_assets, + ); + push_opt_f64( + &mut self.total_equity_values, + &mut self.total_equity_def, + latest.fields.total_equity, + ); + push_opt_f64( + &mut self.shares_outstanding_values, + &mut self.shares_outstanding_def, + latest.fields.shares_outstanding, + ); + + match row.ttm.as_ref() { + Some(ttm) => { + self.ttm_period_end_values.push(ttm.ending_period_end); + self.ttm_period_end_def.push(1); + let ttm_cur_id = self.ttm_currency_interner.intern(ttm.currency.as_str()); + self.ttm_currency_ids.push(ttm_cur_id); + self.ttm_currency_def.push(1); + push_opt_f64( + &mut self.ttm_revenue_values, + &mut self.ttm_revenue_def, + ttm.flows.revenue, + ); + push_opt_f64( + &mut self.ttm_net_income_values, + &mut self.ttm_net_income_def, + ttm.flows.net_income, + ); + push_opt_f64( + &mut self.ttm_operating_cash_flow_values, + &mut self.ttm_operating_cash_flow_def, + ttm.flows.operating_cash_flow, + ); + self.ttm_has_estimated_lag_values + .push(ttm.has_estimated_lag); + self.ttm_has_estimated_lag_def.push(1); + } + None => { + self.ttm_period_end_def.push(0); + self.ttm_currency_def.push(0); + self.ttm_revenue_def.push(0); + self.ttm_net_income_def.push(0); + self.ttm_operating_cash_flow_def.push(0); + self.ttm_has_estimated_lag_def.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_values.clear(); + self.revenue_def.clear(); + self.net_income_values.clear(); + self.net_income_def.clear(); + self.operating_cash_flow_values.clear(); + self.operating_cash_flow_def.clear(); + self.total_assets_values.clear(); + self.total_assets_def.clear(); + self.total_equity_values.clear(); + self.total_equity_def.clear(); + self.shares_outstanding_values.clear(); + self.shares_outstanding_def.clear(); + self.ttm_period_end_values.clear(); + self.ttm_period_end_def.clear(); + self.ttm_currency_ids.clear(); + self.ttm_currency_def.clear(); + self.ttm_currency_interner.clear(); + self.ttm_revenue_values.clear(); + self.ttm_revenue_def.clear(); + self.ttm_net_income_values.clear(); + self.ttm_net_income_def.clear(); + self.ttm_operating_cash_flow_values.clear(); + self.ttm_operating_cash_flow_def.clear(); + self.ttm_has_estimated_lag_values.clear(); + self.ttm_has_estimated_lag_def.clear(); + } +} + +struct YearWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl YearWriter { + 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, None).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, + ) + .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, + ) + .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, + ) + .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, + ) + .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, + ) + .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, + ) + .map_err(map_pq)?; + // 15. ttm_period_end (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.ttm_period_end_values, + &self.buf.ttm_period_end_def, + ) + .map_err(map_pq)?; + // 16. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.ttm_currency_ids, + &self.buf.ttm_currency_def, + &self.buf.ttm_currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 17. ttm_revenue (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_revenue_values, + &self.buf.ttm_revenue_def, + ) + .map_err(map_pq)?; + // 18. ttm_net_income (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ttm_net_income_values, + &self.buf.ttm_net_income_def, + ) + .map_err(map_pq)?; + // 19. 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, + ) + .map_err(map_pq)?; + // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) + write_bool_col( + &mut rg_writer, + &self.buf.ttm_has_estimated_lag_values, + Some(&self.buf.ttm_has_estimated_lag_def), + ) + .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(SyncedYearFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedYearFile { + 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 `(listing_id, effective_known_at)` snapshot 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)`. +/// Out-of-order rows, duplicate keys, snapshots with empty `periods`, partition years outside +/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, empty string metadata fields, and non-finite numeric +/// values return typed [`ParquetFundamentalsError`] variants with nothing published. Empty input +/// returns `Ok(FundamentalsPitWriteStats::default())` without creating +/// `/fundamentals_pit` or touching pre-existing partitions. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/fundamentals_pit` directory are serialized via +/// an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year +/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), +/// flushed, and `sync_all`'d before publication. Pre-existing `part.parquet` files are backed up +/// in place (hard link with exclusive copy fallback) so the live path remains readable until +/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before +/// owned staging files are unlinked, replaced partitions are restored from backup, and newly +/// published partitions are removed (reporting rollback errors via +/// [`ParquetFundamentalsError::RollbackFailed`]). +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, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + 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 = 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 Rust's reverse drop order closes all Parquet file handles + // before unlinking owned `.tmp` staging files on error or panic unwind. + 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, SyncedYearFile)> = { + let mut prev_key: Option<(i32, i64)> = None; + + for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { + let row = item.borrow(); + let key = (row.listing_id, row.effective_known_at_micros); + if let Some((prev_listing_id, prev_effective_known_at_micros)) = prev_key { + match key.cmp(&(prev_listing_id, prev_effective_known_at_micros)) { + 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_effective_known_at_micros, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + } + Ordering::Greater => {} + } + } + + let (year, latest) = validate_row(row, row_index)?; + + let yw = match writers.entry(year) { + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::btree_map::Entry::Vacant(entry) => { + let opened = YearWriter::open( + &dataset_dir, + year, + &run_id, + &schema, + &props, + &mut staging_guards, + )?; + entry.insert(opened) + } + }; + + yw.buf.push(row, latest); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; + } + prev_key = Some(key); + } + + let mut synced = Vec::with_capacity(writers.len()); + let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); + for (year, yw) in drained { + let file = yw.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)); + } + } + } + // Directory occupying final_path: leave it in place so the rename below fails + // cleanly and triggers rollback of all earlier partitions. + 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..7b4b5712 --- /dev/null +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -0,0 +1,1265 @@ +//! Round-trip, schema, 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, FundamentalsPitLatestPeriod, + FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, + ParquetFundamentalsError, DEFAULT_ZSTD_LEVEL, +}; +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, FundamentalsSnapshot, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, +}; +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(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8, micro: i64) -> i64 { + let epoch_day = day(y, m, d); + 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 filing(key: i32, timefiled: &str, form_type: &str) -> QmFiling { + QmFiling { + key, + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: None, + url: None, + } +} + +fn obs( + key: i32, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: &str, + report_date: Option, + fields: FundamentalsFields, +) -> FinancialObservation { + FinancialObservation { + key, + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + } +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedFundamentalsPitRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_has_estimated_lag: Option, +} + +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_req_i32 = |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 req i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 at col {col_idx}"), + } + vals + }; + + let read_opt_i32 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + 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 opt i32"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_i64 = |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 req i64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 at col {col_idx}"), + } + vals + }; + + let read_req_bool = |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 req bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN at col {col_idx}"), + } + vals + }; + + let read_opt_bool = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + 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 opt bool"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_opt_f64 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + 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 opt f64"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_str = |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 req str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY at col {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let read_opt_str = |col_idx: usize| -> Vec> { + let mut raw = Vec::with_capacity(rg_rows); + 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 opt str"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY at col {col_idx}"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let s = std::str::from_utf8(raw[vi].data()) + .expect("valid utf8") + .to_string(); + vi += 1; + Some(s) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let listing_id = read_req_i32(0); + let effective_known_at = read_req_i64(1); + let known_at_source = read_req_str(2); + let has_estimated_lag = read_req_bool(3); + let period_end = read_req_i32(4); + let fiscal_period = read_req_str(5); + let currency = read_req_str(6); + let period_known_at = read_req_i64(7); + let revenue = read_opt_f64(8); + let net_income = read_opt_f64(9); + let operating_cash_flow = read_opt_f64(10); + let total_assets = read_opt_f64(11); + let total_equity = read_opt_f64(12); + let shares_outstanding = read_opt_f64(13); + let ttm_period_end = read_opt_i32(14); + let ttm_currency = read_opt_str(15); + let ttm_revenue = read_opt_f64(16); + let ttm_net_income = read_opt_f64(17); + let ttm_operating_cash_flow = read_opt_f64(18); + let ttm_has_estimated_lag = read_opt_bool(19); + + for i in 0..rg_rows { + out.push(DecodedFundamentalsPitRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: 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_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + + out +} + +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 make_row( + listing_id: i32, + effective_known_at_micros: i64, + period_end: i32, + revenue: Option, + ttm: Option, +) -> FundamentalsPitParquetRow { + FundamentalsPitParquetRow::new( + listing_id, + effective_known_at_micros, + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end, + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: effective_known_at_micros, + fields: FundamentalsFields { + revenue, + net_income: revenue.map(|r| r * 0.1), + operating_cash_flow: revenue.map(|r| r * 0.15), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + }, + ttm, + ) +} + +#[test] +fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { + let tmp = TempDirGuard::new("schema"); + + // 1) Row with no TTM (all 6 ttm_* columns must be null) and some null latest-period fields. + let row_no_ttm = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 5, 1, 20, 15, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: utc_micros(2024, 5, 1, 20, 15, 0, 0), + fields: FundamentalsFields { + revenue: Some(100.0), + net_income: None, + operating_cash_flow: Some(15.0), + total_assets: None, + total_equity: Some(220.0), + shares_outstanding: None, + }, + }, + None, + ); + + // 2) Row with TTM where ttm_has_estimated_lag = Some(false) and all flows present. + let row_ttm_false = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 8, 1, 20, 15, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 6, 30), + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: utc_micros(2024, 8, 1, 20, 15, 0, 0), + fields: FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(18.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), + }, + }, + Some(FundamentalsTtm { + ending_period_end: day(2024, 6, 30), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(370.0), + net_income: Some(37.0), + operating_cash_flow: Some(55.0), + }, + has_estimated_lag: false, + }), + ); + + // 3) Row with TTM where ttm_has_estimated_lag = Some(true), FY latest period, and partial null TTM flow. + let row_ttm_true = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 11, 15, 21, 5, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_STATUTORY_LAG), + true, + FundamentalsPitLatestPeriod { + period_end: day(2024, 9, 30), + fiscal_period: Cow::Borrowed("FY"), + currency: "CAD".to_string(), + period_known_at_micros: utc_micros(2024, 11, 15, 21, 5, 0, 0), + fields: FundamentalsFields { + revenue: Some(450.0), + net_income: Some(45.0), + operating_cash_flow: None, + total_assets: Some(600.0), + total_equity: Some(250.0), + shares_outstanding: Some(105.0), + }, + }, + Some(FundamentalsTtm { + ending_period_end: day(2024, 9, 30), + currency: "CAD".to_string(), + flows: TtmFlowFields { + revenue: Some(450.0), + net_income: None, + operating_cash_flow: Some(60.0), + }, + has_estimated_lag: true, + }), + ); + + let rows = vec![row_no_ttm, row_ttm_false, row_ttm_true]; + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write schema test dataset"); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 3)])); + + let path = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let reader = SerializedFileReader::new(File::open(&path).expect("open parquet")) + .expect("open parquet reader"); + let meta = reader.metadata(); + let expected_schema = fundamentals_pit_parquet_schema().expect("schema"); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + assert_eq!(expected_schema.name(), "fundamentals_pit"); + + let fields = meta.file_metadata().schema().get_fields(); + assert_eq!(fields.len(), 20); + + let expected_cols: [( + &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_period_end", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "ttm_currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "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_has_estimated_lag", + PhysicalType::BOOLEAN, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected_cols.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" + ); + } + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} must use ZSTD compression", + col.column_path() + ); + } + } + + let decoded = read_parquet_rows(&path); + assert_eq!(decoded.len(), 3); + + // Row 0: no TTM -> all 6 ttm_* columns are None. + assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!decoded[0].has_estimated_lag); + assert_eq!(decoded[0].revenue, Some(100.0)); + assert_eq!(decoded[0].net_income, None); + assert_eq!(decoded[0].operating_cash_flow, Some(15.0)); + assert_eq!(decoded[0].total_assets, None); + assert_eq!(decoded[0].total_equity, Some(220.0)); + assert_eq!(decoded[0].shares_outstanding, None); + assert_eq!(decoded[0].ttm_period_end, None); + assert_eq!(decoded[0].ttm_currency, None); + assert_eq!(decoded[0].ttm_revenue, None); + assert_eq!(decoded[0].ttm_net_income, None); + assert_eq!(decoded[0].ttm_operating_cash_flow, None); + assert_eq!(decoded[0].ttm_has_estimated_lag, None); + + // Row 1: ttm_has_estimated_lag = Some(false) + assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); + assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); + assert_eq!(decoded[1].ttm_revenue, Some(370.0)); + assert_eq!(decoded[1].ttm_net_income, Some(37.0)); + assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0)); + assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false)); + + // Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source. + assert_eq!(decoded[2].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(decoded[2].has_estimated_lag); + assert_eq!(decoded[2].fiscal_period, "FY"); + assert_eq!(decoded[2].currency, "CAD"); + assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); + assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); + assert_eq!(decoded[2].ttm_revenue, Some(450.0)); + assert_eq!(decoded[2].ttm_net_income, None); + assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0)); + assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true)); + + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() { + let listing_id = 42_i32; + let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::UsTsx)]); + + let p_2023_q3 = day(2023, 9, 30); + let p_2023_q4 = day(2023, 12, 31); + let p_2024_q1 = day(2024, 3, 31); + let p_2024_q2 = day(2024, 6, 30); + + let initial_filings = vec![ + filing(listing_id, "2023-11-01T16:15:00 EDT", "10-Q"), + filing(listing_id, "2024-02-01T16:15:00 EST", "10-Q"), + filing(listing_id, "2024-05-01T16:15:00 EDT", "10-Q"), + filing(listing_id, "2024-08-01T16:15:00 EDT", "10-Q"), + ]; + let amendment_filing = filing(listing_id, "2024-09-15T17:00:00 EDT", "10-Q/A"); + + let initial_obs = vec![ + obs( + listing_id, + p_2023_q3, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 1)), + FundamentalsFields { + revenue: Some(70.0), + net_income: Some(7.0), + operating_cash_flow: Some(10.0), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2023_q4, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 1)), + FundamentalsFields { + revenue: Some(80.0), + net_income: Some(8.0), + operating_cash_flow: Some(12.0), + total_assets: Some(520.0), + total_equity: Some(210.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(15.0), + total_assets: Some(540.0), + total_equity: Some(220.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2024_q2, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 1)), + FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(18.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), + }, + ), + ]; + + // Late Q1 amendment filed on 2024-09-15 (after Q2's 2024-08-01 filing). + // Restates revenue 100 -> 110 and net_income 10 -> 11, while omitting operating_cash_flow. + let q1_amendment = obs( + listing_id, + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 15)), + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: None, + total_assets: None, + total_equity: Some(225.0), + shares_outstanding: None, + }, + ); + + let mut full_obs = initial_obs.clone(); + full_obs.push(q1_amendment); + let mut full_filings = initial_filings.clone(); + full_filings.push(amendment_filing); + + let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); + let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).expect("full snapshots"); + assert_eq!(full_snaps.len(), 5); + + let baseline_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); + let baseline_snaps = + build_fundamentals_snapshots(&baseline_build.rows, 4).expect("baseline snapshots"); + assert_eq!(baseline_snaps.len(), 4); + + let full_rows_from_ref: Vec = + full_snaps.iter().map(FundamentalsPitParquetRow::from).collect(); + let full_rows_from_owned: Vec = full_snaps + .into_iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + assert_eq!(full_rows_from_ref, full_rows_from_owned); + + let baseline_rows: Vec = baseline_snaps + .iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + + let tmp_full = TempDirGuard::new("restatement-full"); + let tmp_base = TempDirGuard::new("restatement-baseline"); + + let full_stats = write_fundamentals_pit_dataset( + tmp_full.path(), + &full_rows_from_ref, + FundamentalsPitWriteOptions::default(), + ) + .expect("write full dataset"); + assert_eq!(full_stats.rows_written, 5); + assert_eq!(full_stats.files_written, 2); + assert_eq!(full_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 4)])); + + let base_stats = write_fundamentals_pit_dataset( + tmp_base.path(), + &baseline_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write baseline dataset"); + assert_eq!(base_stats.rows_written, 4); + assert_eq!(base_stats.files_written, 2); + assert_eq!(base_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 3)])); + + let mut full_decoded = read_parquet_rows( + &tmp_full + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + full_decoded.extend(read_parquet_rows( + &tmp_full + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(full_decoded.len(), 5); + + 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(), 4); + + let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0, 0); + let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0, 0); + + // Every earlier row (before the amendment) must match the unamended baseline identically. + assert_eq!(&full_decoded[..4], &base_decoded[..]); + + // Every row at or after Q2 filing must keep Q2 as the latest visible period with unchanged fields. + let post_q2_rows: Vec<&DecodedFundamentalsPitRow> = full_decoded + .iter() + .filter(|r| r.effective_known_at >= ts_q2) + .collect(); + assert_eq!(post_q2_rows.len(), 2); + assert_eq!(post_q2_rows[0].effective_known_at, ts_q2); + assert_eq!(post_q2_rows[1].effective_known_at, ts_amend); + + for row in &post_q2_rows { + assert_eq!(row.listing_id, listing_id); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!row.has_estimated_lag); + assert_eq!(row.period_end, p_2024_q2); + assert_eq!(row.period_known_at, ts_q2); + assert_eq!(row.fiscal_period, "Q"); + assert_eq!(row.currency, "USD"); + assert_eq!(row.revenue, Some(120.0)); + assert_eq!(row.net_income, Some(12.0)); + assert_eq!(row.operating_cash_flow, Some(18.0)); + assert_eq!(row.total_assets, Some(560.0)); + assert_eq!(row.total_equity, Some(230.0)); + assert_eq!(row.shares_outstanding, Some(100.0)); + assert_eq!(row.ttm_period_end, Some(p_2024_q2)); + assert_eq!(row.ttm_currency.as_deref(), Some("USD")); + assert_eq!(row.ttm_has_estimated_lag, Some(false)); + } + + // At Q2 filing (before amendment): TTM uses original Q1 (revenue=100, net_income=10, ocf=15). + assert_eq!(post_q2_rows[0].ttm_revenue, Some(370.0)); + assert_eq!(post_q2_rows[0].ttm_net_income, Some(37.0)); + assert_eq!(post_q2_rows[0].ttm_operating_cash_flow, Some(55.0)); + + // At Q1 amendment: TTM revenue & net_income update (+10, +1); TTM OCF preserves prior Q1's 15.0. + assert_eq!(post_q2_rows[1].ttm_revenue, Some(380.0)); + assert_eq!(post_q2_rows[1].ttm_net_income, Some(38.0)); + assert_eq!(post_q2_rows[1].ttm_operating_cash_flow, Some(55.0)); + + assert_no_transient_files(&tmp_full.path().join("fundamentals_pit")); + assert_no_transient_files(&tmp_base.path().join("fundamentals_pit")); +} + +#[test] +fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() { + let tmp = TempDirGuard::new("partitioning"); + + // Globally ordered by (listing_id, effective_known_at), with interleaved UTC years across + // multiple listings and timestamps 1 microsecond apart across midnight UTC. + let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); + let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); + assert_eq!(partition_year_utc(ts_2023_end), 2023); + assert_eq!(partition_year_utc(ts_2024_start), 2024); + + let rows = vec![ + make_row(1, utc_micros(2023, 5, 1, 14, 0, 0, 0), day(2023, 3, 31), Some(10.0), None), + make_row(1, ts_2023_end, day(2023, 9, 30), Some(11.0), None), + make_row(1, ts_2024_start, day(2023, 12, 31), Some(12.0), None), + make_row(2, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(20.0), None), + make_row(2, utc_micros(2024, 2, 1, 14, 0, 0, 0), day(2023, 12, 31), Some(21.0), None), + make_row(3, utc_micros(2023, 11, 1, 14, 0, 0, 0), day(2023, 9, 30), Some(30.0), None), + make_row(3, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(31.0), None), + ]; + + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write partitioned dataset"); + + assert_eq!(stats.rows_written, 7); + assert_eq!(stats.files_written, 2); + // 2023: 4 rows -> 2 row groups; 2024: 3 rows -> 2 row groups + assert_eq!(stats.row_groups_written, 4); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 4), (2024, 3)])); + + let path_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + assert!(path_2023.is_file()); + assert!(path_2024.is_file()); + + let decoded_2023 = read_parquet_rows(&path_2023); + let decoded_2024 = read_parquet_rows(&path_2024); + + assert_eq!(decoded_2023.len(), 4); + assert_eq!(decoded_2024.len(), 3); + + // Verify exact membership and strict sort order by (listing_id, effective_known_at). + for (year, decoded) in [(2023, &decoded_2023), (2024, &decoded_2024)] { + for r in decoded { + assert_eq!(partition_year_utc(r.effective_known_at), year); + } + for pair in decoded.windows(2) { + assert!( + (pair[0].listing_id, pair[0].effective_known_at) + < (pair[1].listing_id, pair[1].effective_known_at), + "year {year} rows must be strictly increasing by (listing_id, effective_known_at)" + ); + } + } + + assert_eq!(decoded_2023[1].effective_known_at, ts_2023_end); + assert_eq!(decoded_2024[0].effective_known_at, ts_2024_start); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_preserve_existing_partitions() { + let tmp = TempDirGuard::new("errors"); + + // Seed an existing 2024 partition and snapshot its exact bytes. + let seed = vec![make_row( + 1, + utc_micros(2024, 3, 1, 15, 0, 0, 0), + day(2023, 12, 31), + Some(50.0), + None, + )]; + write_fundamentals_pit_dataset( + tmp.path(), + &seed, + FundamentalsPitWriteOptions::default(), + ) + .expect("seed existing partition"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let before_bytes = fs::read(&part_2024).expect("read seed bytes"); + + let rg1 = FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + + // 1. Duplicate (listing_id, effective_known_at) with different payload after a valid row. + let ts_a = utc_micros(2024, 5, 1, 20, 0, 0, 0); + let dup_rows = vec![ + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + make_row(1, ts_a, day(2024, 3, 31), Some(999.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &dup_rows, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::DuplicateRow { + row_index: 1, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_a + ), + "expected DuplicateRow, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 2. Unsorted (descending effective_known_at for same listing) after a valid row. + let ts_b = utc_micros(2024, 8, 1, 20, 0, 0, 0); + let unsorted_ts = vec![ + make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_ts, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 1, + prev_effective_known_at_micros, + listing_id: 1, + effective_known_at_micros, + } if prev_effective_known_at_micros == ts_b && effective_known_at_micros == ts_a + ), + "expected UnsortedInput, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 3. Unsorted (descending listing_id) after a valid row. + let unsorted_lid = vec![ + make_row(2, ts_a, day(2024, 3, 31), Some(100.0), None), + make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_lid, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 2, + listing_id: 1, + .. + } + ), + "expected UnsortedInput for descending listing_id, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 4. Empty periods snapshot (at row_index 0 and at row_index 1 after a flushed row group). + let empty_snap = FundamentalsSnapshot { + key: 1_i32, + effective_known_at_utc_micros: ts_b, + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + periods: Vec::new(), + ttm: None, + }; + let empty_row = FundamentalsPitParquetRow::from(&empty_snap); + assert!(empty_row.latest_period().is_none()); + + let tmp_fresh = TempDirGuard::new("empty-periods-first"); + let err_first = write_fundamentals_pit_dataset(tmp_fresh.path(), &[empty_row.clone()], rg1) + .unwrap_err(); + assert!( + matches!( + err_first, + ParquetFundamentalsError::EmptyPeriods { + row_index: 0, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_b + ), + "expected EmptyPeriods at row 0, got {err_first:?}" + ); + assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); + + let mixed = vec![ + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + empty_row, + ]; + let err_second = write_fundamentals_pit_dataset(tmp.path(), &mixed, rg1).unwrap_err(); + assert!( + matches!( + err_second, + ParquetFundamentalsError::EmptyPeriods { + row_index: 1, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_b + ), + "expected EmptyPeriods at row 1, got {err_second:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 5. Empty input does not create directory or touch existing partitions. + let tmp_empty = TempDirGuard::new("empty-input"); + let empty_stats = write_fundamentals_pit_dataset( + tmp_empty.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .expect("empty input succeeds"); + assert_eq!(empty_stats, FundamentalsPitWriteStats::default()); + assert!(!tmp_empty.path().join("fundamentals_pit").exists()); +} + +#[test] +fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { + let tmp = TempDirGuard::new("rollback"); + + // Seed an existing 2023 partition. + let seed = vec![make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(50.0), + None, + )]; + write_fundamentals_pit_dataset( + tmp.path(), + &seed, + FundamentalsPitWriteOptions::default(), + ) + .expect("seed 2023"); + + 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 part_2025 = tmp.path().join("fundamentals_pit/year=2025/part.parquet"); + let before_2023 = fs::read(&part_2023).expect("read seed 2023"); + + // Occupy year=2025/part.parquet with a directory so rename fails after 2023 (replaced) + // and 2024 (newly created) have been renamed into place. + fs::create_dir_all(&part_2025).expect("create blocking directory at year=2025/part.parquet"); + + let rows = vec![ + make_row(1, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(75.0), None), + make_row(1, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(100.0), None), + make_row(1, utc_micros(2025, 5, 1, 14, 0, 0, 0), day(2025, 3, 31), Some(125.0), None), + ]; + + let err = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetFundamentalsError::Io { ref path, .. } if path == &part_2025), + "expected Io error at year=2025/part.parquet, got {err:?}" + ); + + // 2023 must be restored byte for byte; 2024 must be removed; no transient files remain. + assert_eq!(fs::read(&part_2023).expect("read restored 2023"), before_2023); + assert!( + !part_2024.exists(), + "newly published 2024 partition must be removed on rollback" + ); + assert!(part_2025.is_dir()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index fd9b89c2..00d6f1a4 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -363,6 +363,25 @@ fn next_column<'a>( } } +pub(crate) fn write_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], + def_levels: Option<&[i16]>, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, def_levels, None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + pub(crate) fn write_i32_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, values: &[i32],