diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index b2df8b36..848ed021 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, and the `M1.2m` streaming Zstd Parquet writer for `adj_factors`. +Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, and the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`. ## Scope & Sign Conventions @@ -383,6 +383,56 @@ Rules: - Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000` - Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x` +## `corporate_actions` Parquet Writer (`M1.2n`) + +`write_corporate_actions_dataset` (`src/parquet_corporate_actions.rs`) streams non-decreasing `(listing_id, ex_date, kind)` `CorporateActionsParquetRow` records (with `CorporateActionsParquetRow::from_corporate_action_row(&CorporateActionRow, known_at_micros)` construction from `build_corporate_actions`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 11-column contract schema (`corporate_actions_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `ex_date` (`INT32`, `REQUIRED`, `DATE`) + - `declared_date` (`INT32`, `OPTIONAL`, `DATE`) + - `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"split"` | `"dividend"` | `"otc_delist_transfer"` | `"delisting"`) + - `ratio` (`DOUBLE`, `OPTIONAL`) + - `cash_amount` (`DOUBLE`, `OPTIONAL`) + - `currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`, dictionary-encoded) + - `successor_listing_id` (`INT32`, `OPTIONAL`) + - `terminal_return` (`DOUBLE`, `OPTIONAL`) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded: `"declared_date"` | `"ex_date_fallback"` | `"delist_date"`) +2. **Layout, compression & streaming:** + - Writes `/corporate_actions/part.parquet` (unpartitioned). + - Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating `/corporate_actions` and without modifying or removing any pre-existing `part.parquet`. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `CorporateActionsWriteOptions::zstd_level`). + - Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `CorporateActionsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with interned `kind`, `currency`, and `known_at_source` streamed in 4,096-row batches and reused buffers across row groups), flushing and clearing on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, ordering, concurrency & atomic publish rules:** + - Caller supplies `known_at_micros` (date→timestamp derivation policy belongs to the later Mongo-streaming wiring task). + - Input must be non-decreasing on `(listing_id, ex_date, kind)` using `CorporateActionKind`'s `Ord` (`Split < Dividend < OtcDelistTransfer < Delisting`), matching `build_corporate_actions` output without re-sorting; multiple rows may share the same key (e.g. regular + special dividend on the same ex-date). + - Every streamed row is validated before publication: `ex_date` and optional `declared_date` years must fall in `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR` (`1900..=2200`); `split` requires `ratio` finite `> 0.0`; `dividend` requires `cash_amount` finite `> 0.0` and `currency` non-empty after trimming; `otc_delist_transfer` requires `successor_listing_id != listing_id`; `delisting` requires `terminal_return` finite in `[-1.0, 0.0]`; all fields belonging to other kinds must be `None`; and `known_at_source` must match the kind (`delist_date` only for delisting kinds, `declared_date` requires `declared_date.is_some()`). + - Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `/corporate_actions` are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (`30 s` default timeout); writes go to an exclusively created per-run staging file (`part.parquet..tmp`), flush, and `File::sync_all()`; 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, the writer is dropped, any pre-existing `part.parquet` remains byte-identical, only staging/backup files owned by the current run are cleaned up, and backup cleanup failures are surfaced via `RollbackFailed`. +4. **Typed errors (`ParquetCorporateActionsError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_listing_id, prev_ex_date, prev_kind, listing_id, ex_date, kind }` + - `ExDateOutOfRange { listing_id, ex_date, year, min_year, max_year }` + - `DeclaredDateOutOfRange { listing_id, ex_date, declared_date, year, min_year, max_year }` + - `InvalidRatio { listing_id, ex_date, value }` + - `InvalidCashAmount { listing_id, ex_date, value }` + - `InvalidCurrency { listing_id, ex_date }` + - `InvalidSuccessorListingId { listing_id, ex_date, successor_listing_id }` + - `InvalidTerminalReturn { listing_id, ex_date, value }` + - `ForbiddenFieldForKind { listing_id, ex_date, kind, field }` + - `InconsistentKnownAtSource { listing_id, ex_date, kind, known_at_source, declared_date }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions` + - Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72` (weekday dates `1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes) + - Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000` + - Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x` + ## Local Benchmarks ### `bench-split` @@ -567,13 +617,27 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Output: `files=1`, `row_groups=1`, `bytes=2595560`, `read_back_rows=1000000` - Perf: `elapsed=106.01 ms`, `throughput=9432939 rows/s`, `write=23.35 MB/s`, `size=2.60 bytes/row`, `compression=19.65x` +### `bench-parquet-corporate-actions` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `CorporateActionsParquetRow` rows across `20,000` listings on weekday dates (`1990..=2025`, ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes), writing `corporate_actions/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying the Parquet footer row count, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-corporate-actions` + +- Input: `rows=1000000`, `listings=20000`, `raw_row_bytes=72` +- Output: `files=1`, `row_groups=1`, `bytes=4041339`, `read_back_rows=1000000` +- Perf: `elapsed=153.96 ms`, `throughput=6495345 rows/s`, `write=25.03 MB/s`, `size=4.04 bytes/row`, `compression=17.82x` + ## Deferred Follow-Ups (`M1.3+` / `M2`) This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add: - `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata - `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends -- Zstd Parquet writer for the remaining curated table (`corporate_actions`) and `qmPrices` OHLC cross-check +- `qmPrices` OHLC cross-check - Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`) - PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32` - `rayon` parallel sharding across symbol/date partitions diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 7f41fd88..787a75d3 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -14,8 +14,8 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; use crate::corporate_actions::{ - build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent, - DividendActionEvent, SplitActionEvent, + build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats, + DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, }; use crate::events::{ build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json, @@ -29,6 +29,10 @@ use crate::parquet_adj::{ use crate::parquet_bars::{ write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError, }; +use crate::parquet_corporate_actions::{ + write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions, + ParquetCorporateActionsError, +}; use crate::parquet_events::{ write_events_dataset, EventsParquetRow, EventsWriteOptions, ParquetEventsError, }; @@ -64,6 +68,12 @@ pub const DEFAULT_PARQUET_FX_BENCH_ROWS: usize = 1_000_000; pub const PARQUET_FX_RAW_ROW_BYTES: usize = 70; pub const DEFAULT_PARQUET_ADJ_BENCH_ROWS: usize = 1_000_000; pub const PARQUET_ADJ_RAW_ROW_BYTES: usize = 51; +pub const DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS: usize = 1_000_000; +/// Uncompressed logical row size estimate for `corporate_actions/part.parquet` (11 columns): +/// `listing_id` (4) + `ex_date` (4) + `declared_date` (4) + `kind` (~8) + `ratio` (8) +/// + `cash_amount` (8) + `currency` (3) + `successor_listing_id` (4) + `terminal_return` (8) +/// + `known_at` (8) + `known_at_source` (~13) = 72 bytes. +pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; @@ -73,6 +83,7 @@ const PARQUET_SHORTS_BENCH_BASE_LISTINGS: usize = 12_500; const PARQUET_EVENTS_BENCH_BASE_LISTINGS: usize = 5_000; const PARQUET_FX_BENCH_BASE_PAIRS: usize = 80; const PARQUET_ADJ_BENCH_BASE_LISTINGS: usize = 20_000; +const PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS: usize = 20_000; const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; @@ -87,6 +98,7 @@ const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; const PARQUET_EVENTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_E7E4; const PARQUET_FX_BENCH_SEED: u64 = 0x570C_4B07_9A49_F81D; const PARQUET_ADJ_BENCH_SEED: u64 = 0x570C_4B07_9A49_AD7F; +const PARQUET_CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_9A49_C049; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; /// Deterministic SplitMix64 generator (zero external dependencies). @@ -1719,6 +1731,14 @@ impl BenchTempDir { Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-adj") .map_err(|(path, source)| ParquetAdjError::Io { path, source }) } + + fn new_corporate_actions() -> Result { + Self::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-pq-corporate-actions", + ) + .map_err(|(path, source)| ParquetCorporateActionsError::Io { path, source }) + } } impl Drop for BenchTempDir { @@ -3239,6 +3259,336 @@ pub fn run_parquet_adj_benchmark( Ok(report) } +/// Summary metrics produced by [`run_parquet_corporate_actions_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParquetCorporateActionsBenchReport { + pub rows: usize, + pub read_back_rows: usize, + pub listing_count: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub raw_row_bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub bytes_per_row: f64, + pub compression_ratio: f64, +} + +struct ParquetCorporateActionsBenchIter { + weekdays: Vec, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_day_idx: usize, + cur_listing_rows: usize, + rng: SplitMix64, +} + +impl ParquetCorporateActionsBenchIter { + fn new(rows: usize, weekdays: Vec) -> Self { + let min_listings = if rows == 0 { + PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS + } else { + rows.div_ceil(weekdays.len()) + .max(PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS) + }; + let active_listings = rows.min(min_listings); + let base_per_listing = if active_listings == 0 { + 0 + } else { + rows / active_listings + }; + let rem_listings = if active_listings == 0 { + 0 + } else { + rows % active_listings + }; + let mut iter = Self { + weekdays, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_day_idx: 0, + cur_listing_rows: 0, + rng: SplitMix64::new(PARQUET_CORPORATE_ACTIONS_BENCH_SEED), + }; + if active_listings > 0 { + iter.setup_listing(0); + } + iter + } + + fn setup_listing(&mut self, listing_idx: usize) { + self.cur_listing = listing_idx; + self.cur_day_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + } +} + +impl Iterator for ParquetCorporateActionsBenchIter { + type Item = CorporateActionsParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_day_idx >= self.cur_listing_rows { + let next_listing = self.cur_listing + 1; + if next_listing >= self.listing_count { + self.cur_listing = next_listing; + return None; + } + self.setup_listing(next_listing); + } + + let listing_id = (self.cur_listing as i32) + 1; + let w = self.weekdays.len(); + let n = self.cur_listing_rows; + let date_pos = if n == 1 { + (self.cur_listing.wrapping_mul(131)) % w + } else { + (self.cur_day_idx * w) / n + }; + let ex_date = self.weekdays[date_pos]; + self.cur_day_idx += 1; + + let r1 = self.rng.next_u64(); + let kind_roll = r1 % 100; + + // M1.2c mix: ~4% splits, ~92% USD/CAD dividends, ~4% delisting outcomes + // (split between otc_delist_transfer and delisting). + if kind_roll < 4 { + let ratio = SAMPLE_RATIOS[((r1 >> 16) as usize) % SAMPLE_RATIOS.len()]; + let decl_roll = (r1 >> 40) % 100; + let (declared_date, known_at_day, known_at_source) = if decl_roll < 80 { + let d = ex_date - (14 + ((r1 >> 48) % 8) as i32); + (Some(d), d, KnownAtSource::DeclaredDate) + } else if decl_roll < 98 { + (None, ex_date, KnownAtSource::ExDateFallback) + } else { + (Some(ex_date + 3), ex_date, KnownAtSource::ExDateFallback) + }; + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Split, + ratio: Some(ratio), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::from(known_at_day) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source, + }) + } else if kind_roll < 96 { + let currency = if ((r1 >> 8) & 3) == 0 { "CAD" } else { "USD" }; + let cash = (((r1 >> 24) % 250) + 1) as f64 * 0.01; + let decl_roll = (r1 >> 40) % 100; + let (declared_date, known_at_day, known_at_source) = if decl_roll < 80 { + let d = ex_date - (14 + ((r1 >> 48) % 8) as i32); + (Some(d), d, KnownAtSource::DeclaredDate) + } else if decl_roll < 98 { + (None, ex_date, KnownAtSource::ExDateFallback) + } else { + (Some(ex_date + 3), ex_date, KnownAtSource::ExDateFallback) + }; + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(cash), + currency: Some(Cow::Borrowed(currency)), + successor_listing_id: None, + terminal_return: None, + known_at_micros: i64::from(known_at_day) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source, + }) + } else if kind_roll < 98 { + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::OtcDelistTransfer, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: Some(listing_id + 1_000_000), + terminal_return: None, + known_at_micros: i64::from(ex_date) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source: KnownAtSource::DelistDate, + }) + } else { + let terminal_return = match (r1 >> 24) % 4 { + 0 => -1.0, + 1 => -0.5, + 2 => -0.3, + _ => 0.0, + }; + Some(CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::Delisting, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: Some(terminal_return), + known_at_micros: i64::from(ex_date) * 86_400_000_000 + 13 * 3_600_000_000, + known_at_source: KnownAtSource::DelistDate, + }) + } + } +} + +fn verify_parquet_corporate_actions_row_count( + out_dir: &Path, + expected_rows: usize, +) -> Result { + if expected_rows == 0 { + return Ok(0); + } + let path = out_dir.join("corporate_actions/part.parquet"); + let file = File::open(&path).map_err(|source| ParquetCorporateActionsError::Io { + path: path.clone(), + source, + })?; + let reader = + SerializedFileReader::new(file).map_err(|source| ParquetCorporateActionsError::Parquet { + path: path.clone(), + source, + })?; + let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetCorporateActionsError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + + if read_back_rows != expected_rows { + return Err(ParquetCorporateActionsError::Parquet { + path, + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_corporate_actions_benchmark_tracked( + rows: usize, +) -> Result<(ParquetCorporateActionsBenchReport, PathBuf), ParquetCorporateActionsError> { + let temp = BenchTempDir::new_corporate_actions()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_corporate_actions_dataset( + &temp.path, + std::iter::empty::(), + CorporateActionsWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, 0)?; + let report = ParquetCorporateActionsBenchReport { + rows: 0, + read_back_rows, + listing_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let weekdays = collect_bench_weekdays_1990_2025(); + let iter = ParquetCorporateActionsBenchIter::new(rows, weekdays); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_corporate_actions_dataset( + &temp.path, + iter, + CorporateActionsWriteOptions::default(), + )?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetCorporateActionsError::Parquet { + path: temp.path.join("corporate_actions/part.parquet"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = verify_parquet_corporate_actions_row_count(&temp.path, rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let raw_bytes = (rows as f64) * (PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES as f64); + let compression_ratio = if stats.bytes_written > 0 { + raw_bytes / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetCorporateActionsBenchReport { + rows, + read_back_rows, + listing_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `corporate_actions` writer benchmark for `rows` sorted +/// split/dividend/delisting rows spanning `1990..=2025` across up to `20,000` listings, reads back +/// the Parquet footer row count, and deletes its temporary output directory. +pub fn run_parquet_corporate_actions_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_parquet_corporate_actions_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -3961,4 +4311,75 @@ mod tests { "error must report expected (255) and actual (250) row counts, got: {msg}" ); } + + #[test] + fn parquet_corporate_actions_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_corporate_actions_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_parquet_corporate_actions_benchmark_tracked(25_000).unwrap(); + + assert!( + !dir_a.exists(), + "temp dir {} should be removed", + dir_a.display() + ); + assert!( + !dir_b.exists(), + "temp dir {} should be removed", + dir_b.display() + ); + assert_eq!(a.rows, 25_000); + assert_eq!(a.read_back_rows, 25_000); + assert_eq!(a.listing_count, PARQUET_CORPORATE_ACTIONS_BENCH_BASE_LISTINGS); + assert_eq!(a.files_written, 1); + assert_eq!(a.files_written, b.files_written); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.raw_row_bytes, PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_corporate_actions_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_corporate_actions_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listing_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.raw_row_bytes, PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_corporate_actions_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_corporate_actions().unwrap(); + let weekdays = collect_bench_weekdays_1990_2025(); + let iter = ParquetCorporateActionsBenchIter::new(250, weekdays); + write_corporate_actions_dataset(&temp.path, iter, CorporateActionsWriteOptions::default()) + .unwrap(); + + let matched = verify_parquet_corporate_actions_row_count(&temp.path, 250).unwrap(); + assert_eq!(matched, 250); + + let err = verify_parquet_corporate_actions_row_count(&temp.path, 255).unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetCorporateActionsError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 51493389..6b27a228 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -7,9 +7,9 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, - DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, - DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, - DEFAULT_SHORTS_BENCH_ROWS, + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, + DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, + DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -30,6 +30,7 @@ pub enum CliAction { BenchParquetEvents(usize), BenchParquetFx(usize), BenchParquetAdj(usize), + BenchParquetCorporateActions(usize), } /// Formats full help text including binary name and version. @@ -52,7 +53,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\ {name} bench-parquet-events [rows] Run fixed-seed events Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_EVENTS_BENCH_ROWS})\n\ {name} bench-parquet-fx [rows] Run fixed-seed fx_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_FX_BENCH_ROWS})\n\ - {name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})" + {name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\ + {name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})" ) } @@ -74,7 +76,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-parquet-shorts [rows]\n\ {name} bench-parquet-events [rows]\n\ {name} bench-parquet-fx [rows]\n\ - {name} bench-parquet-adj [rows]" + {name} bench-parquet-adj [rows]\n\ + {name} bench-parquet-corporate-actions [rows]" ) } @@ -215,6 +218,18 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-parquet-adj", _, ..] => { Err("too many arguments for bench-parquet-adj".to_string()) } + ["bench-parquet-corporate-actions"] => Ok(CliAction::BenchParquetCorporateActions( + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, + )), + ["bench-parquet-corporate-actions", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetCorporateActions(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-corporate-actions", _, ..] => { + Err("too many arguments for bench-parquet-corporate-actions".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -466,6 +481,24 @@ mod tests { assert!(parse_args(&to_args(&["bench-parquet-adj", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_parquet_corporate_actions_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-corporate-actions"])), + Ok(CliAction::BenchParquetCorporateActions( + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-corporate-actions", "25000"])), + Ok(CliAction::BenchParquetCorporateActions(25_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-corporate-actions", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -482,6 +515,7 @@ mod tests { assert!(full.contains("bench-parquet-events")); assert!(full.contains("bench-parquet-fx")); assert!(full.contains("bench-parquet-adj")); + assert!(full.contains("bench-parquet-corporate-actions")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -497,5 +531,6 @@ mod tests { assert!(short.contains("bench-parquet-events")); assert!(short.contains("bench-parquet-fx")); assert!(short.contains("bench-parquet-adj")); + assert!(short.contains("bench-parquet-corporate-actions")); } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 3b872d50..963fd60d 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -9,6 +9,7 @@ pub mod events; pub mod fx; pub mod parquet_adj; pub mod parquet_bars; +pub mod parquet_corporate_actions; pub mod parquet_events; pub mod parquet_fx; mod parquet_publish; @@ -51,6 +52,10 @@ pub use parquet_bars::{ Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, }; +pub use parquet_corporate_actions::{ + corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow, + CorporateActionsWriteOptions, CorporateActionsWriteStats, ParquetCorporateActionsError, +}; pub use parquet_events::{ events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 2085013a..4c075bbe 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -6,8 +6,9 @@ use std::process::ExitCode; use curate_etl::bench::{ run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark, run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, - run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, - run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, + run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, + run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, + run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -446,6 +447,36 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchParquetCorporateActions(rows)) => { + let report = match run_parquet_corporate_actions_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet corporate_actions benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-corporate-actions"); + println!( + " input: rows={} listings={} raw_row_bytes={}", + report.rows, report.listing_count, report.raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); diff --git a/tools/curate-etl/src/parquet_corporate_actions.rs b/tools/curate-etl/src/parquet_corporate_actions.rs new file mode 100644 index 00000000..c1905b03 --- /dev/null +++ b/tools/curate-etl/src/parquet_corporate_actions.rs @@ -0,0 +1,1817 @@ +//! Streaming, atomic Zstd Parquet writer for `corporate_actions`. +//! +//! Writes `/corporate_actions/part.parquet` matching the 11-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `ex_date` (`INT32`, `REQUIRED`, `DATE`) +//! 3. `declared_date` (`INT32`, `OPTIONAL`, `DATE`) +//! 4. `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 5. `ratio` (`DOUBLE`, `OPTIONAL`) +//! 6. `cash_amount` (`DOUBLE`, `OPTIONAL`) +//! 7. `currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) +//! 8. `successor_listing_id` (`INT32`, `OPTIONAL`) +//! 9. `terminal_return` (`DOUBLE`, `OPTIONAL`) +//! 10. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 11. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::types::{ColumnPath, Type, TypePtr}; + +use crate::corporate_actions::{CorporateActionKind, CorporateActionRow, KnownAtSource}; +use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::{ + create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, + write_i32_col, write_i64_col, write_interned_str_col, write_optional_f64_col, + write_optional_i32_col, write_optional_interned_str_col, DatasetFileLock, PublishIoError, + StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, + STRING_WRITE_BATCH_ROWS, +}; +pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; +use crate::shorts::epoch_days_to_ymd; + +/// Single `corporate_actions` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct CorporateActionsParquetRow { + pub listing_id: i32, + pub ex_date: i32, + pub declared_date: Option, + pub kind: CorporateActionKind, + pub ratio: Option, + pub cash_amount: Option, + pub currency: Option>, + pub successor_listing_id: Option, + pub terminal_return: Option, + pub known_at_micros: i64, + pub known_at_source: KnownAtSource, +} + +impl CorporateActionsParquetRow { + /// Builds a [`CorporateActionsParquetRow`] from a curated [`CorporateActionRow`] and a + /// caller-supplied UTC microsecond `known_at` timestamp. + #[inline] + pub fn from_corporate_action_row(row: &CorporateActionRow, known_at_micros: i64) -> Self { + Self { + listing_id: row.key, + ex_date: row.ex_date, + declared_date: row.declared_date, + kind: row.kind, + ratio: row.ratio, + cash_amount: row.cash_amount, + currency: row.currency.clone().map(Cow::Owned), + successor_listing_id: row.successor_key, + terminal_return: row.terminal_return, + known_at_micros, + known_at_source: row.known_at_source, + } + } +} + +/// Configuration for [`write_corporate_actions_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CorporateActionsWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for CorporateActionsWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_corporate_actions_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CorporateActionsWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed error returned by [`write_corporate_actions_dataset`]. +#[derive(Debug)] +pub enum ParquetCorporateActionsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_ex_date: i32, + prev_kind: CorporateActionKind, + listing_id: i32, + ex_date: i32, + kind: CorporateActionKind, + }, + ExDateOutOfRange { + listing_id: i32, + ex_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + DeclaredDateOutOfRange { + listing_id: i32, + ex_date: i32, + declared_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + InvalidRatio { + listing_id: i32, + ex_date: i32, + value: Option, + }, + InvalidCashAmount { + listing_id: i32, + ex_date: i32, + value: Option, + }, + InvalidCurrency { + listing_id: i32, + ex_date: i32, + }, + InvalidSuccessorListingId { + listing_id: i32, + ex_date: i32, + successor_listing_id: Option, + }, + InvalidTerminalReturn { + listing_id: i32, + ex_date: i32, + value: Option, + }, + ForbiddenFieldForKind { + listing_id: i32, + ex_date: i32, + kind: CorporateActionKind, + field: &'static str, + }, + InconsistentKnownAtSource { + listing_id: i32, + ex_date: i32, + kind: CorporateActionKind, + known_at_source: KnownAtSource, + declared_date: Option, + }, + 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 ParquetCorporateActionsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidRowGroupRows => { + write!(f, "invalid row_group_rows: must be greater than 0") + } + Self::InvalidZstdLevel { level } => { + write!(f, "invalid Zstd compression level: {level}") + } + Self::UnsortedInput { + prev_listing_id, + prev_ex_date, + prev_kind, + listing_id, + ex_date, + kind, + } => write!( + f, + "unsorted input: ({listing_id}, {ex_date}, {kind}) follows ({prev_listing_id}, {prev_ex_date}, {prev_kind})" + ), + Self::ExDateOutOfRange { + listing_id, + ex_date, + year, + min_year, + max_year, + } => write!( + f, + "ex_date {ex_date} (year {year}) for listing_id {listing_id} is outside supported range [{min_year}, {max_year}]" + ), + Self::DeclaredDateOutOfRange { + listing_id, + ex_date, + declared_date, + year, + min_year, + max_year, + } => write!( + f, + "declared_date {declared_date} (year {year}) for ({listing_id}, {ex_date}) is outside supported range [{min_year}, {max_year}]" + ), + Self::InvalidRatio { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid split ratio {value:?} for ({listing_id}, {ex_date}): must be Some(finite > 0)" + ), + Self::InvalidCashAmount { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid dividend cash_amount {value:?} for ({listing_id}, {ex_date}): must be Some(finite > 0)" + ), + Self::InvalidCurrency { + listing_id, + ex_date, + } => write!( + f, + "invalid dividend currency for ({listing_id}, {ex_date}): must be Some(non-empty)" + ), + Self::InvalidSuccessorListingId { + listing_id, + ex_date, + successor_listing_id, + } => write!( + f, + "invalid successor_listing_id {successor_listing_id:?} for ({listing_id}, {ex_date}): must be Some(id != {listing_id})" + ), + Self::InvalidTerminalReturn { + listing_id, + ex_date, + value, + } => write!( + f, + "invalid terminal_return {value:?} for ({listing_id}, {ex_date}): must be Some(finite in [-1.0, 0.0])" + ), + Self::ForbiddenFieldForKind { + listing_id, + ex_date, + kind, + field, + } => write!( + f, + "field '{field}' must be None for kind '{kind}' on ({listing_id}, {ex_date})" + ), + Self::InconsistentKnownAtSource { + listing_id, + ex_date, + kind, + known_at_source, + declared_date, + } => write!( + f, + "inconsistent known_at_source '{known_at_source}' for kind '{kind}' (declared_date={declared_date:?}) on ({listing_id}, {ex_date})" + ), + 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 ParquetCorporateActionsError { + 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 ParquetCorporateActionsError { + 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 11-column Parquet schema for `corporate_actions` per +/// `design/DATA-CONTRACTS.md` (§3A). +pub fn corporate_actions_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("ex_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("declared_date", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("kind", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ratio", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("cash_amount", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("successor_listing_id", PhysicalType::INT32) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("terminal_return", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("corporate_actions") + .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("kind"), true) + .set_column_dictionary_enabled(ColumnPath::from("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn check_forbidden_none( + row: &CorporateActionsParquetRow, + value: &Option, + field: &'static str, +) -> Result<(), ParquetCorporateActionsError> { + if value.is_some() { + return Err(ParquetCorporateActionsError::ForbiddenFieldForKind { + listing_id: row.listing_id, + ex_date: row.ex_date, + kind: row.kind, + field, + }); + } + Ok(()) +} + +#[inline] +fn validate_row(row: &CorporateActionsParquetRow) -> Result<(), ParquetCorporateActionsError> { + let (ex_year, _, _) = epoch_days_to_ymd(row.ex_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&ex_year) { + return Err(ParquetCorporateActionsError::ExDateOutOfRange { + listing_id: row.listing_id, + ex_date: row.ex_date, + year: ex_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + if let Some(declared_date) = row.declared_date { + let (decl_year, _, _) = epoch_days_to_ymd(declared_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&decl_year) { + return Err(ParquetCorporateActionsError::DeclaredDateOutOfRange { + listing_id: row.listing_id, + ex_date: row.ex_date, + declared_date, + year: decl_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + + match row.kind { + CorporateActionKind::Split => { + match row.ratio { + Some(r) if r.is_finite() && r > 0.0 => {} + other => { + return Err(ParquetCorporateActionsError::InvalidRatio { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other, + }); + } + } + check_forbidden_none(row, &row.cash_amount, "cash_amount")?; + check_forbidden_none(row, &row.currency, "currency")?; + check_forbidden_none(row, &row.successor_listing_id, "successor_listing_id")?; + check_forbidden_none(row, &row.terminal_return, "terminal_return")?; + } + CorporateActionKind::Dividend => { + match row.cash_amount { + Some(c) if c.is_finite() && c > 0.0 => {} + other => { + return Err(ParquetCorporateActionsError::InvalidCashAmount { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other, + }); + } + } + match row.currency.as_deref() { + Some(curr) if !curr.trim().is_empty() => {} + _ => { + return Err(ParquetCorporateActionsError::InvalidCurrency { + listing_id: row.listing_id, + ex_date: row.ex_date, + }); + } + } + check_forbidden_none(row, &row.ratio, "ratio")?; + check_forbidden_none(row, &row.successor_listing_id, "successor_listing_id")?; + check_forbidden_none(row, &row.terminal_return, "terminal_return")?; + } + CorporateActionKind::OtcDelistTransfer => { + match row.successor_listing_id { + Some(succ) if succ != row.listing_id => {} + other => { + return Err(ParquetCorporateActionsError::InvalidSuccessorListingId { + listing_id: row.listing_id, + ex_date: row.ex_date, + successor_listing_id: other, + }); + } + } + check_forbidden_none(row, &row.ratio, "ratio")?; + check_forbidden_none(row, &row.cash_amount, "cash_amount")?; + check_forbidden_none(row, &row.currency, "currency")?; + check_forbidden_none(row, &row.terminal_return, "terminal_return")?; + } + CorporateActionKind::Delisting => { + match row.terminal_return { + Some(r) if r.is_finite() && (-1.0..=0.0).contains(&r) => {} + other => { + return Err(ParquetCorporateActionsError::InvalidTerminalReturn { + listing_id: row.listing_id, + ex_date: row.ex_date, + value: other, + }); + } + } + check_forbidden_none(row, &row.ratio, "ratio")?; + check_forbidden_none(row, &row.cash_amount, "cash_amount")?; + check_forbidden_none(row, &row.currency, "currency")?; + check_forbidden_none(row, &row.successor_listing_id, "successor_listing_id")?; + } + } + + let known_at_ok = match (row.kind, row.known_at_source) { + ( + CorporateActionKind::Split | CorporateActionKind::Dividend, + KnownAtSource::DeclaredDate, + ) => row.declared_date.is_some(), + ( + CorporateActionKind::Split | CorporateActionKind::Dividend, + KnownAtSource::ExDateFallback, + ) => true, + ( + CorporateActionKind::OtcDelistTransfer | CorporateActionKind::Delisting, + KnownAtSource::DelistDate, + ) => true, + _ => false, + }; + if !known_at_ok { + return Err(ParquetCorporateActionsError::InconsistentKnownAtSource { + listing_id: row.listing_id, + ex_date: row.ex_date, + kind: row.kind, + known_at_source: row.known_at_source, + declared_date: row.declared_date, + }); + } + + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + ex_date: Vec, + declared_date_vals: Vec, + declared_date_def_levels: Vec, + kind_ids: Vec, + kind_interner: StringInterner, + ratio_vals: Vec, + ratio_def_levels: Vec, + cash_amount_vals: Vec, + cash_amount_def_levels: Vec, + currency_ids: Vec, + currency_def_levels: Vec, + currency_interner: StringInterner, + successor_listing_id_vals: Vec, + successor_listing_id_def_levels: Vec, + terminal_return_vals: Vec, + terminal_return_def_levels: Vec, + known_at_micros: Vec, + known_at_source_ids: Vec, + known_at_source_interner: StringInterner, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &CorporateActionsParquetRow) { + self.listing_id.push(row.listing_id); + self.ex_date.push(row.ex_date); + + match row.declared_date { + Some(d) => { + self.declared_date_vals.push(d); + self.declared_date_def_levels.push(1); + } + None => self.declared_date_def_levels.push(0), + } + + let kind_id = self.kind_interner.intern(row.kind.as_str()); + self.kind_ids.push(kind_id); + + match row.ratio { + Some(r) => { + self.ratio_vals.push(r); + self.ratio_def_levels.push(1); + } + None => self.ratio_def_levels.push(0), + } + + match row.cash_amount { + Some(c) => { + self.cash_amount_vals.push(c); + self.cash_amount_def_levels.push(1); + } + None => self.cash_amount_def_levels.push(0), + } + + match row.currency.as_deref() { + Some(curr) => { + let id = self.currency_interner.intern(curr); + self.currency_ids.push(id); + self.currency_def_levels.push(1); + } + None => self.currency_def_levels.push(0), + } + + match row.successor_listing_id { + Some(succ) => { + self.successor_listing_id_vals.push(succ); + self.successor_listing_id_def_levels.push(1); + } + None => self.successor_listing_id_def_levels.push(0), + } + + match row.terminal_return { + Some(tr) => { + self.terminal_return_vals.push(tr); + self.terminal_return_def_levels.push(1); + } + None => self.terminal_return_def_levels.push(0), + } + + self.known_at_micros.push(row.known_at_micros); + + let src_id = self + .known_at_source_interner + .intern(row.known_at_source.as_str()); + self.known_at_source_ids.push(src_id); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.ex_date.clear(); + self.declared_date_vals.clear(); + self.declared_date_def_levels.clear(); + self.kind_ids.clear(); + self.kind_interner.clear(); + self.ratio_vals.clear(); + self.ratio_def_levels.clear(); + self.cash_amount_vals.clear(); + self.cash_amount_def_levels.clear(); + self.currency_ids.clear(); + self.currency_def_levels.clear(); + self.currency_interner.clear(); + self.successor_listing_id_vals.clear(); + self.successor_listing_id_def_levels.clear(); + self.terminal_return_vals.clear(); + self.terminal_return_def_levels.clear(); + self.known_at_micros.clear(); + self.known_at_source_ids.clear(); + self.known_at_source_interner.clear(); + } +} + +struct CorporateActionsFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl CorporateActionsFileWriter { + fn from_file( + tmp_path: PathBuf, + final_path: PathBuf, + file: File, + schema: &TypePtr, + props: &WriterPropertiesPtr, + ) -> Result { + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetCorporateActionsError::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<(), ParquetCorporateActionsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetCorporateActionsError::Parquet { + path: self.tmp_path.clone(), + source, + }; + + let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; + + // 1. listing_id (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; + // 2. ex_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.ex_date).map_err(map_pq)?; + // 3. declared_date (INT32, OPTIONAL, DATE) + write_optional_i32_col( + &mut rg_writer, + &self.buf.declared_date_vals, + &self.buf.declared_date_def_levels, + ) + .map_err(map_pq)?; + // 4. kind (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.kind_ids, + &self.buf.kind_interner, + scratch, + ) + .map_err(map_pq)?; + // 5. ratio (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.ratio_vals, + &self.buf.ratio_def_levels, + ) + .map_err(map_pq)?; + // 6. cash_amount (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.cash_amount_vals, + &self.buf.cash_amount_def_levels, + ) + .map_err(map_pq)?; + // 7. currency (BYTE_ARRAY, OPTIONAL, STRING) + write_optional_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_def_levels, + &self.buf.currency_interner, + scratch, + ) + .map_err(map_pq)?; + // 8. successor_listing_id (INT32, OPTIONAL) + write_optional_i32_col( + &mut rg_writer, + &self.buf.successor_listing_id_vals, + &self.buf.successor_listing_id_def_levels, + ) + .map_err(map_pq)?; + // 9. terminal_return (DOUBLE, OPTIONAL) + write_optional_f64_col( + &mut rg_writer, + &self.buf.terminal_return_vals, + &self.buf.terminal_return_def_levels, + ) + .map_err(map_pq)?; + // 10. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + // 11. 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)?; + + 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| ParquetCorporateActionsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer + .flush() + .map_err(|source| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all() + .map_err(|source| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetCorporateActionsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedCorporateActionsFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedCorporateActionsFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams non-decreasing `(listing_id, ex_date, kind)` rows into a single Zstd Parquet file +/// at `/corporate_actions/part.parquet`. +/// +/// Multiple rows may share the same `(listing_id, ex_date, kind)` key (for example, two separate +/// cash dividends on the same ex-date). +/// +/// # Empty Input +/// Empty input returns `Ok(CorporateActionsWriteStats::default())` without creating +/// `/corporate_actions` and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/corporate_actions` directory are serialized +/// via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file +/// is written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists, +/// a live-preserving backup (`part.parquet..bak`) is created via hard link (or exclusive +/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a +/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run +/// is cleaned up (reporting cleanup failures via [`ParquetCorporateActionsError::RollbackFailed`]), +/// and only staging files owned by this run are unlinked. +pub fn write_corporate_actions_dataset( + out_dir: P, + rows: I, + options: CorporateActionsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_corporate_actions_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + |path| fs::remove_file(path), + ) +} + +fn write_corporate_actions_dataset_with_hooks( + out_dir: P, + rows: I, + options: CorporateActionsWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, + mut remove_backup: Rm, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), + Rm: FnMut(&Path) -> io::Result<()>, +{ + if options.row_group_rows == 0 { + return Err(ParquetCorporateActionsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetCorporateActionsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(CorporateActionsWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let dataset_dir = out_dir.join("corporate_actions"); + let schema = corporate_actions_parquet_schema().map_err(|source| { + ParquetCorporateActionsError::Parquet { + path: dataset_dir.clone(), + source, + } + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&dataset_dir).map_err(|source| ParquetCorporateActionsError::Io { + path: dataset_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&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(); + let (tmp_path, tmp_file) = create_exclusive_tmp_file(&dataset_dir, &run_id)?; + // Declared before `file_writer` so Rust's reverse drop order closes the file handle + // before the guard unlinks the staging file on error or panic unwind, while `_file_lock` + // and `_in_process_guard` are still held. + let mut staging_guard = StagingFileGuard::new(tmp_path.clone()); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(CorporateActionsFileWriter::from_file( + tmp_path, + dataset_dir.join("part.parquet"), + tmp_file, + &schema, + &props, + )?); + + let synced = { + let mut prev_key: Option<(i32, i32, CorporateActionKind)> = None; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + // Validate row fields before checking sort order so e.g. an out-of-range + // ex_date is reported as ExDateOutOfRange rather than UnsortedInput. + validate_row(row)?; + let key = (row.listing_id, row.ex_date, row.kind); + if let Some((prev_listing_id, prev_ex_date, prev_kind)) = prev_key { + if key.cmp(&(prev_listing_id, prev_ex_date, prev_kind)) == Ordering::Less { + return Err(ParquetCorporateActionsError::UnsortedInput { + prev_listing_id, + prev_ex_date, + prev_kind, + listing_id: row.listing_id, + ex_date: row.ex_date, + kind: row.kind, + }); + } + } + prev_key = Some(key); + + writer.buf.push(row); + if writer.buf.len() == options.row_group_rows { + writer.flush_row_group(&mut scratch)?; + } + } + + let writer = file_writer.take().expect("writer still present"); + writer.finish_and_sync(&mut scratch)? + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + Some(create_backup_preserving_live(&synced.final_path, &run_id)?) + } + // Directory occupying final_path: leave it in place so the rename below fails cleanly. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + return Err(ParquetCorporateActionsError::Io { + path: synced.final_path, + source, + }); + } + }; + + on_after_backup(&synced.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) { + // `synced.final_path` was never moved during backup creation, so it remains intact; + // remove the backup created for this run. `staging_guard` unlinks our staging file on drop. + let backup_remove_failure = backup_path.and_then(|bak| { + fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { + final_path: synced.final_path.clone(), + backup_path: Some(bak), + source: remove_err, + }) + }); + let cause = ParquetCorporateActionsError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetCorporateActionsError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + staging_guard.disarm(); + + if let Some(bak) = backup_path { + if let Err(remove_err) = remove_backup(&bak) { + let cause = ParquetCorporateActionsError::Io { + path: bak.clone(), + source: remove_err, + }; + return match fs::rename(&bak, &synced.final_path) { + Ok(()) => Err(cause), + Err(restore_err) => Err(ParquetCorporateActionsError::RollbackFailed { + cause: Box::new(cause), + failures: vec![RollbackFailure { + final_path: synced.final_path, + backup_path: Some(bak), + source: restore_err, + }], + }), + }; + } + } + + Ok(CorporateActionsWriteStats { + rows_written: synced.rows_written, + files_written: 1, + row_groups_written: synced.row_groups_written, + bytes_written: synced.bytes, + }) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::corporate_actions::{ + build_corporate_actions, DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent, + }; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-corp-actions-test-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + pub(super) fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") + } + + pub(super) fn known_at_from_day(d: i32) -> i64 { + i64::from(d) * 86_400_000_000 + 13 * 3_600_000_000 + 30 * 60_000_000 + } + + pub(super) fn make_split_row( + listing_id: i32, + ex_date: i32, + declared_date: Option, + ratio: f64, + ) -> CorporateActionsParquetRow { + let (known_at_day, known_at_source) = match declared_date { + Some(d) if d <= ex_date => (d, KnownAtSource::DeclaredDate), + _ => (ex_date, KnownAtSource::ExDateFallback), + }; + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Split, + ratio: Some(ratio), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(known_at_day), + known_at_source, + } + } + + pub(super) fn make_div_row( + listing_id: i32, + ex_date: i32, + declared_date: Option, + cash_amount: f64, + currency: &'static str, + ) -> CorporateActionsParquetRow { + let (known_at_day, known_at_source) = match declared_date { + Some(d) if d <= ex_date => (d, KnownAtSource::DeclaredDate), + _ => (ex_date, KnownAtSource::ExDateFallback), + }; + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date, + kind: CorporateActionKind::Dividend, + ratio: None, + cash_amount: Some(cash_amount), + currency: Some(Cow::Borrowed(currency)), + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(known_at_day), + known_at_source, + } + } + + pub(super) fn make_otc_transfer_row( + listing_id: i32, + ex_date: i32, + successor_listing_id: i32, + ) -> CorporateActionsParquetRow { + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::OtcDelistTransfer, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: Some(successor_listing_id), + terminal_return: None, + known_at_micros: known_at_from_day(ex_date), + known_at_source: KnownAtSource::DelistDate, + } + } + + pub(super) fn make_delisting_row( + listing_id: i32, + ex_date: i32, + terminal_return: f64, + ) -> CorporateActionsParquetRow { + CorporateActionsParquetRow { + listing_id, + ex_date, + declared_date: None, + kind: CorporateActionKind::Delisting, + ratio: None, + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: Some(terminal_return), + known_at_micros: known_at_from_day(ex_date), + known_at_source: KnownAtSource::DelistDate, + } + } + + fn parse_kind(s: &str) -> CorporateActionKind { + match s { + "split" => CorporateActionKind::Split, + "dividend" => CorporateActionKind::Dividend, + "otc_delist_transfer" => CorporateActionKind::OtcDelistTransfer, + "delisting" => CorporateActionKind::Delisting, + other => panic!("unexpected kind string in Parquet: {other}"), + } + } + + fn parse_known_at_source(s: &str) -> KnownAtSource { + match s { + "declared_date" => KnownAtSource::DeclaredDate, + "ex_date_fallback" => KnownAtSource::ExDateFallback, + "delist_date" => KnownAtSource::DelistDate, + other => panic!("unexpected known_at_source string in Parquet: {other}"), + } + } + + pub(super) fn read_parquet_rows(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let read_i32 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i32"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + let read_opt_i32 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional i32"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + result.push(Some(vals[val_idx])); + val_idx += 1; + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + let read_i64 = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read i64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + let read_opt_f64 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional f64"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + result.push(Some(vals[val_idx])); + val_idx += 1; + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + let read_req_str = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read utf8"); + assert_eq!(read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + vals.into_iter() + .map(|ba| { + std::str::from_utf8(ba.data()) + .expect("valid utf8") + .to_owned() + }) + .collect() + }; + let read_opt_str = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut def_levels = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (read, _, levels_read) = r + .read_records(num_rows, Some(&mut def_levels), None, &mut vals) + .expect("read optional utf8"); + assert_eq!(read, num_rows); + assert_eq!(levels_read, num_rows); + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + let mut val_idx = 0usize; + let mut result = Vec::with_capacity(num_rows); + for def in def_levels { + match def { + 0 => result.push(None), + 1 => { + let text = std::str::from_utf8(vals[val_idx].data()) + .expect("valid utf8") + .to_owned(); + val_idx += 1; + result.push(Some(text)); + } + other => panic!("unexpected definition level {other}"), + } + } + assert_eq!(val_idx, vals.len()); + result + }; + + let listing_id = read_i32(0); + let ex_date = read_i32(1); + let declared_date = read_opt_i32(2); + let kind = read_req_str(3); + let ratio = read_opt_f64(4); + let cash_amount = read_opt_f64(5); + let currency = read_opt_str(6); + let successor_listing_id = read_opt_i32(7); + let terminal_return = read_opt_f64(8); + let known_at_micros = read_i64(9); + let known_at_source = read_req_str(10); + + for i in 0..num_rows { + out.push(CorporateActionsParquetRow { + listing_id: listing_id[i], + ex_date: ex_date[i], + declared_date: declared_date[i], + kind: parse_kind(&kind[i]), + ratio: ratio[i], + cash_amount: cash_amount[i], + currency: currency[i].clone().map(Cow::Owned), + successor_listing_id: successor_listing_id[i], + terminal_return: terminal_return[i], + known_at_micros: known_at_micros[i], + known_at_source: parse_known_at_source(&known_at_source[i]), + }); + } + } + out + } + + pub(super) fn assert_opt_f64_bitwise_eq(actual: Option, expected: Option) { + assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits)); + } + + pub(super) fn assert_row_bitwise_eq( + actual: &CorporateActionsParquetRow, + expected: &CorporateActionsParquetRow, + ) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ex_date, expected.ex_date); + assert_eq!(actual.declared_date, expected.declared_date); + assert_eq!(actual.kind, expected.kind); + assert_opt_f64_bitwise_eq(actual.ratio, expected.ratio); + assert_opt_f64_bitwise_eq(actual.cash_amount, expected.cash_amount); + assert_eq!(actual.currency, expected.currency); + assert_eq!(actual.successor_listing_id, expected.successor_listing_id); + assert_opt_f64_bitwise_eq(actual.terminal_return, expected.terminal_return); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.known_at_source, expected.known_at_source); + } + + pub(super) fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file remaining: {}", + entry.path().display() + ); + } + } + + fn assert_contract_schema(schema: &Type) { + assert_eq!(schema.name(), "corporate_actions"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 11); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 11] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ex_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "declared_date", + PhysicalType::INT32, + Repetition::OPTIONAL, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "kind", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "ratio", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "cash_amount", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::OPTIONAL, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "successor_listing_id", + PhysicalType::INT32, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "terminal_return", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "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, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + let f = &fields[idx]; + assert_eq!(f.name(), name, "field {idx} name"); + assert_eq!(f.get_physical_type(), phys, "field {name} physical type"); + assert_eq!( + f.get_basic_info().repetition(), + rep, + "field {name} repetition" + ); + assert_eq!( + f.get_basic_info().logical_type_ref().cloned(), + logical, + "field {name} logical type" + ); + assert_eq!( + f.get_basic_info().converted_type(), + converted, + "field {name} converted type" + ); + } + } + + #[test] + fn schema_matches_contract_names_types_nullability_and_order() { + let schema = corporate_actions_parquet_schema().expect("build schema"); + assert_contract_schema(schema.as_ref()); + } + + #[test] + fn round_trip_all_kinds_same_date_dividends_multi_row_group_and_zstd_footer() { + let tmp = TempDirGuard::new("round-trip"); + let d_pre = day(1969, 12, 31); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 10); + let d3 = day(2024, 9, 20); + let d4 = day(2025, 1, 15); + + let rows = vec![ + // Pre-1970 split with null declared_date (ex_date_fallback) + make_split_row(10, d_pre, None, 2.0), + // Split with declared_date <= ex_date + make_split_row(10, d2, Some(d2 - 20), 10.0), + // Two dividends on the exact same (listing_id, ex_date): regular + special + make_div_row(10, d2, Some(d2 - 14), 0.25, "USD"), + make_div_row(10, d2, None, 1.50, "USD"), + // Late declaration (declared_date > ex_date) falls back to ex_date_fallback + make_div_row(20, d1, Some(d1 + 5), 0.45, "CAD"), + // OTC delist transfer + make_otc_transfer_row(20, d3, 20_001), + // Terminal delisting at boundaries -1.0 and 0.0 + make_delisting_row(30, d4, -0.30), + make_delisting_row(31, d4, -1.0), + make_delisting_row(32, d4, 0.0), + ]; + + let opts = CorporateActionsWriteOptions { + row_group_rows: 3, + ..CorporateActionsWriteOptions::default() + }; + let stats = write_corporate_actions_dataset(tmp.path(), &rows, opts).unwrap(); + + assert_eq!(stats.rows_written, 9); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("corporate_actions/part.parquet"); + assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written); + + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + assert_eq!(meta.file_metadata().num_rows(), 9); + assert_eq!(meta.num_row_groups(), 3); + assert_contract_schema(meta.file_metadata().schema()); + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_eq!(actual[0].ex_date, -1); + assert_eq!(actual[0].declared_date, None); + assert_eq!(actual[4].declared_date, Some(d1 + 5)); + assert_eq!(actual[4].known_at_source, KnownAtSource::ExDateFallback); + assert_no_transient_files(&tmp.path().join("corporate_actions")); + } + + #[test] + fn build_corporate_actions_converts_and_writes_without_resorting() { + let tmp = TempDirGuard::new("from-builder"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 10); + let d3 = day(2024, 9, 20); + + let splits = vec![ + ( + 101i32, + SplitActionEvent { + ex_date: d2, + ratio: 10.0, + declared_date: Some(d2 - 19), + }, + ), + ( + 101i32, + SplitActionEvent { + ex_date: d1, + ratio: 1.0, // no-op dropped by builder + declared_date: None, + }, + ), + ]; + let dividends = vec![ + ( + 101i32, + DividendActionEvent { + ex_date: d2, + cash: 0.10, + currency: "USD".to_string(), + declared_date: Some(d2 - 14), + }, + ), + ( + 101i32, + DividendActionEvent { + ex_date: d2, + cash: 0.50, + currency: "USD".to_string(), + declared_date: None, + }, + ), + ( + 202i32, + DividendActionEvent { + ex_date: d1, + cash: 0.90, + currency: "CAD".to_string(), + declared_date: Some(d1 + 3), // late declaration -> ExDateFallback + }, + ), + ]; + let delistings = vec![ + ( + 202i32, + DelistingOutcomeEvent { + delist_date: d3, + successor_key: Some(20_201), + terminal_return: None, + }, + ), + ( + 303i32, + DelistingOutcomeEvent { + delist_date: d3, + successor_key: None, + terminal_return: Some(-0.30), + }, + ), + ]; + + let built = build_corporate_actions(splits, dividends, delistings).unwrap(); + let rows: Vec = built + .rows + .iter() + .map(|r| { + CorporateActionsParquetRow::from_corporate_action_row( + r, + known_at_from_day(r.known_at_date), + ) + }) + .collect(); + assert_eq!(rows.len(), 6); + + let stats = write_corporate_actions_dataset( + tmp.path(), + &rows, + CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let actual = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("corporate_actions")); + } + + #[test] + fn empty_input_creates_nothing_and_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("empty"); + let fresh = tmp.path().join("fresh"); + let stats = write_corporate_actions_dataset( + &fresh, + std::iter::empty::(), + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, CorporateActionsWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let seed_rows = vec![make_div_row(10, day(2024, 3, 15), None, 0.25, "USD")]; + write_corporate_actions_dataset( + &seeded, + &seed_rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + let part = seeded.join("corporate_actions/part.parquet"); + let before = fs::read(&part).unwrap(); + + let empty_stats = write_corporate_actions_dataset( + &seeded, + std::iter::empty::(), + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, CorporateActionsWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("corporate_actions")); + } + + #[test] + fn determinism_identical_rows_produce_byte_identical_files() { + let tmp = TempDirGuard::new("determinism"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 10); + let rows = vec![ + make_split_row(1, d1, Some(d1 - 14), 4.0), + make_div_row(1, d2, Some(d2 - 14), 0.25, "USD"), + make_otc_transfer_row(2, d2, 2001), + make_delisting_row(3, d2, -0.3), + ]; + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }; + write_corporate_actions_dataset(&out_a, &rows, opts).unwrap(); + write_corporate_actions_dataset(&out_b, &rows, opts).unwrap(); + + let bytes_a = fs::read(out_a.join("corporate_actions/part.parquet")).unwrap(); + let bytes_b = fs::read(out_b.join("corporate_actions/part.parquet")).unwrap(); + assert_eq!(bytes_a, bytes_b); + } +} + +#[cfg(test)] +#[path = "parquet_corporate_actions_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_corporate_actions_tests.rs b/tools/curate-etl/src/parquet_corporate_actions_tests.rs new file mode 100644 index 00000000..d8bc0b27 --- /dev/null +++ b/tools/curate-etl/src/parquet_corporate_actions_tests.rs @@ -0,0 +1,1374 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use parquet::basic::Encoding; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{ + assert_no_transient_files, assert_row_bitwise_eq, day, known_at_from_day, make_delisting_row, + make_div_row, make_otc_transfer_row, make_split_row, read_parquet_rows, TempDirGuard, +}; +use super::{ + write_corporate_actions_dataset, write_corporate_actions_dataset_with_hooks, + CorporateActionsParquetRow, CorporateActionsWriteOptions, ParquetCorporateActionsError, +}; +use crate::corporate_actions::{CorporateActionKind, KnownAtSource}; +use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; +use crate::parquet_publish::STRING_WRITE_BATCH_ROWS; + +fn seed_existing(out_dir: &Path) -> (PathBuf, Vec) { + let seed = vec![ + make_split_row(100, day(2024, 1, 15), Some(day(2024, 1, 1)), 2.0), + make_div_row(100, day(2024, 6, 15), Some(day(2024, 6, 1)), 0.50, "USD"), + ]; + write_corporate_actions_dataset(out_dir, &seed, CorporateActionsWriteOptions::default()) + .unwrap(); + let part = out_dir.join("corporate_actions/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +#[test] +fn single_row_and_row_group_boundary_counts_with_pre_1970_split() { + let tmp = TempDirGuard::new("rg-boundaries"); + + // 1 row: pre-1970 split with null declared_date + let out_1 = tmp.path().join("one"); + let single = vec![make_split_row(7, day(1969, 12, 31), None, 2.0)]; + let stats_1 = write_corporate_actions_dataset( + &out_1, + &single, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats_1.rows_written, 1); + assert_eq!(stats_1.files_written, 1); + assert_eq!(stats_1.row_groups_written, 1); + let actual_1 = read_parquet_rows(&out_1.join("corporate_actions/part.parquet")); + assert_eq!(actual_1.len(), 1); + assert_row_bitwise_eq(&actual_1[0], &single[0]); + assert_eq!(actual_1[0].ex_date, -1); + assert!(actual_1[0].declared_date.is_none()); + + // Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group) + let base = day(2024, 1, 2); + let rows_exact = vec![ + make_split_row(10, base, Some(base - 14), 2.0), + make_div_row(10, base, Some(base - 10), 0.25, "USD"), + make_otc_transfer_row(10, base + 30, 10_001), + make_delisting_row(11, base + 60, -0.30), + ]; + let out_exact = tmp.path().join("exact"); + let opts = CorporateActionsWriteOptions { + row_group_rows: 4, + ..CorporateActionsWriteOptions::default() + }; + let stats_exact = write_corporate_actions_dataset(&out_exact, &rows_exact, opts).unwrap(); + assert_eq!(stats_exact.rows_written, 4); + assert_eq!(stats_exact.row_groups_written, 1); + let reader_exact = SerializedFileReader::new( + File::open(out_exact.join("corporate_actions/part.parquet")).unwrap(), + ) + .unwrap(); + assert_eq!(reader_exact.metadata().num_row_groups(), 1); + assert_eq!(reader_exact.metadata().row_group(0).num_rows(), 4); + + // row_group_rows + 1 (5 rows, row_group_rows = 4 => 2 row groups: [4, 1]) + let rows_plus_one = vec![ + make_split_row(1, day(1969, 6, 15), None, 3.0), + make_div_row(1, base, Some(base - 14), 0.40, "USD"), + make_div_row(1, base, None, 0.80, "USD"), + make_otc_transfer_row(2, base, 2001), + make_delisting_row(3, base, -1.0), + ]; + let out_plus = tmp.path().join("plus-one"); + let stats_plus = write_corporate_actions_dataset(&out_plus, &rows_plus_one, opts).unwrap(); + assert_eq!(stats_plus.rows_written, 5); + assert_eq!(stats_plus.row_groups_written, 2); + let p_plus = out_plus.join("corporate_actions/part.parquet"); + let reader_plus = SerializedFileReader::new(File::open(&p_plus).unwrap()).unwrap(); + let rg_sizes: Vec = (0..reader_plus.metadata().num_row_groups()) + .map(|i| reader_plus.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![4, 1]); + let actual_plus = read_parquet_rows(&p_plus); + assert_eq!(actual_plus.len(), rows_plus_one.len()); + for (a, e) in actual_plus.iter().zip(&rows_plus_one) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_plus.join("corporate_actions")); +} + +#[test] +fn multi_batch_all_null_and_mixed_null_optional_columns_round_trip() { + let tmp = TempDirGuard::new("opt-col-batches"); + let base = day(2000, 1, 3); + + // 100% split rows with declared_date = None spanning > STRING_WRITE_BATCH_ROWS (4096) + // exercises all-null optional i32 (declared_date, successor_listing_id), + // optional f64 (cash_amount, terminal_return), and optional String (currency). + let all_null_count = STRING_WRITE_BATCH_ROWS + 137; + let all_null_rows: Vec = (0..all_null_count) + .map(|i| { + let listing_id = (i / 100) as i32 + 1; + let ex_date = base + (i % 100) as i32; + make_split_row(listing_id, ex_date, None, 2.0) + }) + .collect(); + let out_null = tmp.path().join("all-null"); + let stats_null = write_corporate_actions_dataset( + &out_null, + &all_null_rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats_null.rows_written, all_null_count); + assert_eq!(stats_null.row_groups_written, 1); + let actual_null = read_parquet_rows(&out_null.join("corporate_actions/part.parquet")); + assert_eq!(actual_null.len(), all_null_rows.len()); + for (a, e) in actual_null.iter().zip(&all_null_rows) { + assert_row_bitwise_eq(a, e); + } + + // > STRING_WRITE_BATCH_ROWS * 2 mixed rows crossing multiple 4,096-row batches + // including an all-null-currency middle chunk (rows 4096..8192) inside the same row group. + let mixed_count = STRING_WRITE_BATCH_ROWS * 2 + 257; + let mixed_rows: Vec = (0..mixed_count) + .map(|i| { + let listing_id = (i / 500) as i32 + 1; + let ex_date = base + (i % 500) as i32; + if (STRING_WRITE_BATCH_ROWS..STRING_WRITE_BATCH_ROWS * 2).contains(&i) { + make_delisting_row(listing_id, ex_date, -0.30) + } else { + match i % 4 { + 0 => make_split_row(listing_id, ex_date, Some(ex_date - 14), 2.0), + 1 => make_div_row(listing_id, ex_date, Some(ex_date - 10), 0.25, "USD"), + 2 => make_div_row(listing_id, ex_date, None, 0.40, "CAD"), + _ => make_otc_transfer_row(listing_id, ex_date, listing_id + 100_000), + } + } + }) + .collect(); + + let out_mixed = tmp.path().join("mixed-multi-batch"); + let stats_mixed = write_corporate_actions_dataset( + &out_mixed, + &mixed_rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats_mixed.rows_written, mixed_count); + assert_eq!(stats_mixed.row_groups_written, 1); + let actual_mixed = read_parquet_rows(&out_mixed.join("corporate_actions/part.parquet")); + assert_eq!(actual_mixed.len(), mixed_rows.len()); + for (a, e) in actual_mixed.iter().zip(&mixed_rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&out_mixed.join("corporate_actions")); +} + +#[test] +fn dictionary_encoding_active_on_string_columns_and_invalid_options_preserve_state() { + let tmp = TempDirGuard::new("dict-zstd"); + let base = day(2024, 1, 2); + let rows: Vec = (0..64_i32) + .map(|i| { + let listing_id = if i < 32 { 1 } else { 2 }; + let d = base + (i % 32); + match i % 4 { + 0 => make_split_row(listing_id, d, Some(d - 14), 2.0), + 1 => make_div_row(listing_id, d, Some(d - 10), 0.30, "USD"), + 2 => make_div_row(listing_id, d, None, 0.45, "CAD"), + _ => make_delisting_row(listing_id, d, -0.30), + } + }) + .collect(); + + let out_ok = tmp.path().join("lvl-3"); + write_corporate_actions_dataset(&out_ok, &rows, CorporateActionsWriteOptions::default()) + .unwrap(); + let p = out_ok.join("corporate_actions/part.parquet"); + let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap(); + let rg0 = reader.metadata().row_group(0); + + for (col_idx, col_name) in [(3, "kind"), (6, "currency"), (10, "known_at_source")] { + let col = rg0.column(col_idx); + assert!( + col.encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "expected dictionary encoding on {col_name} column, got {:?}", + col.encodings().collect::>() + ); + } + + // Invalid row_group_rows and zstd_level in fresh dir + let out_bad = tmp.path().join("bad-opts-fresh"); + assert!(matches!( + write_corporate_actions_dataset( + &out_bad, + &rows, + CorporateActionsWriteOptions { + row_group_rows: 0, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidRowGroupRows) + )); + assert!(matches!( + write_corporate_actions_dataset( + &out_bad, + &rows, + CorporateActionsWriteOptions { + zstd_level: 23, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_corporate_actions_dataset( + &out_bad, + &rows, + CorporateActionsWriteOptions { + zstd_level: 99, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidZstdLevel { level: 99 }) + )); + assert!(!out_bad.exists(), "invalid options must not create out_dir"); + + // Invalid options in seeded dir leave existing part.parquet byte-identical + let out_seeded = tmp.path().join("bad-opts-seeded"); + let (part, before) = seed_existing(&out_seeded); + assert!(matches!( + write_corporate_actions_dataset( + &out_seeded, + &rows, + CorporateActionsWriteOptions { + row_group_rows: 0, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidRowGroupRows) + )); + assert!(matches!( + write_corporate_actions_dataset( + &out_seeded, + &rows, + CorporateActionsWriteOptions { + zstd_level: 23, + ..CorporateActionsWriteOptions::default() + } + ), + Err(ParquetCorporateActionsError::InvalidZstdLevel { level: 23 }) + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&out_seeded.join("corporate_actions")); +} + +#[test] +fn overwrite_replaces_existing_part_parquet_and_leaves_no_transients() { + let tmp = TempDirGuard::new("overwrite"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![ + make_div_row(500, day(2025, 4, 15), Some(day(2025, 4, 1)), 0.75, "CAD"), + make_delisting_row(500, day(2025, 6, 1), -0.50), + ]; + let stats = write_corporate_actions_dataset( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats.rows_written, 2); + assert_eq!(stats.files_written, 1); + + let after = fs::read(&part).unwrap(); + assert_ne!(after, before); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), replacement.len()); + for (a, e) in actual.iter().zip(&replacement) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn validation_errors_return_typed_variants_and_preserve_existing_state() { + let tmp = TempDirGuard::new("validation"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 6, 15); + + type ErrorCheck = fn(&ParquetCorporateActionsError) -> bool; + let bad_cases: Vec<(&str, Vec, ErrorCheck)> = vec![ + // Unsorted input on listing_id, ex_date, and kind + ( + "unsorted-listing", + vec![ + make_div_row(2, d1, None, 0.25, "USD"), + make_div_row(1, d1, None, 0.25, "USD"), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::UnsortedInput { + prev_listing_id: 2, + listing_id: 1, + .. + } + ) + }, + ), + ( + "unsorted-ex-date", + vec![ + make_div_row(1, d2, None, 0.25, "USD"), + make_div_row(1, d1, None, 0.25, "USD"), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::UnsortedInput { + listing_id: 1, + prev_kind: CorporateActionKind::Dividend, + kind: CorporateActionKind::Dividend, + .. + } + ) + }, + ), + ( + "unsorted-kind", + vec![ + make_div_row(1, d1, None, 0.25, "USD"), + make_split_row(1, d1, None, 2.0), + ], + |e| { + matches!( + e, + ParquetCorporateActionsError::UnsortedInput { + listing_id: 1, + prev_kind: CorporateActionKind::Dividend, + kind: CorporateActionKind::Split, + .. + } + ) + }, + ), + // Date year range checks + ( + "ex-date-below-min-year", + vec![make_split_row(1, day(1899, 12, 31), None, 2.0)], + |e| { + matches!( + e, + ParquetCorporateActionsError::ExDateOutOfRange { + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "ex-date-above-max-year", + vec![make_split_row(1, day(2201, 1, 1), None, 2.0)], + |e| { + matches!( + e, + ParquetCorporateActionsError::ExDateOutOfRange { + year: 2201, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "declared-date-below-min-year", + vec![make_split_row(1, d1, Some(day(1899, 12, 31)), 2.0)], + |e| { + matches!( + e, + ParquetCorporateActionsError::DeclaredDateOutOfRange { + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + ( + "declared-date-above-max-year", + vec![make_div_row(1, d1, Some(day(2201, 1, 1)), 0.25, "USD")], + |e| { + matches!( + e, + ParquetCorporateActionsError::DeclaredDateOutOfRange { + year: 2201, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ) + }, + ), + // Split ratio violations + ( + "split-ratio-none", + vec![CorporateActionsParquetRow { + ratio: None, + ..make_split_row(1, d1, None, 2.0) + }], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { value: None, .. }), + ), + ( + "split-ratio-zero", + vec![make_split_row(1, d1, None, 0.0)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { value: Some(v), .. } if *v == 0.0), + ), + ( + "split-ratio-neg-zero", + vec![make_split_row(1, d1, None, -0.0)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + ( + "split-ratio-negative", + vec![make_split_row(1, d1, None, -2.0)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + ( + "split-ratio-nan", + vec![make_split_row(1, d1, None, f64::NAN)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + ( + "split-ratio-inf", + vec![make_split_row(1, d1, None, f64::INFINITY)], + |e| matches!(e, ParquetCorporateActionsError::InvalidRatio { .. }), + ), + // Dividend cash_amount & currency violations + ( + "div-cash-none", + vec![CorporateActionsParquetRow { + cash_amount: None, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { value: None, .. }), + ), + ( + "div-cash-zero", + vec![make_div_row(1, d1, None, 0.0, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-neg-zero", + vec![make_div_row(1, d1, None, -0.0, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-negative", + vec![make_div_row(1, d1, None, -0.05, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-nan", + vec![make_div_row(1, d1, None, f64::NAN, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-cash-inf", + vec![make_div_row(1, d1, None, f64::INFINITY, "USD")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCashAmount { .. }), + ), + ( + "div-currency-none", + vec![CorporateActionsParquetRow { + currency: None, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| matches!(e, ParquetCorporateActionsError::InvalidCurrency { .. }), + ), + ( + "div-currency-empty", + vec![make_div_row(1, d1, None, 0.25, "")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCurrency { .. }), + ), + ( + "div-currency-whitespace", + vec![make_div_row(1, d1, None, 0.25, " \t ")], + |e| matches!(e, ParquetCorporateActionsError::InvalidCurrency { .. }), + ), + // OTC delist transfer successor_listing_id violations + ( + "otc-successor-none", + vec![CorporateActionsParquetRow { + successor_listing_id: None, + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidSuccessorListingId { + successor_listing_id: None, + .. + } + ) + }, + ), + ( + "otc-successor-self", + vec![make_otc_transfer_row(42, d1, 42)], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidSuccessorListingId { + listing_id: 42, + successor_listing_id: Some(42), + .. + } + ) + }, + ), + // Delisting terminal_return violations + ( + "delist-return-none", + vec![CorporateActionsParquetRow { + terminal_return: None, + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InvalidTerminalReturn { value: None, .. } + ) + }, + ), + ( + "delist-return-nan", + vec![make_delisting_row(1, d1, f64::NAN)], + |e| matches!(e, ParquetCorporateActionsError::InvalidTerminalReturn { .. }), + ), + ( + "delist-return-inf", + vec![make_delisting_row(1, d1, f64::NEG_INFINITY)], + |e| matches!(e, ParquetCorporateActionsError::InvalidTerminalReturn { .. }), + ), + ( + "delist-return-below-minus-one", + vec![make_delisting_row(1, d1, -1.0001)], + |e| matches!(e, ParquetCorporateActionsError::InvalidTerminalReturn { .. }), + ), + ( + "delist-return-above-zero", + vec![make_delisting_row(1, d1, 0.0001)], + |e| matches!(e, ParquetCorporateActionsError::InvalidTerminalReturn { .. }), + ), + // Forbidden fields for Split + ( + "split-forbids-cash", + vec![CorporateActionsParquetRow { + cash_amount: Some(0.25), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Split, + field: "cash_amount", + .. + } + ) + }, + ), + ( + "split-forbids-currency", + vec![CorporateActionsParquetRow { + currency: Some(Cow::Borrowed("USD")), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Split, + field: "currency", + .. + } + ) + }, + ), + ( + "split-forbids-successor", + vec![CorporateActionsParquetRow { + successor_listing_id: Some(2), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Split, + field: "successor_listing_id", + .. + } + ) + }, + ), + ( + "split-forbids-terminal-return", + vec![CorporateActionsParquetRow { + terminal_return: Some(-0.3), + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Split, + field: "terminal_return", + .. + } + ) + }, + ), + // Forbidden fields for Dividend + ( + "div-forbids-ratio", + vec![CorporateActionsParquetRow { + ratio: Some(2.0), + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Dividend, + field: "ratio", + .. + } + ) + }, + ), + ( + "div-forbids-successor", + vec![CorporateActionsParquetRow { + successor_listing_id: Some(2), + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Dividend, + field: "successor_listing_id", + .. + } + ) + }, + ), + ( + "div-forbids-terminal-return", + vec![CorporateActionsParquetRow { + terminal_return: Some(-0.3), + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Dividend, + field: "terminal_return", + .. + } + ) + }, + ), + // Forbidden fields for OtcDelistTransfer + ( + "otc-forbids-ratio", + vec![CorporateActionsParquetRow { + ratio: Some(2.0), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::OtcDelistTransfer, + field: "ratio", + .. + } + ) + }, + ), + ( + "otc-forbids-cash", + vec![CorporateActionsParquetRow { + cash_amount: Some(0.25), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::OtcDelistTransfer, + field: "cash_amount", + .. + } + ) + }, + ), + ( + "otc-forbids-currency", + vec![CorporateActionsParquetRow { + currency: Some(Cow::Borrowed("USD")), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::OtcDelistTransfer, + field: "currency", + .. + } + ) + }, + ), + ( + "otc-forbids-terminal-return", + vec![CorporateActionsParquetRow { + terminal_return: Some(-0.3), + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::OtcDelistTransfer, + field: "terminal_return", + .. + } + ) + }, + ), + // Forbidden fields for Delisting + ( + "delist-forbids-ratio", + vec![CorporateActionsParquetRow { + ratio: Some(2.0), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Delisting, + field: "ratio", + .. + } + ) + }, + ), + ( + "delist-forbids-cash", + vec![CorporateActionsParquetRow { + cash_amount: Some(0.25), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Delisting, + field: "cash_amount", + .. + } + ) + }, + ), + ( + "delist-forbids-currency", + vec![CorporateActionsParquetRow { + currency: Some(Cow::Borrowed("USD")), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Delisting, + field: "currency", + .. + } + ) + }, + ), + ( + "delist-forbids-successor", + vec![CorporateActionsParquetRow { + successor_listing_id: Some(2), + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::ForbiddenFieldForKind { + kind: CorporateActionKind::Delisting, + field: "successor_listing_id", + .. + } + ) + }, + ), + // Inconsistent known_at_source + ( + "split-delist-date-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::DelistDate, + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Split, + known_at_source: KnownAtSource::DelistDate, + .. + } + ) + }, + ), + ( + "div-delist-date-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::DelistDate, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Dividend, + known_at_source: KnownAtSource::DelistDate, + .. + } + ) + }, + ), + ( + "split-declared-source-without-declared-date", + vec![CorporateActionsParquetRow { + declared_date: None, + known_at_source: KnownAtSource::DeclaredDate, + ..make_split_row(1, d1, None, 2.0) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Split, + known_at_source: KnownAtSource::DeclaredDate, + declared_date: None, + .. + } + ) + }, + ), + ( + "div-declared-source-without-declared-date", + vec![CorporateActionsParquetRow { + declared_date: None, + known_at_source: KnownAtSource::DeclaredDate, + ..make_div_row(1, d1, None, 0.25, "USD") + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Dividend, + known_at_source: KnownAtSource::DeclaredDate, + declared_date: None, + .. + } + ) + }, + ), + ( + "otc-ex-date-fallback-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::ExDateFallback, + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::OtcDelistTransfer, + known_at_source: KnownAtSource::ExDateFallback, + .. + } + ) + }, + ), + ( + "otc-declared-date-source", + vec![CorporateActionsParquetRow { + declared_date: Some(d1 - 5), + known_at_source: KnownAtSource::DeclaredDate, + ..make_otc_transfer_row(1, d1, 2) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::OtcDelistTransfer, + known_at_source: KnownAtSource::DeclaredDate, + .. + } + ) + }, + ), + ( + "delist-ex-date-fallback-source", + vec![CorporateActionsParquetRow { + known_at_source: KnownAtSource::ExDateFallback, + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Delisting, + known_at_source: KnownAtSource::ExDateFallback, + .. + } + ) + }, + ), + ( + "delist-declared-date-source", + vec![CorporateActionsParquetRow { + declared_date: Some(d1 - 5), + known_at_source: KnownAtSource::DeclaredDate, + ..make_delisting_row(1, d1, -0.3) + }], + |e| { + matches!( + e, + ParquetCorporateActionsError::InconsistentKnownAtSource { + kind: CorporateActionKind::Delisting, + known_at_source: KnownAtSource::DeclaredDate, + .. + } + ) + }, + ), + ]; + + for (label, rows, check) in bad_cases { + let fresh = tmp.path().join(format!("fresh-{label}")); + let err = write_corporate_actions_dataset( + &fresh, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!(check(&err), "fresh case '{label}' got unexpected {err:?}"); + assert!( + !fresh.join("corporate_actions/part.parquet").exists(), + "fresh case '{label}' must not publish part.parquet" + ); + assert_no_transient_files(&fresh.join("corporate_actions")); + + let seeded = tmp.path().join(format!("seeded-{label}")); + let (part, before) = seed_existing(&seeded); + let err_s = write_corporate_actions_dataset( + &seeded, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!(check(&err_s), "seeded case '{label}' got unexpected {err_s:?}"); + assert_eq!( + fs::read(&part).unwrap(), + before, + "seeded case '{label}' must preserve existing part.parquet" + ); + assert_no_transient_files(&seeded.join("corporate_actions")); + } +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_file() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let (part, before) = seed_existing(tmp.path()); + + let base = day(2024, 1, 2); + let mut rows: Vec = (0..5_i32) + .map(|i| make_div_row(1, base + i * 30, Some(base + i * 30 - 10), 0.25, "USD")) + .collect(); + rows.push(CorporateActionsParquetRow { + listing_id: 1, + ex_date: base + 6 * 30, + declared_date: None, + kind: CorporateActionKind::Split, + ratio: Some(f64::NAN), + cash_amount: None, + currency: None, + successor_listing_id: None, + terminal_return: None, + known_at_micros: known_at_from_day(base + 6 * 30), + known_at_source: KnownAtSource::ExDateFallback, + }); + + let err = write_corporate_actions_dataset( + tmp.path(), + &rows, + CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetCorporateActionsError::InvalidRatio { .. } + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn out_dir_or_corporate_actions_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_div_row(1, day(2024, 3, 15), None, 0.25, "USD")]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = write_corporate_actions_dataset( + &file_as_out, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(err, ParquetCorporateActionsError::Io { .. })); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out_with_file_ds = tmp.path().join("ds-is-file"); + fs::create_dir_all(&out_with_file_ds).unwrap(); + let ds_file = out_with_file_ds.join("corporate_actions"); + fs::write(&ds_file, b"file-not-dir").unwrap(); + let err2 = write_corporate_actions_dataset( + &out_with_file_ds, + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(err2, ParquetCorporateActionsError::Io { .. })); + assert_eq!(fs::read(&ds_file).unwrap(), b"file-not-dir"); +} + +#[test] +fn stale_lock_times_out_leaving_lock_and_existing_part_intact() { + let tmp = TempDirGuard::new("stale-lock"); + let (part, before) = seed_existing(tmp.path()); + let lock_path = tmp.path().join("corporate_actions/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_div_row(1, day(2024, 6, 15), None, 0.50, "USD")]; + let err = write_corporate_actions_dataset_with_hooks( + tmp.path(), + &rows, + CorporateActionsWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + |path| fs::remove_file(path), + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetCorporateActionsError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout, got {err:?}" + ); + assert!( + lock_path.exists(), + "stale lock must not be deleted by timed-out writer" + ); + assert_eq!(fs::read(&part).unwrap(), before); +} + +#[test] +fn live_part_parquet_stays_readable_between_backup_and_rename() { + let tmp = TempDirGuard::new("live-readable"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(200, day(2024, 9, 15), None, 0.60, "CAD")]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_corporate_actions_dataset_with_hooks( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + Duration::from_secs(5), + move |final_path, backup_path| { + assert!( + backup_path.is_some(), + "expected backup path for existing file" + ); + assert_eq!(fs::read(final_path).unwrap(), before); + assert_eq!(fs::read(backup_path.unwrap()).unwrap(), before); + *observed_clone.lock().unwrap() = true; + }, + |path| fs::remove_file(path), + ) + .unwrap(); + + assert!(*observed_live.lock().unwrap()); + let actual = read_parquet_rows(&part); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() { + let tmp = TempDirGuard::new("rename-blocker"); + let ds_dir = tmp.path().join("corporate_actions"); + let blocking_dir = ds_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + + let unowned_tmp = ds_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_div_row(1, day(2024, 3, 15), None, 0.25, "USD")]; + let err = write_corporate_actions_dataset( + tmp.path(), + &rows, + CorporateActionsWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetCorporateActionsError::Io { .. }), + "got {err:?}" + ); + assert!(blocking_dir.is_dir(), "directory blocker must remain intact"); + assert_eq!( + fs::read(&unowned_tmp).unwrap(), + b"keep-me", + "unowned .tmp file must be preserved" + ); + + let mut entries: Vec = fs::read_dir(&ds_dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + entries.sort(); + assert_eq!( + entries, + vec![ + "part.parquet".to_string(), + "part.parquet.unowned-other-run.tmp".to_string(), + ] + ); +} + +#[test] +fn concurrent_in_process_writers_serialize_cleanly() { + let tmp = TempDirGuard::new("concurrent-unit"); + let out = Arc::new(tmp.path().to_path_buf()); + + let out_1 = Arc::clone(&out); + let handle_1 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + thread::sleep(Duration::from_millis(30)); + } + make_div_row(10, day(2024, 1, 15) + i * 30, None, 0.25, "USD") + }); + write_corporate_actions_dataset( + out_1.as_path(), + iter, + CorporateActionsWriteOptions::default(), + ) + }); + + thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let handle_2 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| make_split_row(20, day(2024, 2, 15) + i * 30, None, 2.0)); + write_corporate_actions_dataset( + out_2.as_path(), + iter, + CorporateActionsWriteOptions::default(), + ) + }); + + let s1 = handle_1.join().unwrap().unwrap(); + let s2 = handle_2.join().unwrap().unwrap(); + assert_eq!(s1.rows_written, 2); + assert_eq!(s2.rows_written, 2); + + let got = read_parquet_rows(&tmp.path().join("corporate_actions/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.listing_id == 10) || got.iter().all(|r| r.listing_id == 20), + "output must come entirely from one writer generation" + ); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn panicking_iterator_cleans_up_staging_file_and_releases_lock() { + let tmp = TempDirGuard::new("panic-unwind"); + let (part, before) = seed_existing(tmp.path()); + + let out = tmp.path().to_path_buf(); + let opts = CorporateActionsWriteOptions { + row_group_rows: 2, + ..CorporateActionsWriteOptions::default() + }; + let result = std::panic::catch_unwind(move || { + let base = day(2024, 3, 15); + let iter = (0..5_i32).map(move |i| { + if i == 3 { + panic!("simulated iterator panic after row-group flush"); + } + make_div_row(1, base + i * 30, None, 0.25, "USD") + }); + let _ = write_corporate_actions_dataset(&out, iter, opts); + }); + assert!(result.is_err(), "iterator must have panicked"); + + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("corporate_actions")); + + let replacement = vec![make_div_row(99, day(2024, 6, 15), None, 0.75, "CAD")]; + let stats = write_corporate_actions_dataset( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); + let got = read_parquet_rows(&part); + assert_eq!(got.len(), 1); + assert_row_bitwise_eq(&got[0], &replacement[0]); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn backup_unlink_failure_after_rename_restores_live_file_and_returns_error() { + let tmp = TempDirGuard::new("backup-unlink-fail"); + let (part, before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(300, day(2024, 9, 15), None, 0.60, "CAD")]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_corporate_actions_dataset_with_hooks( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + assert!( + matches!( + err, + ParquetCorporateActionsError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "expected Io error on backup path, got {err:?}" + ); + assert_eq!( + fs::read(&part).unwrap(), + before, + "live part.parquet must be atomically restored from backup" + ); + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} + +#[test] +fn backup_unlink_and_restore_failure_reports_rollback_failed() { + let tmp = TempDirGuard::new("backup-rollback-fail"); + let (part, _before) = seed_existing(tmp.path()); + + let replacement = vec![make_div_row(300, day(2024, 9, 15), None, 0.60, "CAD")]; + let observed_bak: Arc>> = Arc::new(Mutex::new(None)); + let observed_bak_clone = Arc::clone(&observed_bak); + + let err = write_corporate_actions_dataset_with_hooks( + tmp.path(), + &replacement, + CorporateActionsWriteOptions::default(), + Duration::from_secs(5), + |_, _| {}, + move |bak_path| { + *observed_bak_clone.lock().unwrap() = Some(bak_path.to_path_buf()); + let _ = fs::remove_file(bak_path); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "simulated backup unlink failure", + )) + }, + ) + .unwrap_err(); + + let expected_bak = observed_bak + .lock() + .unwrap() + .clone() + .expect("backup unlink hook must be called"); + match err { + ParquetCorporateActionsError::RollbackFailed { cause, failures } => { + assert!( + matches!( + *cause, + ParquetCorporateActionsError::Io { ref path, ref source } + if path == &expected_bak + && source.kind() == std::io::ErrorKind::PermissionDenied + ), + "unexpected cause: {cause:?}" + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, part); + assert_eq!( + failures[0].backup_path.as_deref(), + Some(expected_bak.as_path()) + ); + assert_eq!(failures[0].source.kind(), std::io::ErrorKind::NotFound); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + assert_no_transient_files(&tmp.path().join("corporate_actions")); +} diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index 2b7fb32b..fd9b89c2 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -381,6 +381,25 @@ pub(crate) fn write_i32_col( col.close() } +pub(crate) fn write_optional_i32_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[i32], + def_levels: &[i16], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::Int32ColumnWriter(typed) => { + typed.write_batch(values, Some(def_levels), None)?; + } + _ => { + return Err(ParquetError::General( + "expected INT32 column writer".to_string(), + )); + } + } + col.close() +} + pub(crate) fn write_i64_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, values: &[i64], @@ -418,6 +437,14 @@ pub(crate) fn write_f64_col( col.close() } +pub(crate) fn write_optional_f64_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[f64], + def_levels: &[i16], +) -> Result<(), ParquetError> { + write_f64_col(rg_writer, values, Some(def_levels)) +} + pub(crate) fn write_interned_str_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, ids: &[u32],