diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index f067bedc..47a90244 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, and the `M1.2i` streaming Zstd Parquet writer for `bars_1d`. +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`, and the `M1.2j` streaming Zstd Parquet writer for `shorts`. ## Scope & Sign Conventions @@ -212,6 +212,48 @@ Rules: - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` - Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +## `shorts` Parquet Writer (`M1.2j`) + +`write_shorts_dataset` (`src/parquet_shorts.rs`) streams strictly ascending `(listing_id, report_date)` `ShortsParquetRow` records (with `From<&ShortRow>` / `From>` conversions from `build_shorts`) into a single Zstd-compressed Parquet file matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 7-column contract schema (`shorts_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `report_date` (`INT32`, `REQUIRED`, `DATE`) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `shares_short` (`DOUBLE`, `REQUIRED`) + - `net_change` (`DOUBLE`, `OPTIONAL`) + - `pct_float` (`DOUBLE`, `OPTIONAL`) + - `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) +2. **Layout, compression & streaming:** + - Writes `/shorts/part.parquet` (unpartitioned). + - Empty input returns `Ok(ShortsWriteStats::default())` without creating `/shorts` and without modifying or removing any pre-existing `part.parquet`. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `ShortsWriteOptions::zstd_level`). + - Bounded streaming buffer (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `ShortsWriteOptions::row_group_rows`): buffers at most one row group of columnar data (with string interning for `source`), flushing and clearing on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Validation, concurrency & atomic publish rules:** + - Input must be strictly ascending by `(listing_id, report_date)` (rejecting duplicates and out-of-order rows). + - `shares_short` must be finite and `>= 0.0`; `net_change` and `pct_float` must be finite when `Some`; `known_at_micros` must be strictly after `report_date` `00:00:00 UTC` (compared in `i128` to avoid overflow on extreme `i32` epoch days); `source` must be non-empty after trimming. + - Reuses the shared `parquet_publish` locking and atomic publication path: concurrent writers targeting `/shorts` 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 (`ParquetShortsError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_listing_id, prev_report_date, listing_id, report_date }` + - `DuplicateKey { listing_id, report_date }` + - `InvalidSharesShort { listing_id, report_date, value }` + - `InvalidNetChange { listing_id, report_date, value }` + - `InvalidPctFloat { listing_id, report_date, value }` + - `KnownAtNotAfterReportDate { listing_id, report_date, known_at_micros }` + - `EmptySource { listing_id, report_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-shorts` + - Input: `rows=1000000`, `listings=12500`, `raw_row_bytes=50` (semi-monthly dates `2017-04-15..=2026-04-30`) + - Output: `files=1`, `row_groups=1`, `bytes=6741816`, `read_back_rows=1000000` + - Perf: `elapsed=106.79 ms`, `throughput=9364116 rows/s`, `write=60.21 MB/s`, `size=6.74 bytes/row`, `compression=7.42x` + ## Local Benchmarks ### `bench-split` @@ -340,13 +382,27 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` - Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +### `bench-parquet-shorts` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `1,000,000` sorted `ShortsParquetRow` rows across `12,500` listings on semi-monthly dates (`2017-04-15..=2026-04-30`) with CIRO `+4` business-day `17:00 ET` `known_at` timestamps, writing `shorts/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-shorts [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-shorts` + +- Input: `rows=1000000`, `listings=12500`, `raw_row_bytes=50` +- Output: `files=1`, `row_groups=1`, `bytes=6741816`, `read_back_rows=1000000` +- Perf: `elapsed=106.79 ms`, `throughput=9364116 rows/s`, `write=60.21 MB/s`, `size=6.74 bytes/row`, `compression=7.42x` + ## 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 writers for the remaining curated tables (`adj_factors`, `corporate_actions`, `fx_1d`, `events`, `shorts`) and `qmPrices` OHLC cross-check +- Zstd Parquet writers for the remaining curated tables (`adj_factors`, `corporate_actions`, `fx_1d`, `events`) and `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 4ab31613..6396586a 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -22,8 +22,15 @@ use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar}; use crate::parquet_bars::{ write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError, }; +use crate::parquet_shorts::{ + write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, +}; use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; -use crate::shorts::{build_shorts, epoch_days_to_ymd, CeoShortReport, ShortsError, ShortsStats}; +use crate::shorts::{ + add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, CeoShortReport, + ShortsError, ShortsStats, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, + SHORTS_LAG_BUSINESS_DAYS, SHORTS_SOURCE_CEO, +}; use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable}; pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; @@ -37,11 +44,14 @@ pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000; pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000; pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000; pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84; +pub const DEFAULT_PARQUET_SHORTS_BENCH_ROWS: usize = 1_000_000; +pub const PARQUET_SHORTS_RAW_ROW_BYTES: usize = 50; 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; const SHORTS_BENCH_KEY_COUNT: usize = 12_500; const PARQUET_BARS_BENCH_BASE_LISTINGS: usize = 2_000; +const PARQUET_SHORTS_BENCH_BASE_LISTINGS: usize = 12_500; const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; @@ -52,6 +62,7 @@ const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500; const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500; const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00; const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45; +const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; 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). @@ -1636,31 +1647,39 @@ struct BenchTempDir { } impl BenchTempDir { - fn new_in(base: &Path) -> Result { + fn new_in_with_prefix(base: &Path, prefix: &str) -> Result { let pid = std::process::id(); for _ in 0..1024 { let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let path = base.join(format!("curate-etl-bench-pq-bars-{pid}-{seq}")); + let path = base.join(format!("{prefix}-{pid}-{seq}")); match fs::create_dir(&path) { Ok(()) => return Ok(Self { path }), Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ParquetBarsError::Io { path, source }); - } + Err(source) => return Err((path, source)), } } - Err(ParquetBarsError::Io { - path: base.to_path_buf(), - source: io::Error::new( + Err(( + base.to_path_buf(), + io::Error::new( io::ErrorKind::AlreadyExists, "exhausted unique benchmark temp directory names", ), - }) + )) + } + + fn new_in(base: &Path) -> Result { + Self::new_in_with_prefix(base, "curate-etl-bench-pq-bars") + .map_err(|(path, source)| ParquetBarsError::Io { path, source }) } fn new() -> Result { Self::new_in(&std::env::temp_dir()) } + + fn new_shorts() -> Result { + Self::new_in_with_prefix(&std::env::temp_dir(), "curate-etl-bench-pq-shorts") + .map_err(|(path, source)| ParquetShortsError::Io { path, source }) + } } impl Drop for BenchTempDir { @@ -1956,6 +1975,289 @@ pub fn run_parquet_bars_benchmark(rows: usize) -> Result Vec<(i32, i64)> { + semi_monthly_report_dates() + .into_iter() + .map(|report_date| { + let known_day = add_canadian_business_days(report_date, SHORTS_LAG_BUSINESS_DAYS) + .expect("semi-monthly date within calendar range"); + let known_at = et_to_utc_micros( + known_day, + SHORTS_DISSEMINATION_HOUR_ET, + SHORTS_DISSEMINATION_MINUTE_ET, + 0, + ) + .expect("17:00 ET valid"); + (report_date, known_at) + }) + .collect() +} + +struct ParquetShortsBenchIter { + dates: Vec<(i32, i64)>, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_date_idx: usize, + cur_listing_rows: usize, + cur_shares: f64, + rng: SplitMix64, +} + +impl ParquetShortsBenchIter { + fn new(rows: usize, dates: Vec<(i32, i64)>) -> Self { + let min_listings = if rows == 0 { + PARQUET_SHORTS_BENCH_BASE_LISTINGS + } else { + rows.div_ceil(dates.len()) + .max(PARQUET_SHORTS_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 { + dates, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_date_idx: 0, + cur_listing_rows: 0, + cur_shares: 10_000.0, + rng: SplitMix64::new(PARQUET_SHORTS_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_date_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + self.cur_shares = ((self.rng.next_u64() % 2_000_000) + 100) as f64; + } +} + +impl Iterator for ParquetShortsBenchIter { + type Item = ShortsParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_date_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 + 1) as i32; + let w = self.dates.len(); + let n = self.cur_listing_rows; + let date_pos = if n == 1 { + (self.cur_listing.wrapping_mul(131)) % w + } else { + (self.cur_date_idx * w) / n + }; + let (report_date, known_at_micros) = self.dates[date_pos]; + self.cur_date_idx += 1; + + let r1 = self.rng.next_u64(); + let r2 = self.rng.next_u64(); + let delta = ((r1 % 40_001) as f64) - 20_000.0; + let next_shares = (self.cur_shares + delta).max(0.0); + let net_change = if (r2 & 0xF) == 0 { + None + } else { + Some(next_shares - self.cur_shares) + }; + self.cur_shares = next_shares; + let pct_float = if ((r2 >> 4) & 0x3) == 0 { + None + } else { + Some(((r2 >> 8) % 2_500) as f64 * 0.01) + }; + + Some(ShortsParquetRow { + listing_id, + report_date, + known_at_micros, + shares_short: next_shares, + net_change, + pct_float, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + }) + } +} + +fn verify_parquet_shorts_row_count( + out_dir: &Path, + expected_rows: usize, +) -> Result { + if expected_rows == 0 { + return Ok(0); + } + let path = out_dir.join("shorts/part.parquet"); + let file = File::open(&path).map_err(|source| ParquetShortsError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| ParquetShortsError::Parquet { + path: path.clone(), + source, + })?; + let read_back_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetShortsError::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(ParquetShortsError::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_shorts_benchmark_tracked( + rows: usize, +) -> Result<(ParquetShortsBenchReport, PathBuf), ParquetShortsError> { + let temp = BenchTempDir::new_shorts()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_shorts_dataset( + &temp.path, + std::iter::empty::(), + ShortsWriteOptions::default(), + )?; + let read_back_rows = verify_parquet_shorts_row_count(&temp.path, 0)?; + let report = ParquetShortsBenchReport { + 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_SHORTS_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 dates = semi_monthly_report_dates_with_known_at(); + let iter = ParquetShortsBenchIter::new(rows, dates); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_shorts_dataset(&temp.path, iter, ShortsWriteOptions::default())?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetShortsError::Parquet { + path: temp.path.join("shorts/part.parquet"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = verify_parquet_shorts_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_SHORTS_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(( + ParquetShortsBenchReport { + 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_SHORTS_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `shorts` writer benchmark for `rows` sorted short-interest +/// rows across `12,500` listings (scaling automatically for larger row counts) on semi-monthly +/// dates (`2017-04-15..=2026-04-30`), reads back the Parquet footer row count, and deletes its +/// temporary output directory. +pub fn run_parquet_shorts_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_parquet_shorts_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -2390,4 +2692,66 @@ mod tests { assert!(colliding.is_dir()); assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete"); } + + #[test] + fn parquet_shorts_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_shorts_benchmark_tracked(25_000).unwrap(); + let (b, dir_b) = run_parquet_shorts_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_SHORTS_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_SHORTS_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_shorts_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_shorts_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_SHORTS_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_shorts_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new_shorts().unwrap(); + let dates = semi_monthly_report_dates_with_known_at(); + let iter = ParquetShortsBenchIter::new(250, dates); + write_shorts_dataset(&temp.path, iter, ShortsWriteOptions::default()).unwrap(); + + let matched = verify_parquet_shorts_row_count(&temp.path, 250).unwrap(); + assert_eq!(matched, 250); + + let err = verify_parquet_shorts_row_count(&temp.path, 255).unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetShortsError::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 b03e400c..cc355b9f 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -6,8 +6,8 @@ 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_BARS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, - DEFAULT_SHORTS_BENCH_ROWS, + DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, + DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -24,6 +24,7 @@ pub enum CliAction { BenchEvents(usize), BenchProviderMapping(usize), BenchParquetBars(usize), + BenchParquetShorts(usize), } /// Formats full help text including binary name and version. @@ -42,7 +43,8 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ {name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\ - {name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})" + {name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})\n\ + {name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})" ) } @@ -60,7 +62,8 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ {name} bench-provider-mapping [lookups]\n\ - {name} bench-parquet-bars [rows]" + {name} bench-parquet-bars [rows]\n\ + {name} bench-parquet-shorts [rows]" ) } @@ -157,6 +160,18 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-parquet-bars", _, ..] => { Err("too many arguments for bench-parquet-bars".to_string()) } + ["bench-parquet-shorts"] => Ok(CliAction::BenchParquetShorts( + DEFAULT_PARQUET_SHORTS_BENCH_ROWS, + )), + ["bench-parquet-shorts", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetShorts(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-shorts", _, ..] => { + Err("too many arguments for bench-parquet-shorts".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -340,6 +355,24 @@ mod tests { assert!(parse_args(&to_args(&["bench-parquet-bars", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_parquet_shorts_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-shorts"])), + Ok(CliAction::BenchParquetShorts( + DEFAULT_PARQUET_SHORTS_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-shorts", "50000"])), + Ok(CliAction::BenchParquetShorts(50_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-shorts", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -352,6 +385,7 @@ mod tests { assert!(full.contains("bench-events")); assert!(full.contains("bench-provider-mapping")); assert!(full.contains("bench-parquet-bars")); + assert!(full.contains("bench-parquet-shorts")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); @@ -363,5 +397,6 @@ mod tests { assert!(short.contains("bench-events")); assert!(short.contains("bench-provider-mapping")); assert!(short.contains("bench-parquet-bars")); + assert!(short.contains("bench-parquet-shorts")); } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 6efd8878..5c94aa02 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -8,6 +8,8 @@ pub mod corporate_actions; pub mod events; pub mod fx; pub mod parquet_bars; +mod parquet_publish; +pub mod parquet_shorts; pub mod provider_mapping; pub mod shorts; pub mod split; @@ -42,6 +44,10 @@ pub use parquet_bars::{ Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, }; +pub use parquet_shorts::{ + shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, + ShortsWriteOptions, ShortsWriteStats, +}; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 3441e023..7bc4064a 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -5,8 +5,8 @@ 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_bars_benchmark, run_provider_mapping_benchmark, - run_shorts_benchmark, run_split_benchmark, + run_fx_benchmark, run_parquet_bars_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}; @@ -325,6 +325,36 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchParquetShorts(rows)) => { + let report = match run_parquet_shorts_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet shorts benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-shorts"); + 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_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 16c8833e..5367748e 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -18,44 +18,37 @@ use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; -use std::collections::{BTreeMap, HashMap}; +use std::collections::BTreeMap; use std::error::Error; use std::fmt; -use std::fs::{self, File, OpenOptions}; +use std::fs::{self, File}; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::thread; -use std::time::{Duration, Instant}; +use std::sync::Arc; +use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; -use parquet::column::writer::ColumnWriter; use parquet::data_type::ByteArray; use parquet::errors::ParquetError; use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; use parquet::file::writer::SerializedFileWriter; use parquet::schema::types::{ColumnPath, Type, TypePtr}; +use crate::parquet_publish::{ + cleanup_owned_files, create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, + next_run_id, rollback_published, write_f64_col, write_i32_col, write_i64_col, + write_interned_str_col, DatasetFileLock, PublishIoError, PublishedPartition, 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; -/// Default maximum number of rows buffered per Parquet row group. -pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000; - -/// Default Zstd compression level for `bars_1d` Parquet files. -pub const DEFAULT_ZSTD_LEVEL: i32 = 3; - /// Minimum allowed calendar year for `session_date` partitioning. pub const MIN_PARQUET_YEAR: i32 = 1900; /// Maximum allowed calendar year for `session_date` partitioning. pub const MAX_PARQUET_YEAR: i32 = 2200; -const STRING_WRITE_BATCH_ROWS: usize = 4_096; -const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; -const LINEAR_INTERN_LIMIT: usize = 8; -const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30); - /// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. #[derive(Debug, Clone, PartialEq)] pub struct Bars1dParquetRow { @@ -99,34 +92,6 @@ pub struct Bars1dWriteStats { pub rows_by_year: BTreeMap, } -/// Single failure encountered while rolling back a partial publication. -#[derive(Debug)] -pub struct RollbackFailure { - pub final_path: PathBuf, - pub backup_path: Option, - pub source: io::Error, -} - -impl fmt::Display for RollbackFailure { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match &self.backup_path { - Some(bak) => write!( - f, - "partition '{}' (backup '{}'): {}", - self.final_path.display(), - bak.display(), - self.source - ), - None => write!( - f, - "partition '{}': {}", - self.final_path.display(), - self.source - ), - } - } -} - /// Typed error returned by [`write_bars_1d_dataset`]. #[derive(Debug)] pub enum ParquetBarsError { @@ -242,6 +207,15 @@ impl Error for ParquetBarsError { } } +impl From for ParquetBarsError { + 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 12-column Parquet schema for `bars_1d` per `design/DATA-CONTRACTS.md`. pub fn bars_1d_parquet_schema() -> Result { let fields: Vec = vec![ @@ -330,54 +304,6 @@ fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { ) } -#[derive(Default)] -struct StringInterner { - values: Vec, - index: HashMap, -} - -impl StringInterner { - fn intern(&mut self, s: &str) -> u32 { - if self.values.len() <= LINEAR_INTERN_LIMIT { - let bytes = s.as_bytes(); - for (idx, existing) in self.values.iter().enumerate() { - if existing.data() == bytes { - return idx as u32; - } - } - let id = self.values.len() as u32; - self.values.push(ByteArray::from(s)); - if self.values.len() > LINEAR_INTERN_LIMIT { - self.index.reserve(self.values.len()); - for (i, val) in self.values.iter().enumerate() { - if let Ok(text) = std::str::from_utf8(val.data()) { - self.index.insert(text.to_owned(), i as u32); - } - } - } - return id; - } - - if let Some(&id) = self.index.get(s) { - return id; - } - let id = self.values.len() as u32; - self.values.push(ByteArray::from(s)); - self.index.insert(s.to_owned(), id); - id - } - - #[inline] - fn get(&self, id: u32) -> &ByteArray { - &self.values[id as usize] - } - - fn clear(&mut self) { - self.values.clear(); - self.index.clear(); - } -} - #[derive(Default)] struct RowGroupBuffer { listing_id: Vec, @@ -447,177 +373,6 @@ impl RowGroupBuffer { } } -static DATASET_LOCKS: OnceLock>>>> = OnceLock::new(); -static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0); - -fn dataset_mutex(bars_dir: &Path) -> Arc> { - let key = fs::canonicalize(bars_dir).unwrap_or_else(|_| bars_dir.to_path_buf()); - let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new())); - let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner()); - map.entry(key) - .or_insert_with(|| Arc::new(Mutex::new(()))) - .clone() -} - -struct DatasetFileLock { - path: PathBuf, -} - -impl DatasetFileLock { - fn acquire_with_timeout(bars_dir: &Path, timeout: Duration) -> Result { - let lock_path = bars_dir.join(".write.lock"); - let start = Instant::now(); - let mut backoff_ms = 2u64; - loop { - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&lock_path) - { - Ok(mut file) => { - let _ = writeln!(file, "{}", std::process::id()); - let _ = file.sync_all(); - return Ok(Self { path: lock_path }); - } - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { - let elapsed = start.elapsed(); - if elapsed >= timeout { - return Err(ParquetBarsError::LockTimeout { - path: lock_path, - waited: elapsed, - }); - } - let remaining = timeout.saturating_sub(elapsed); - thread::sleep(Duration::from_millis(backoff_ms).min(remaining)); - backoff_ms = (backoff_ms * 2).min(25); - } - Err(source) => { - return Err(ParquetBarsError::Io { - path: lock_path, - source, - }); - } - } - } - } -} - -impl Drop for DatasetFileLock { - fn drop(&mut self) { - let _ = fs::remove_file(&self.path); - } -} - -fn next_run_id() -> String { - let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - format!("{}-{seq}", std::process::id()) -} - -fn create_exclusive_tmp_file( - year_dir: &Path, - run_id: &str, -) -> Result<(PathBuf, File), ParquetBarsError> { - for attempt in 0..1024u32 { - let file_name = if attempt == 0 { - format!("part.parquet.{run_id}.tmp") - } else { - format!("part.parquet.{run_id}.{attempt}.tmp") - }; - let tmp_path = year_dir.join(file_name); - match OpenOptions::new() - .write(true) - .create_new(true) - .open(&tmp_path) - { - Ok(file) => return Ok((tmp_path, file)), - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ParquetBarsError::Io { - path: tmp_path, - source, - }); - } - } - } - Err(ParquetBarsError::Io { - path: year_dir.join(format!("part.parquet.{run_id}.tmp")), - source: io::Error::new( - io::ErrorKind::AlreadyExists, - "exhausted unique staging file names", - ), - }) -} - -fn is_hard_link_unsupported(err: &io::Error) -> bool { - matches!( - err.kind(), - io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied - ) -} - -fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> { - let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?; - let copy_res = (|| -> io::Result<()> { - let mut src_file = File::open(src)?; - io::copy(&mut src_file, &mut dst_file)?; - dst_file.sync_all()?; - Ok(()) - })(); - if let Err(err) = copy_res { - drop(dst_file); - let _ = fs::remove_file(dst); - return Err(err); - } - Ok(()) -} - -/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk. -/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive -/// file copy so readers never observe a missing `part.parquet` before replacement. -fn create_backup_preserving_live( - final_path: &Path, - run_id: &str, -) -> Result { - let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); - for attempt in 0..1024u32 { - let file_name = if attempt == 0 { - format!("part.parquet.{run_id}.bak") - } else { - format!("part.parquet.{run_id}.{attempt}.bak") - }; - let bak_path = parent.join(file_name); - match fs::hard_link(final_path, &bak_path) { - Ok(()) => return Ok(bak_path), - Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(err) if is_hard_link_unsupported(&err) => { - match copy_to_exclusive_backup(final_path, &bak_path) { - Ok(()) => return Ok(bak_path), - Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue, - Err(source) => { - return Err(ParquetBarsError::Io { - path: bak_path, - source, - }); - } - } - } - Err(source) => { - return Err(ParquetBarsError::Io { - path: bak_path, - source, - }); - } - } - } - Err(ParquetBarsError::Io { - path: parent.join(format!("part.parquet.{run_id}.bak")), - source: io::Error::new( - io::ErrorKind::AlreadyExists, - "exhausted unique backup file names", - ), - }) -} - struct YearWriter { tmp_path: PathBuf, final_path: PathBuf, @@ -678,46 +433,46 @@ impl YearWriter { 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, &self.tmp_path)?; + write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; // 2. ts (INT64, REQUIRED) - write_i64_col(&mut rg_writer, &self.buf.ts_micros, &self.tmp_path)?; + write_i64_col(&mut rg_writer, &self.buf.ts_micros).map_err(map_pq)?; // 3. session_date (INT32, REQUIRED) - write_i32_col(&mut rg_writer, &self.buf.session_date, &self.tmp_path)?; + write_i32_col(&mut rg_writer, &self.buf.session_date).map_err(map_pq)?; // 4. open (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.open, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.open, None).map_err(map_pq)?; // 5. high (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.high, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.high, None).map_err(map_pq)?; // 6. low (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.low, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.low, None).map_err(map_pq)?; // 7. close (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.close, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.close, None).map_err(map_pq)?; // 8. volume (DOUBLE, REQUIRED) - write_f64_col(&mut rg_writer, &self.buf.volume, None, &self.tmp_path)?; + write_f64_col(&mut rg_writer, &self.buf.volume, None).map_err(map_pq)?; // 9. vwap (DOUBLE, OPTIONAL) write_f64_col( &mut rg_writer, &self.buf.vwap_values, Some(&self.buf.vwap_def_levels), - &self.tmp_path, - )?; + ) + .map_err(map_pq)?; // 10. currency (BYTE_ARRAY, REQUIRED) write_interned_str_col( &mut rg_writer, &self.buf.currency_ids, &self.buf.currency_interner, scratch, - &self.tmp_path, - )?; + ) + .map_err(map_pq)?; // 11. source (BYTE_ARRAY, REQUIRED) write_interned_str_col( &mut rg_writer, &self.buf.source_ids, &self.buf.source_interner, scratch, - &self.tmp_path, - )?; + ) + .map_err(map_pq)?; // 12. known_at (INT64, REQUIRED) - write_i64_col(&mut rg_writer, &self.buf.known_at_micros, &self.tmp_path)?; + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; rg_writer.close().map_err(map_pq)?; @@ -778,182 +533,6 @@ struct SyncedYearFile { bytes: u64, } -fn next_column<'a>( - rg_writer: &'a mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - path: &Path, -) -> Result, ParquetBarsError> { - match rg_writer.next_column() { - Ok(Some(col)) => Ok(col), - Ok(None) => Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("unexpected end of Parquet schema columns".to_string()), - }), - Err(source) => Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }), - } -} - -fn write_i32_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - values: &[i32], - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::Int32ColumnWriter(typed) => { - typed - .write_batch(values, None, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected INT32 column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn write_i64_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - values: &[i64], - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::Int64ColumnWriter(typed) => { - typed - .write_batch(values, None, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected INT64 column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn write_f64_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - values: &[f64], - def_levels: Option<&[i16]>, - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::DoubleColumnWriter(typed) => { - typed - .write_batch(values, def_levels, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected DOUBLE column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn write_interned_str_col( - rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, - ids: &[u32], - interner: &StringInterner, - scratch: &mut Vec, - path: &Path, -) -> Result<(), ParquetBarsError> { - let mut col = next_column(rg_writer, path)?; - match col.untyped() { - ColumnWriter::ByteArrayColumnWriter(typed) => { - for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) { - scratch.clear(); - for &id in chunk { - scratch.push(interner.get(id).clone()); - } - typed - .write_batch(scratch, None, None) - .map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - })?; - } - } - _ => { - return Err(ParquetBarsError::Parquet { - path: path.to_path_buf(), - source: ParquetError::General("expected BYTE_ARRAY column writer".to_string()), - }); - } - } - col.close().map_err(|source| ParquetBarsError::Parquet { - path: path.to_path_buf(), - source, - }) -} - -fn cleanup_owned_files(owned_paths: &[PathBuf]) { - for path in owned_paths { - let _ = fs::remove_file(path); - } -} - -struct PublishedPartition { - final_path: PathBuf, - backup_path: Option, -} - -fn rollback_published(published: &[PublishedPartition]) -> Vec { - let mut failures = Vec::new(); - for part in published.iter().rev() { - match &part.backup_path { - Some(bak) => { - if let Err(source) = fs::rename(bak, &part.final_path) { - failures.push(RollbackFailure { - final_path: part.final_path.clone(), - backup_path: Some(bak.clone()), - source, - }); - } - } - None => { - if let Err(source) = fs::remove_file(&part.final_path) { - failures.push(RollbackFailure { - final_path: part.final_path.clone(), - backup_path: None, - source, - }); - } - } - } - } - failures -} - fn finish_with_rollback( cause: ParquetBarsError, published: &[PublishedPartition], @@ -1159,7 +738,12 @@ where match create_backup_preserving_live(&file.final_path, &run_id) { Ok(bak) => Some(bak), Err(err) => { - return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths)); + return Err(finish_with_rollback( + err.into(), + &published, + None, + &owned_tmp_paths, + )); } } } @@ -1223,6 +807,8 @@ where #[cfg(test)] mod tests { use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + use std::sync::Mutex; + use std::thread; use parquet::basic::ConvertedType; use parquet::column::reader::ColumnReader; diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs new file mode 100644 index 00000000..6eaff1db --- /dev/null +++ b/tools/curate-etl/src/parquet_publish.rs @@ -0,0 +1,417 @@ +//! Shared internal helpers for streaming Zstd Parquet writers (`bars_1d`, `shorts`, ...). +//! +//! Covers per-dataset locking, exclusive staging/backup files, rollback accounting, +//! low-cardinality string interning, and typed Parquet column-chunk writes. + +use std::collections::HashMap; +use std::fmt; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::thread; +use std::time::{Duration, Instant}; + +use parquet::column::writer::ColumnWriter; +use parquet::data_type::ByteArray; +use parquet::errors::ParquetError; +use parquet::file::writer::{SerializedColumnWriter, SerializedRowGroupWriter}; + +/// Default maximum number of rows buffered per Parquet row group. +pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000; + +/// Default Zstd compression level for curated Parquet files. +pub const DEFAULT_ZSTD_LEVEL: i32 = 3; + +pub(crate) const STRING_WRITE_BATCH_ROWS: usize = 4_096; +pub(crate) const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; +const LINEAR_INTERN_LIMIT: usize = 8; +pub(crate) const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30); + +/// Single failure encountered while rolling back a partial publication. +#[derive(Debug)] +pub struct RollbackFailure { + pub final_path: PathBuf, + pub backup_path: Option, + pub source: io::Error, +} + +impl fmt::Display for RollbackFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.backup_path { + Some(bak) => write!( + f, + "partition '{}' (backup '{}'): {}", + self.final_path.display(), + bak.display(), + self.source + ), + None => write!( + f, + "partition '{}': {}", + self.final_path.display(), + self.source + ), + } + } +} + +/// Internal I/O or lock-acquisition error returned by publish helpers. +#[derive(Debug)] +pub(crate) enum PublishIoError { + LockTimeout { path: PathBuf, waited: Duration }, + Io { path: PathBuf, source: io::Error }, +} + +#[derive(Default)] +pub(crate) struct StringInterner { + values: Vec, + index: HashMap, +} + +impl StringInterner { + pub(crate) fn intern(&mut self, s: &str) -> u32 { + if self.values.len() <= LINEAR_INTERN_LIMIT { + let bytes = s.as_bytes(); + for (idx, existing) in self.values.iter().enumerate() { + if existing.data() == bytes { + return idx as u32; + } + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + if self.values.len() > LINEAR_INTERN_LIMIT { + self.index.reserve(self.values.len()); + for (i, val) in self.values.iter().enumerate() { + if let Ok(text) = std::str::from_utf8(val.data()) { + self.index.insert(text.to_owned(), i as u32); + } + } + } + return id; + } + + if let Some(&id) = self.index.get(s) { + return id; + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + self.index.insert(s.to_owned(), id); + id + } + + #[inline] + pub(crate) fn get(&self, id: u32) -> &ByteArray { + &self.values[id as usize] + } + + pub(crate) fn clear(&mut self) { + self.values.clear(); + self.index.clear(); + } +} + +static DATASET_LOCKS: OnceLock>>>> = OnceLock::new(); +static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn dataset_mutex(dataset_dir: &Path) -> Arc> { + let key = fs::canonicalize(dataset_dir).unwrap_or_else(|_| dataset_dir.to_path_buf()); + let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new())); + let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner()); + map.entry(key) + .or_insert_with(|| Arc::new(Mutex::new(()))) + .clone() +} + +pub(crate) struct DatasetFileLock { + path: PathBuf, +} + +impl DatasetFileLock { + pub(crate) fn acquire_with_timeout( + dataset_dir: &Path, + timeout: Duration, + ) -> Result { + let lock_path = dataset_dir.join(".write.lock"); + let start = Instant::now(); + let mut backoff_ms = 2u64; + loop { + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock_path) + { + Ok(mut file) => { + let _ = writeln!(file, "{}", std::process::id()); + let _ = file.sync_all(); + return Ok(Self { path: lock_path }); + } + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(PublishIoError::LockTimeout { + path: lock_path, + waited: elapsed, + }); + } + let remaining = timeout.saturating_sub(elapsed); + thread::sleep(Duration::from_millis(backoff_ms).min(remaining)); + backoff_ms = (backoff_ms * 2).min(25); + } + Err(source) => { + return Err(PublishIoError::Io { + path: lock_path, + source, + }); + } + } + } + } +} + +impl Drop for DatasetFileLock { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +pub(crate) fn next_run_id() -> String { + let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + format!("{}-{seq}", std::process::id()) +} + +pub(crate) fn create_exclusive_tmp_file( + dir: &Path, + run_id: &str, +) -> Result<(PathBuf, File), PublishIoError> { + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.tmp") + } else { + format!("part.parquet.{run_id}.{attempt}.tmp") + }; + let tmp_path = dir.join(file_name); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + { + Ok(file) => return Ok((tmp_path, file)), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(PublishIoError::Io { + path: tmp_path, + source, + }); + } + } + } + Err(PublishIoError::Io { + path: dir.join(format!("part.parquet.{run_id}.tmp")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique staging file names", + ), + }) +} + +fn is_hard_link_unsupported(err: &io::Error) -> bool { + matches!( + err.kind(), + io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied + ) +} + +fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> { + let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?; + let copy_res = (|| -> io::Result<()> { + let mut src_file = File::open(src)?; + io::copy(&mut src_file, &mut dst_file)?; + dst_file.sync_all()?; + Ok(()) + })(); + if let Err(err) = copy_res { + drop(dst_file); + let _ = fs::remove_file(dst); + return Err(err); + } + Ok(()) +} + +/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk. +/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive +/// file copy so readers never observe a missing `part.parquet` before replacement. +pub(crate) fn create_backup_preserving_live( + final_path: &Path, + run_id: &str, +) -> Result { + let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.bak") + } else { + format!("part.parquet.{run_id}.{attempt}.bak") + }; + let bak_path = parent.join(file_name); + match fs::hard_link(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(err) if is_hard_link_unsupported(&err) => { + match copy_to_exclusive_backup(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(PublishIoError::Io { + path: bak_path, + source, + }); + } + } + } + Err(source) => { + return Err(PublishIoError::Io { + path: bak_path, + source, + }); + } + } + } + Err(PublishIoError::Io { + path: parent.join(format!("part.parquet.{run_id}.bak")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique backup file names", + ), + }) +} + +pub(crate) fn cleanup_owned_files(owned_paths: &[PathBuf]) { + for path in owned_paths { + let _ = fs::remove_file(path); + } +} + +pub(crate) struct PublishedPartition { + pub(crate) final_path: PathBuf, + pub(crate) backup_path: Option, +} + +pub(crate) fn rollback_published(published: &[PublishedPartition]) -> Vec { + let mut failures = Vec::new(); + for part in published.iter().rev() { + match &part.backup_path { + Some(bak) => { + if let Err(source) = fs::rename(bak, &part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: Some(bak.clone()), + source, + }); + } + } + None => { + if let Err(source) = fs::remove_file(&part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: None, + source, + }); + } + } + } + } + failures +} + +fn next_column<'a>( + rg_writer: &'a mut SerializedRowGroupWriter<'_, BufWriter>, +) -> Result, ParquetError> { + match rg_writer.next_column()? { + Some(col) => Ok(col), + None => Err(ParquetError::General( + "unexpected end of Parquet schema columns".to_string(), + )), + } +} + +pub(crate) fn write_i32_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[i32], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::Int32ColumnWriter(typed) => { + typed.write_batch(values, None, 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], +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::Int64ColumnWriter(typed) => { + typed.write_batch(values, None, None)?; + } + _ => { + return Err(ParquetError::General( + "expected INT64 column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_f64_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[f64], + def_levels: Option<&[i16]>, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::DoubleColumnWriter(typed) => { + typed.write_batch(values, def_levels, None)?; + } + _ => { + return Err(ParquetError::General( + "expected DOUBLE column writer".to_string(), + )); + } + } + col.close() +} + +pub(crate) fn write_interned_str_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + ids: &[u32], + interner: &StringInterner, + scratch: &mut Vec, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::ByteArrayColumnWriter(typed) => { + for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) { + scratch.clear(); + for &id in chunk { + scratch.push(interner.get(id).clone()); + } + typed.write_batch(scratch, None, None)?; + } + } + _ => { + return Err(ParquetError::General( + "expected BYTE_ARRAY column writer".to_string(), + )); + } + } + col.close() +} diff --git a/tools/curate-etl/src/parquet_shorts.rs b/tools/curate-etl/src/parquet_shorts.rs new file mode 100644 index 00000000..4ab7857b --- /dev/null +++ b/tools/curate-etl/src/parquet_shorts.rs @@ -0,0 +1,1187 @@ +//! Streaming, atomic Zstd Parquet writer for `shorts`. +//! +//! Writes `/shorts/part.parquet` matching the 7-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `report_date` (`INT32`, `REQUIRED`, `DATE`) +//! 3. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 4. `shares_short` (`DOUBLE`, `REQUIRED`) +//! 5. `net_change` (`DOUBLE`, `OPTIONAL`) +//! 6. `pct_float` (`DOUBLE`, `OPTIONAL`) +//! 7. `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::parquet_publish::{ + cleanup_owned_files, create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, + next_run_id, write_f64_col, write_i32_col, write_i64_col, write_interned_str_col, + DatasetFileLock, PublishIoError, 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::ShortRow; + +const MICROS_PER_DAY: i128 = 86_400_000_000; + +/// Single `shorts` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct ShortsParquetRow { + pub listing_id: i32, + pub report_date: i32, + pub known_at_micros: i64, + pub shares_short: f64, + pub net_change: Option, + pub pct_float: Option, + pub source: Cow<'static, str>, +} + +impl From<&ShortRow> for ShortsParquetRow { + fn from(row: &ShortRow) -> Self { + Self { + listing_id: row.key, + report_date: row.report_date, + known_at_micros: row.known_at_utc_micros, + shares_short: row.shares_short, + net_change: row.net_change, + pct_float: row.pct_float, + source: Cow::Borrowed(row.source), + } + } +} + +impl From> for ShortsParquetRow { + fn from(row: ShortRow) -> Self { + Self::from(&row) + } +} + +/// Configuration for [`write_shorts_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ShortsWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for ShortsWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_shorts_dataset`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ShortsWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, +} + +/// Typed error returned by [`write_shorts_dataset`]. +#[derive(Debug)] +pub enum ParquetShortsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_report_date: i32, + listing_id: i32, + report_date: i32, + }, + DuplicateKey { + listing_id: i32, + report_date: i32, + }, + InvalidSharesShort { + listing_id: i32, + report_date: i32, + value: f64, + }, + InvalidNetChange { + listing_id: i32, + report_date: i32, + value: f64, + }, + InvalidPctFloat { + listing_id: i32, + report_date: i32, + value: f64, + }, + KnownAtNotAfterReportDate { + listing_id: i32, + report_date: i32, + known_at_micros: i64, + }, + EmptySource { + listing_id: i32, + report_date: i32, + }, + 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 ParquetShortsError { + 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_report_date, + listing_id, + report_date, + } => write!( + f, + "unsorted input: ({listing_id}, {report_date}) follows ({prev_listing_id}, {prev_report_date})" + ), + Self::DuplicateKey { + listing_id, + report_date, + } => write!( + f, + "duplicate (listing_id, report_date) key: ({listing_id}, {report_date})" + ), + Self::InvalidSharesShort { + listing_id, + report_date, + value, + } => write!( + f, + "invalid shares_short {value} for ({listing_id}, {report_date}): must be finite and >= 0" + ), + Self::InvalidNetChange { + listing_id, + report_date, + value, + } => write!( + f, + "invalid net_change {value} for ({listing_id}, {report_date}): must be finite when present" + ), + Self::InvalidPctFloat { + listing_id, + report_date, + value, + } => write!( + f, + "invalid pct_float {value} for ({listing_id}, {report_date}): must be finite when present" + ), + Self::KnownAtNotAfterReportDate { + listing_id, + report_date, + known_at_micros, + } => write!( + f, + "known_at {known_at_micros} is not strictly after report_date {report_date} 00:00 UTC for listing_id {listing_id}" + ), + Self::EmptySource { + listing_id, + report_date, + } => write!( + f, + "empty source for ({listing_id}, {report_date}): must be non-empty" + ), + 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 ParquetShortsError { + 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 ParquetShortsError { + 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 7-column Parquet schema for `shorts` per `design/DATA-CONTRACTS.md`. +pub fn shorts_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("report_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("shares_short", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("net_change", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("pct_float", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("shorts") + .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("source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[inline] +fn validate_row(row: &ShortsParquetRow) -> Result<(), ParquetShortsError> { + if !row.shares_short.is_finite() || row.shares_short < 0.0 { + return Err(ParquetShortsError::InvalidSharesShort { + listing_id: row.listing_id, + report_date: row.report_date, + value: row.shares_short, + }); + } + if let Some(value) = row.net_change { + if !value.is_finite() { + return Err(ParquetShortsError::InvalidNetChange { + listing_id: row.listing_id, + report_date: row.report_date, + value, + }); + } + } + if let Some(value) = row.pct_float { + if !value.is_finite() { + return Err(ParquetShortsError::InvalidPctFloat { + listing_id: row.listing_id, + report_date: row.report_date, + value, + }); + } + } + let report_midnight_micros = i128::from(row.report_date) * MICROS_PER_DAY; + if i128::from(row.known_at_micros) <= report_midnight_micros { + return Err(ParquetShortsError::KnownAtNotAfterReportDate { + listing_id: row.listing_id, + report_date: row.report_date, + known_at_micros: row.known_at_micros, + }); + } + if row.source.trim().is_empty() { + return Err(ParquetShortsError::EmptySource { + listing_id: row.listing_id, + report_date: row.report_date, + }); + } + Ok(()) +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + report_date: Vec, + known_at_micros: Vec, + shares_short: Vec, + net_change_values: Vec, + net_change_def_levels: Vec, + pct_float_values: Vec, + pct_float_def_levels: Vec, + source_ids: Vec, + source_interner: StringInterner, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &ShortsParquetRow) { + self.listing_id.push(row.listing_id); + self.report_date.push(row.report_date); + self.known_at_micros.push(row.known_at_micros); + self.shares_short.push(row.shares_short); + match row.net_change { + Some(v) => { + self.net_change_values.push(v); + self.net_change_def_levels.push(1); + } + None => { + self.net_change_def_levels.push(0); + } + } + match row.pct_float { + Some(v) => { + self.pct_float_values.push(v); + self.pct_float_def_levels.push(1); + } + None => { + self.pct_float_def_levels.push(0); + } + } + let source_id = self.source_interner.intern(row.source.as_ref()); + self.source_ids.push(source_id); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.report_date.clear(); + self.known_at_micros.clear(); + self.shares_short.clear(); + self.net_change_values.clear(); + self.net_change_def_levels.clear(); + self.pct_float_values.clear(); + self.pct_float_def_levels.clear(); + self.source_ids.clear(); + self.source_interner.clear(); + } +} + +struct ShortsFileWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl ShortsFileWriter { + fn open( + shorts_dir: &Path, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + owned_tmp_paths: &mut Vec, + ) -> Result { + let (tmp_path, file) = create_exclusive_tmp_file(shorts_dir, run_id)?; + owned_tmp_paths.push(tmp_path.clone()); + let final_path = shorts_dir.join("part.parquet"); + + let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); + let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( + |source| ParquetShortsError::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<(), ParquetShortsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetShortsError::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. report_date (INT32, REQUIRED, DATE) + write_i32_col(&mut rg_writer, &self.buf.report_date).map_err(map_pq)?; + // 3. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?; + // 4. shares_short (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.shares_short, None).map_err(map_pq)?; + // 5. net_change (DOUBLE, OPTIONAL) + write_f64_col( + &mut rg_writer, + &self.buf.net_change_values, + Some(&self.buf.net_change_def_levels), + ) + .map_err(map_pq)?; + // 6. pct_float (DOUBLE, OPTIONAL) + write_f64_col( + &mut rg_writer, + &self.buf.pct_float_values, + Some(&self.buf.pct_float_def_levels), + ) + .map_err(map_pq)?; + // 7. source (BYTE_ARRAY, REQUIRED, STRING) + write_interned_str_col( + &mut rg_writer, + &self.buf.source_ids, + &self.buf.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| ParquetShortsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetShortsError::Io { + path: self.tmp_path.clone(), + source, + })? + .len(); + drop(file); + + Ok(SyncedShortsFile { + tmp_path: self.tmp_path, + final_path: self.final_path, + rows_written: self.rows_written, + row_groups_written: self.row_groups_written, + bytes, + }) + } +} + +struct SyncedShortsFile { + tmp_path: PathBuf, + final_path: PathBuf, + rows_written: usize, + row_groups_written: usize, + bytes: u64, +} + +/// Streams strictly ascending `(listing_id, report_date)` rows into a single Zstd Parquet file +/// at `/shorts/part.parquet`. +/// +/// # Empty Input +/// Empty input returns `Ok(ShortsWriteStats::default())` without creating `/shorts` +/// and without modifying or removing any pre-existing `part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/shorts` 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 [`ParquetShortsError::RollbackFailed`]), and +/// only staging files owned by this run are unlinked. +pub fn write_shorts_dataset( + out_dir: P, + rows: I, + options: ShortsWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_shorts_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _| {}, + ) +} + +fn write_shorts_dataset_with_hooks( + out_dir: P, + rows: I, + options: ShortsWriteOptions, + lock_timeout: Duration, + mut on_after_backup: F, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, + F: FnMut(&Path, Option<&Path>), +{ + if options.row_group_rows == 0 { + return Err(ParquetShortsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetShortsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(ShortsWriteStats::default()); + }; + validate_row(first_item.borrow())?; + + let out_dir = out_dir.as_ref(); + let shorts_dir = out_dir.join("shorts"); + let schema = shorts_parquet_schema().map_err(|source| ParquetShortsError::Parquet { + path: shorts_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&shorts_dir).map_err(|source| ParquetShortsError::Io { + path: shorts_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(&shorts_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&shorts_dir, lock_timeout)?; + + let run_id = next_run_id(); + let mut owned_tmp_paths: Vec = Vec::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let mut file_writer = Some(ShortsFileWriter::open( + &shorts_dir, + &run_id, + &schema, + &props, + &mut owned_tmp_paths, + )?); + + let write_result: Result = (|| { + let mut prev_key: Option<(i32, i32)> = None; + let writer = file_writer.as_mut().expect("writer initialized"); + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + if let Some((prev_listing_id, prev_report_date)) = prev_key { + match (row.listing_id, row.report_date).cmp(&(prev_listing_id, prev_report_date)) { + Ordering::Equal => { + return Err(ParquetShortsError::DuplicateKey { + listing_id: row.listing_id, + report_date: row.report_date, + }); + } + Ordering::Less => { + return Err(ParquetShortsError::UnsortedInput { + prev_listing_id, + prev_report_date, + listing_id: row.listing_id, + report_date: row.report_date, + }); + } + Ordering::Greater => {} + } + } + validate_row(row)?; + prev_key = Some((row.listing_id, row.report_date)); + + 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 synced = match write_result { + Ok(file) => file, + Err(err) => { + drop(file_writer); + cleanup_owned_files(&owned_tmp_paths); + return Err(err); + } + }; + + let backup_path = match fs::symlink_metadata(&synced.final_path) { + Ok(meta) if !meta.is_dir() => { + match create_backup_preserving_live(&synced.final_path, &run_id) { + Ok(bak) => Some(bak), + Err(err) => { + cleanup_owned_files(&owned_tmp_paths); + return Err(err.into()); + } + } + } + // 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) => { + cleanup_owned_files(&owned_tmp_paths); + return Err(ParquetShortsError::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 and clean up our staging file. + 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, + }) + }); + cleanup_owned_files(&owned_tmp_paths); + let cause = ParquetShortsError::Io { + path: synced.final_path, + source, + }; + return match backup_remove_failure { + Some(failure) => Err(ParquetShortsError::RollbackFailed { + cause: Box::new(cause), + failures: vec![failure], + }), + None => Err(cause), + }; + } + + if let Some(bak) = backup_path { + let _ = fs::remove_file(bak); + } + + Ok(ShortsWriteStats { + 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::shorts::{build_shorts, CeoShortReport, SHORTS_SOURCE_CEO}; + 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-shorts-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 make_row( + listing_id: i32, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, + ) -> ShortsParquetRow { + let known_at_micros = i64::from(report_date + 6) * 86_400_000_000 + 21 * 3_600_000_000; + ShortsParquetRow { + listing_id, + report_date, + known_at_micros, + shares_short, + net_change, + pct_float, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + } + } + + 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_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_f64_req = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, None, None, &mut vals) + .expect("read f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + vals + }; + let read_f64_opt = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(num_rows); + let mut defs = Vec::with_capacity(num_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::DoubleColumnReader(mut r) => { + let (read, _, _) = r + .read_records(num_rows, Some(&mut defs), None, &mut vals) + .expect("read optional f64"); + assert_eq!(read, num_rows); + } + _ => panic!("expected DOUBLE column at index {col_idx}"), + } + assert_eq!(defs.len(), num_rows); + let mut iter = vals.into_iter(); + defs.into_iter() + .map(|d| if d == 1 { Some(iter.next().unwrap()) } else { None }) + .collect() + }; + let read_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(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned()) + .collect() + }; + + let listing_id = read_i32(0); + let report_date = read_i32(1); + let known_at_micros = read_i64(2); + let shares_short = read_f64_req(3); + let net_change = read_f64_opt(4); + let pct_float = read_f64_opt(5); + let source = read_str(6); + + for i in 0..num_rows { + out.push(ShortsParquetRow { + listing_id: listing_id[i], + report_date: report_date[i], + known_at_micros: known_at_micros[i], + shares_short: shares_short[i], + net_change: net_change[i], + pct_float: pct_float[i], + source: Cow::Owned(source[i].clone()), + }); + } + } + out + } + + pub(super) fn assert_row_bitwise_eq(actual: &ShortsParquetRow, expected: &ShortsParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.report_date, expected.report_date); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + assert_eq!(actual.shares_short.to_bits(), expected.shares_short.to_bits()); + assert_eq!( + actual.net_change.map(f64::to_bits), + expected.net_change.map(f64::to_bits) + ); + assert_eq!( + actual.pct_float.map(f64::to_bits), + expected.pct_float.map(f64::to_bits) + ); + assert_eq!(actual.source, expected.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() + ); + } + } + + #[test] + fn schema_matches_contract_names_types_nullability_and_order() { + let schema = shorts_parquet_schema().expect("build schema"); + assert_eq!(schema.name(), "shorts"); + let fields = schema.get_fields(); + assert_eq!(fields.len(), 7); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 7] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "report_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "shares_short", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "net_change", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "pct_float", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "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 build_shorts_round_trip_bitwise_and_zstd_on_every_column_chunk() { + let tmp = TempDirGuard::new("round-trip"); + let built = build_shorts(vec![ + CeoShortReport { + key: 101_i32, + report_date: day(2024, 3, 15), + shares_short: 125_000.0, + net_change: Some(-4_500.0), + pct_float: Some(3.25), + }, + CeoShortReport { + key: 101_i32, + report_date: day(2024, 3, 31), + shares_short: 0.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: 202_i32, + report_date: day(2023, 12, 29), + shares_short: 88_500.5, + net_change: Some(1_250.25), + pct_float: None, + }, + ]) + .expect("build_shorts"); + + let rows: Vec = built.rows.iter().map(ShortsParquetRow::from).collect(); + let stats = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap(); + + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 1); + assert!(stats.bytes_written > 0); + + let path = tmp.path().join("shorts/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(), 3); + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} expected ZSTD, got {:?}", + col.column_path(), + col.compression() + ); + } + } + + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("shorts")); + } + + #[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_shorts_dataset( + &fresh, + std::iter::empty::(), + ShortsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats, ShortsWriteStats::default()); + assert!(!fresh.exists(), "empty input must not create out_dir"); + + let seeded = tmp.path().join("seeded"); + let seed_rows = vec![make_row(1, day(2024, 3, 15), 1_000.0, Some(50.0), Some(1.5))]; + write_shorts_dataset(&seeded, &seed_rows, ShortsWriteOptions::default()).unwrap(); + let part = seeded.join("shorts/part.parquet"); + let before = fs::read(&part).unwrap(); + + let empty_stats = write_shorts_dataset( + &seeded, + std::iter::empty::(), + ShortsWriteOptions::default(), + ) + .unwrap(); + assert_eq!(empty_stats, ShortsWriteStats::default()); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&seeded.join("shorts")); + } + + #[test] + fn determinism_identical_rows_produce_byte_identical_files() { + let tmp = TempDirGuard::new("determinism"); + let rows = vec![ + make_row(1, day(2024, 1, 15), 10_000.0, Some(250.0), Some(0.75)), + make_row(1, day(2024, 1, 31), 9_500.0, Some(-500.0), None), + make_row(2, day(2024, 2, 15), 0.0, None, Some(0.0)), + ]; + + let out_a = tmp.path().join("a"); + let out_b = tmp.path().join("b"); + let opts = ShortsWriteOptions { + row_group_rows: 2, + ..ShortsWriteOptions::default() + }; + write_shorts_dataset(&out_a, &rows, opts).unwrap(); + write_shorts_dataset(&out_b, &rows, opts).unwrap(); + + let bytes_a = fs::read(out_a.join("shorts/part.parquet")).unwrap(); + let bytes_b = fs::read(out_b.join("shorts/part.parquet")).unwrap(); + assert_eq!(bytes_a, bytes_b); + } +} + +#[cfg(test)] +#[path = "parquet_shorts_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_shorts_tests.rs b/tools/curate-etl/src/parquet_shorts_tests.rs new file mode 100644 index 00000000..42ba7f10 --- /dev/null +++ b/tools/curate-etl/src/parquet_shorts_tests.rs @@ -0,0 +1,533 @@ +use std::borrow::Cow; +use std::error::Error as StdError; +use std::fs::{self, File}; +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, make_row, read_parquet_rows, + TempDirGuard, +}; +use super::{ + write_shorts_dataset, write_shorts_dataset_with_hooks, ParquetShortsError, ShortsParquetRow, + ShortsWriteOptions, +}; +use crate::shorts::SHORTS_SOURCE_CEO; + +fn seed_existing(out_dir: &std::path::Path) -> (std::path::PathBuf, Vec) { + let seed = vec![ + make_row(1, day(2024, 1, 15), 5_000.0, Some(100.0), Some(1.25)), + make_row(2, day(2024, 1, 31), 8_000.0, None, Some(2.5)), + ]; + write_shorts_dataset(out_dir, &seed, ShortsWriteOptions::default()).unwrap(); + let part = out_dir.join("shorts/part.parquet"); + let before = fs::read(&part).unwrap(); + (part, before) +} + +#[test] +fn single_row_and_row_group_boundary_counts_and_optional_patterns() { + let tmp = TempDirGuard::new("rg-boundaries"); + + // 1 row + let out_1 = tmp.path().join("one"); + let single = vec![make_row(7, day(2024, 2, 15), 42.0, None, None)]; + let stats_1 = write_shorts_dataset(&out_1, &single, ShortsWriteOptions::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("shorts/part.parquet")); + assert_eq!(actual_1.len(), 1); + assert_row_bitwise_eq(&actual_1[0], &single[0]); + + // Exactly row_group_rows (4 rows, row_group_rows = 4 => 1 row group) + let base = day(2024, 1, 1); + let rows_exact: Vec = (0..4_i32) + .map(|i| make_row(1, base + i * 15, f64::from(i) * 100.0, None, None)) + .collect(); + let out_exact = tmp.path().join("exact"); + let opts = ShortsWriteOptions { + row_group_rows: 4, + ..ShortsWriteOptions::default() + }; + let stats_exact = write_shorts_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("shorts/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]) + // Exercises all-None, all-Some, and mixed optional columns across row groups. + let rows_plus_one = vec![ + make_row(1, base, 10.0, None, None), + make_row(1, base + 15, 20.0, Some(10.0), Some(0.5)), + make_row(1, base + 30, 30.0, Some(-5.0), None), + make_row(1, base + 45, 40.0, None, Some(1.25)), + make_row(2, base, 50.0, Some(50.0), Some(2.0)), + ]; + let out_plus = tmp.path().join("plus-one"); + let stats_plus = write_shorts_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("shorts/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("shorts")); +} + +#[test] +fn source_column_uses_dictionary_encoding_and_zstd_levels_work() { + let tmp = TempDirGuard::new("dict-zstd"); + let base = day(2024, 1, 15); + let rows: Vec = (0..64_i32) + .map(|i| make_row(1 + i / 8, base + (i % 8) * 15, 1_000.0 + f64::from(i), Some(5.0), Some(1.0))) + .collect(); + + let out_ok = tmp.path().join("lvl-3"); + write_shorts_dataset(&out_ok, &rows, ShortsWriteOptions::default()).unwrap(); + let p = out_ok.join("shorts/part.parquet"); + let reader = SerializedFileReader::new(File::open(&p).unwrap()).unwrap(); + let source_col = reader.metadata().row_group(0).column(6); + assert!( + source_col.encodings().any(|e| { + matches!( + e, + Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY + ) + }), + "expected dictionary encoding on source column, got {:?}", + source_col.encodings().collect::>() + ); + + // Invalid Zstd level and invalid row_group_rows + let out_bad = tmp.path().join("bad-opts"); + assert!(matches!( + write_shorts_dataset( + &out_bad, + &rows, + ShortsWriteOptions { + row_group_rows: 0, + ..ShortsWriteOptions::default() + } + ), + Err(ParquetShortsError::InvalidRowGroupRows) + )); + assert!(matches!( + write_shorts_dataset( + &out_bad, + &rows, + ShortsWriteOptions { + zstd_level: 23, + ..ShortsWriteOptions::default() + } + ), + Err(ParquetShortsError::InvalidZstdLevel { level: 23 }) + )); + assert!(matches!( + write_shorts_dataset( + &out_bad, + &rows, + ShortsWriteOptions { + zstd_level: 99, + ..ShortsWriteOptions::default() + } + ), + Err(ParquetShortsError::InvalidZstdLevel { level: 99 }) + )); + assert!(!out_bad.exists(), "invalid options must not create out_dir"); +} + +#[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_row(10, day(2025, 4, 15), 99_999.0, Some(-123.5), Some(4.5)), + make_row(11, day(2025, 4, 30), 0.0, None, None), + ]; + let stats = write_shorts_dataset(tmp.path(), &replacement, ShortsWriteOptions::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("shorts")); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_preserve_existing_part_parquet() { + let tmp = TempDirGuard::new("invalid-inputs"); + let (part, before) = seed_existing(tmp.path()); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 31); + + // 1. Unsorted (listing_id goes backwards) + let unsorted_listing = vec![ + make_row(2, d1, 100.0, None, None), + make_row(1, d2, 200.0, None, None), + ]; + let err = write_shorts_dataset(tmp.path(), &unsorted_listing, ShortsWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::UnsortedInput { + prev_listing_id: 2, + prev_report_date, + listing_id: 1, + report_date, + } if prev_report_date == d1 && report_date == d2 + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // 2. Unsorted (report_date goes backwards for same listing) + let unsorted_date = vec![ + make_row(1, d2, 100.0, None, None), + make_row(1, d1, 200.0, None, None), + ]; + let err = + write_shorts_dataset(tmp.path(), &unsorted_date, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::UnsortedInput { + prev_listing_id: 1, + prev_report_date, + listing_id: 1, + report_date, + } if prev_report_date == d2 && report_date == d1 + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // 3. Duplicate (listing_id, report_date) + let duplicate = vec![ + make_row(1, d1, 100.0, None, None), + make_row(1, d1, 100.0, None, None), + ]; + let err = + write_shorts_dataset(tmp.path(), &duplicate, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + ParquetShortsError::DuplicateKey { + listing_id: 1, + report_date, + } if report_date == d1 + )); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + + // 4. Invalid shares_short: NaN, +inf, -inf, negative + for bad_shares in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.0001] { + let rows = vec![make_row(1, d1, bad_shares, None, None)]; + let err = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidSharesShort { + listing_id: 1, + report_date, + .. + } if report_date == d1 + ), + "expected InvalidSharesShort for {bad_shares}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 5. Invalid net_change: NaN, +inf, -inf + for bad_net in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let rows = vec![make_row(1, d1, 100.0, Some(bad_net), None)]; + let err = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidNetChange { + listing_id: 1, + report_date, + .. + } if report_date == d1 + ), + "expected InvalidNetChange for {bad_net}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 6. Invalid pct_float: NaN, +inf, -inf + for bad_pct in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let rows = vec![make_row(1, d1, 100.0, None, Some(bad_pct))]; + let err = + write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::InvalidPctFloat { + listing_id: 1, + report_date, + .. + } if report_date == d1 + ), + "expected InvalidPctFloat for {bad_pct}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 7. known_at not strictly after report_date 00:00 UTC (equal, before, and extreme report_date = i32::MAX) + let midnight = i64::from(d1) * 86_400_000_000; + for (report_date, known_at_micros) in [ + (d1, midnight), + (d1, midnight - 1), + (i32::MAX, i64::MAX), + ] { + let mut r = make_row(1, d1, 100.0, None, None); + r.report_date = report_date; + r.known_at_micros = known_at_micros; + let err = write_shorts_dataset(tmp.path(), &[r], ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::KnownAtNotAfterReportDate { + listing_id: 1, + report_date: rd, + known_at_micros: ka, + } if rd == report_date && ka == known_at_micros + ), + "expected KnownAtNotAfterReportDate for ({report_date}, {known_at_micros}), got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } + + // 8. Empty and whitespace-only source + for bad_source in ["", " ", "\t\n"] { + let mut r = make_row(1, d1, 100.0, None, None); + r.source = Cow::Owned(bad_source.to_string()); + let err = write_shorts_dataset(tmp.path(), &[r], ShortsWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetShortsError::EmptySource { + listing_id: 1, + report_date, + } if report_date == d1 + ), + "expected EmptySource for {bad_source:?}, got {err:?}" + ); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); + } +} + +#[test] +fn mid_stream_failure_after_flushed_row_groups_preserves_existing_part_parquet() { + let tmp = TempDirGuard::new("mid-stream-fail"); + let (part, before) = seed_existing(tmp.path()); + let base = day(2024, 1, 1); + + let mut rows = vec![ + make_row(1, base, 100.0, Some(1.0), Some(0.1)), + make_row(1, base + 15, 200.0, Some(2.0), Some(0.2)), + make_row(1, base + 30, 300.0, Some(3.0), Some(0.3)), + make_row(1, base + 45, 400.0, Some(4.0), Some(0.4)), + ]; + // 5th row fails after 2 row groups of size 2 have already been flushed to staging. + rows.push(make_row(1, base + 60, -1.0, None, None)); + + let err = write_shorts_dataset( + tmp.path(), + &rows, + ShortsWriteOptions { + row_group_rows: 2, + ..ShortsWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetShortsError::InvalidSharesShort { .. })); + assert_eq!(fs::read(&part).unwrap(), before); + assert_no_transient_files(&tmp.path().join("shorts")); +} + +#[test] +fn out_dir_or_shorts_occupied_by_regular_file_returns_io_error() { + let tmp = TempDirGuard::new("io-blocker"); + let rows = vec![make_row(1, day(2024, 3, 15), 100.0, None, None)]; + + let file_as_out = tmp.path().join("not-a-dir"); + fs::write(&file_as_out, b"sentinel").unwrap(); + let err = write_shorts_dataset(&file_as_out, &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetShortsError::Io { .. })); + assert!(StdError::source(&err).is_some()); + assert_eq!(fs::read(&file_as_out).unwrap(), b"sentinel"); + + let out_with_file_shorts = tmp.path().join("shorts-is-file"); + fs::create_dir_all(&out_with_file_shorts).unwrap(); + let shorts_file = out_with_file_shorts.join("shorts"); + fs::write(&shorts_file, b"file-not-dir").unwrap(); + let err2 = + write_shorts_dataset(&out_with_file_shorts, &rows, ShortsWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err2, ParquetShortsError::Io { .. })); + assert_eq!(fs::read(&shorts_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("shorts/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let rows = vec![make_row(9, day(2024, 6, 15), 500.0, None, None)]; + let err = write_shorts_dataset_with_hooks( + tmp.path(), + &rows, + ShortsWriteOptions::default(), + Duration::from_millis(30), + |_, _| {}, + ) + .unwrap_err(); + + assert!( + matches!(err, ParquetShortsError::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_row(5, day(2024, 9, 15), 777.0, Some(7.0), Some(0.7))]; + let observed_live = Arc::new(Mutex::new(false)); + let observed_clone = Arc::clone(&observed_live); + + write_shorts_dataset_with_hooks( + tmp.path(), + &replacement, + ShortsWriteOptions::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; + }, + ) + .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("shorts")); +} + +#[test] +fn rename_failure_over_directory_blocker_cleans_up_staging_and_unowned_tmp_is_preserved() { + let tmp = TempDirGuard::new("rename-blocker"); + let shorts_dir = tmp.path().join("shorts"); + let blocking_dir = shorts_dir.join("part.parquet"); + fs::create_dir_all(&blocking_dir).unwrap(); + + let unowned_tmp = shorts_dir.join("part.parquet.unowned-other-run.tmp"); + fs::write(&unowned_tmp, b"keep-me").unwrap(); + + let rows = vec![make_row(1, day(2024, 3, 15), 100.0, None, None)]; + let err = write_shorts_dataset(tmp.path(), &rows, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetShortsError::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" + ); + + // Only the unowned .tmp file and the blocking directory may remain. + let mut entries: Vec = fs::read_dir(&shorts_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 events = Arc::new(Mutex::new(Vec::<&'static str>::new())); + + let out_1 = Arc::clone(&out); + let events_1 = Arc::clone(&events); + let handle_1 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + events_1.lock().unwrap().push("t1_mid"); + thread::sleep(Duration::from_millis(30)); + } + make_row(1, day(2024, 1, 15) + i * 16, 100.0 + f64::from(i), None, None) + }); + write_shorts_dataset(out_1.as_path(), iter, ShortsWriteOptions::default()) + }); + + thread::sleep(Duration::from_millis(5)); + let out_2 = Arc::clone(&out); + let events_2 = Arc::clone(&events); + let handle_2 = thread::spawn(move || { + let iter = (0..2_i32).map(move |i| { + if i == 1 { + events_2.lock().unwrap().push("t2_mid"); + } + make_row(2, day(2024, 2, 15) + i * 14, 500.0 + f64::from(i), Some(10.0), None) + }); + write_shorts_dataset(out_2.as_path(), iter, ShortsWriteOptions::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("shorts/part.parquet")); + assert_eq!(got.len(), 2); + assert!( + got.iter().all(|r| r.listing_id == 1) || got.iter().all(|r| r.listing_id == 2), + "output must come entirely from one writer generation" + ); + assert!(got.iter().all(|r| r.source == SHORTS_SOURCE_CEO)); + assert_no_transient_files(&tmp.path().join("shorts")); +} diff --git a/tools/curate-etl/tests/parquet_shorts_contract.rs b/tools/curate-etl/tests/parquet_shorts_contract.rs new file mode 100644 index 00000000..904df543 --- /dev/null +++ b/tools/curate-etl/tests/parquet_shorts_contract.rs @@ -0,0 +1,543 @@ +//! Contract tests for the public `shorts` Parquet writer API (T-92 / M1.2j). +//! +//! Uses only the crate's public surface (`build_shorts`, `write_shorts_dataset`, +//! `shorts_parquet_schema`, the `curate-etl` binary) plus an independent Parquet column reader, +//! guarding the `design/DATA-CONTRACTS.md` §3A `shorts/part.parquet` schema, atomic single-file +//! publish semantics, validation errors, concurrency serialization, determinism, and the +//! `bench-parquet-shorts` CLI contract. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread; + +use curate_etl::{ + build_shorts, shorts_parquet_schema, write_shorts_dataset, ymd_to_epoch_days, CeoShortReport, + ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, SHORTS_SOURCE_CEO, +}; +use parquet::basic::{ + Compression, ConvertedType, Encoding, LogicalType, Repetition, TimeUnit, Type as PhysicalType, +}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-shorts-contract-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn part_path(out: &Path) -> PathBuf { + out.join("shorts/part.parquet") +} + +fn row( + listing_id: i32, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, +) -> ShortsParquetRow { + ShortsParquetRow { + listing_id, + report_date, + known_at_micros: i64::from(report_date + 6) * 86_400_000_000 + 21 * 3_600_000_000, + shares_short, + net_change, + pct_float, + source: Cow::Borrowed(SHORTS_SOURCE_CEO), + } +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int32ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT32"), + } + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int64ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT64"), + } + v + }; + let f64s = |c: ColumnReader| -> Vec> { + let mut v = Vec::new(); + let mut defs = Vec::new(); + match c { + ColumnReader::DoubleColumnReader(mut r) => { + assert_eq!( + r.read_records(n, Some(&mut defs), None, &mut v).unwrap().0, + n + ); + } + _ => panic!("expected DOUBLE"), + } + if defs.is_empty() { + return v.into_iter().map(Some).collect(); + } + let mut it = v.into_iter(); + defs.iter() + .map(|&d| if d == 1 { it.next() } else { None }) + .collect() + }; + let strs = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::ByteArrayColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected BYTE_ARRAY"), + } + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect() + }; + + let lid = i32s(col(0)); + let rd = i32s(col(1)); + let ka = i64s(col(2)); + let ss: Vec = f64s(col(3)) + .into_iter() + .map(|x| x.expect("required shares_short")) + .collect(); + let nc = f64s(col(4)); + let pf = f64s(col(5)); + let src = strs(col(6)); + + for i in 0..n { + out.push(ShortsParquetRow { + listing_id: lid[i], + report_date: rd[i], + known_at_micros: ka[i], + shares_short: ss[i], + net_change: nc[i], + pct_float: pf[i], + source: Cow::Owned(src[i].clone()), + }); + } + } + out +} + +fn assert_rows_bitwise(actual: &[ShortsParquetRow], expected: &[ShortsParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.report_date, e.report_date, "row {i} report_date"); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + assert_eq!( + a.shares_short.to_bits(), + e.shares_short.to_bits(), + "row {i} shares_short" + ); + assert_eq!( + a.net_change.map(f64::to_bits), + e.net_change.map(f64::to_bits), + "row {i} net_change" + ); + assert_eq!( + a.pct_float.map(f64::to_bits), + e.pct_float.map(f64::to_bits), + "row {i} pct_float" + ); + assert_eq!(a.source, e.source, "row {i} source"); + } +} + +fn list_files(dir: &Path) -> Vec { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.push(path.strip_prefix(root).unwrap().display().to_string()); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +#[test] +fn build_shorts_round_trip_matches_contract_schema_zstd_and_bitwise_values() { + let tmp = TempDir::new("contract"); + let built = build_shorts(vec![ + CeoShortReport { + key: 42_i32, + report_date: day(2024, 3, 28), // Good Friday rollover + shares_short: 250_000.0, + net_change: Some(12_500.0), + pct_float: Some(4.75), + }, + CeoShortReport { + key: 42_i32, + report_date: day(2024, 4, 15), + shares_short: 0.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: 7_i32, + report_date: day(2023, 12, 29), // Year-end rollover + shares_short: 15_300.25, + net_change: Some(-300.5), + pct_float: None, + }, + ]) + .expect("build_shorts"); + + let rows_ref: Vec = built.rows.iter().map(ShortsParquetRow::from).collect(); + let rows_owned: Vec = + built.rows.into_iter().map(ShortsParquetRow::from).collect(); + assert_rows_bitwise(&rows_ref, &rows_owned); + + let stats = write_shorts_dataset(&tmp.0, &rows_ref, ShortsWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 1); + + let path = part_path(&tmp.0); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let meta = reader.metadata(); + let file_schema = meta.file_metadata().schema(); + let public_schema = shorts_parquet_schema().unwrap(); + assert_eq!(file_schema, public_schema.as_ref()); + + let expected: [( + &str, + PhysicalType, + Repetition, + Option, + ConvertedType, + ); 7] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "report_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "shares_short", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "net_change", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "pct_float", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ]; + let fields = file_schema.get_fields(); + assert_eq!(fields.len(), expected.len()); + for (i, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + assert_eq!(fields[i].name(), name); + assert_eq!(fields[i].get_physical_type(), phys); + assert_eq!(fields[i].get_basic_info().repetition(), rep); + assert_eq!(fields[i].get_basic_info().logical_type_ref().cloned(), logical); + assert_eq!(fields[i].get_basic_info().converted_type(), converted); + } + + for rg in meta.row_groups() { + for c in rg.columns() { + assert!( + matches!(c.compression(), Compression::ZSTD(_)), + "{} not ZSTD", + c.column_path() + ); + } + assert!( + rg.column(6) + .encodings() + .any(|e| matches!(e, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)), + "source column must use dictionary encoding" + ); + } + + assert_rows_bitwise(&read_rows(&path), &rows_ref); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); +} + +#[test] +fn row_group_boundaries_overwrite_empty_and_byte_identical_rerun() { + let tmp = TempDir::new("edges"); + let base = day(2024, 1, 15); + let rows: Vec = (0..5_i32) + .map(|i| { + row( + 1 + i / 3, + base + (i % 3) * 15, + 1_000.0 * f64::from(i), + if i % 2 == 0 { None } else { Some(50.0) }, + if i % 3 == 0 { Some(1.5) } else { None }, + ) + }) + .collect(); + + // Exact row_group_rows == 4 -> 1 group; 5 rows -> 2 groups [4, 1] + let opts = ShortsWriteOptions { + row_group_rows: 4, + ..ShortsWriteOptions::default() + }; + let s_eq = write_shorts_dataset(&tmp.0, &rows[..4], opts).unwrap(); + assert_eq!(s_eq.row_groups_written, 1); + + // Overwrite with 5 rows + let s_plus = write_shorts_dataset(&tmp.0, &rows, opts).unwrap(); + assert_eq!(s_plus.rows_written, 5); + assert_eq!(s_plus.row_groups_written, 2); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0)), &rows); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); + + // Empty input does not destroy existing part.parquet + let bytes_before = fs::read(part_path(&tmp.0)).unwrap(); + let s_empty = + write_shorts_dataset(&tmp.0, std::iter::empty::(), opts).unwrap(); + assert_eq!(s_empty, ShortsWriteStats::default()); + assert_eq!(fs::read(part_path(&tmp.0)).unwrap(), bytes_before); + + // Determinism: second directory yields byte-identical file + let tmp2 = TempDir::new("edges-rerun"); + write_shorts_dataset(&tmp2.0, &rows, opts).unwrap(); + assert_eq!(fs::read(part_path(&tmp2.0)).unwrap(), bytes_before); +} + +#[test] +fn invalid_inputs_return_typed_errors_and_leave_existing_file_byte_identical() { + let tmp = TempDir::new("invalid"); + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 31); + let seed = vec![row(1, d1, 10_000.0, Some(200.0), Some(2.0))]; + write_shorts_dataset(&tmp.0, &seed, ShortsWriteOptions::default()).unwrap(); + let before = fs::read(part_path(&tmp.0)).unwrap(); + + let cases: Vec<(&str, Vec)> = vec![ + ( + "unsorted", + vec![row(1, d2, 10.0, None, None), row(1, d1, 20.0, None, None)], + ), + ( + "duplicate", + vec![row(1, d1, 10.0, None, None), row(1, d1, 10.0, None, None)], + ), + ("nan_shares", vec![row(1, d1, f64::NAN, None, None)]), + ("neg_shares", vec![row(1, d1, -1.0, None, None)]), + ("inf_net_change", vec![row(1, d1, 10.0, Some(f64::INFINITY), None)]), + ("nan_pct_float", vec![row(1, d1, 10.0, None, Some(f64::NAN))]), + ( + "known_at_not_after", + vec![ShortsParquetRow { + known_at_micros: i64::from(d1) * 86_400_000_000, + ..row(1, d1, 10.0, None, None) + }], + ), + ( + "empty_source", + vec![ShortsParquetRow { + source: Cow::Borrowed(""), + ..row(1, d1, 10.0, None, None) + }], + ), + ]; + + for (label, bad_rows) in cases { + let err = + write_shorts_dataset(&tmp.0, &bad_rows, ShortsWriteOptions::default()).unwrap_err(); + match (label, &err) { + ("unsorted", ParquetShortsError::UnsortedInput { .. }) => {} + ("duplicate", ParquetShortsError::DuplicateKey { .. }) => {} + ("nan_shares" | "neg_shares", ParquetShortsError::InvalidSharesShort { .. }) => {} + ("inf_net_change", ParquetShortsError::InvalidNetChange { .. }) => {} + ("nan_pct_float", ParquetShortsError::InvalidPctFloat { .. }) => {} + ("known_at_not_after", ParquetShortsError::KnownAtNotAfterReportDate { .. }) => {} + ("empty_source", ParquetShortsError::EmptySource { .. }) => {} + other => panic!("unexpected error for case {label}: {other:?}"), + } + assert_eq!( + fs::read(part_path(&tmp.0)).unwrap(), + before, + "case {label} modified existing part.parquet" + ); + assert_eq!( + list_files(&tmp.0.join("shorts")), + ["part.parquet"], + "case {label} left transient files behind" + ); + } + + // out_dir occupied by a regular file returns Io error + let file_out = tmp.0.join("not-a-dir"); + fs::write(&file_out, b"x").unwrap(); + let io_err = write_shorts_dataset(&file_out, &seed, ShortsWriteOptions::default()).unwrap_err(); + assert!(matches!(io_err, ParquetShortsError::Io { .. })); + assert!(std::error::Error::source(&io_err).is_some()); +} + +#[test] +fn concurrent_in_process_writers_publish_one_complete_generation_and_no_transients() { + let tmp = TempDir::new("concurrent"); + let out = Arc::new(tmp.0.clone()); + let base = day(2022, 1, 15); + let make = |base_shares: f64| -> Vec { + (0..1_000_i32) + .map(|i| { + row( + 1 + i / 200, + base + (i % 200) * 15, + base_shares + f64::from(i), + Some(f64::from(i)), + if i % 2 == 0 { None } else { Some(1.25) }, + ) + }) + .collect() + }; + let gens = Arc::new([make(1_000.0), make(9_000.0)]); + let barrier = Arc::new(Barrier::new(2)); + let handles: Vec<_> = (0..2) + .map(|g| { + let (out, gens, barrier) = (out.clone(), gens.clone(), barrier.clone()); + thread::spawn(move || { + barrier.wait(); + let opts = ShortsWriteOptions { + row_group_rows: 131, + ..ShortsWriteOptions::default() + }; + write_shorts_dataset(out.as_path(), &gens[g], opts) + }) + }) + .collect(); + for h in handles { + let stats = h.join().expect("writer thread").expect("writer result"); + assert_eq!(stats.rows_written, 1_000); + assert_eq!(stats.files_written, 1); + } + + let got = read_rows(&part_path(&tmp.0)); + let g = if got.first().map(|r| r.shares_short) == Some(1_000.0) { + 0 + } else { + 1 + }; + assert_rows_bitwise(&got, &gens[g]); + assert_eq!(list_files(&tmp.0.join("shorts")), ["part.parquet"]); +} + +#[test] +fn bench_parquet_shorts_cli_prints_metrics_and_removes_its_temp_dir() { + let tmp = TempDir::new("cli"); + let out = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-shorts", "20000"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + for needle in [ + "curate-etl bench-parquet-shorts", + "rows=20000", + "read_back_rows=20000", + "rows/s", + "MB/s", + "bytes/row", + "compression=", + ] { + assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}"); + } + let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect(); + assert!( + leftovers.is_empty(), + "benchmark left files in TMPDIR: {leftovers:?}" + ); + + let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-shorts", "0"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + assert!(!bad.status.success()); + assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-shorts")); +}