From 62f47cf3e898d77b2ffffbd44c8943ddbd19a710 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 11:24:10 -0500 Subject: [PATCH] =?UTF-8?q?T-90:=20M1.2i=20=E2=80=94=20`tools/curate-etl`:?= =?UTF-8?q?=20Zstd=20Parquet=20writer=20for=20`bars=5F1d`=20(`year=3DYYYY/?= =?UTF-8?q?part.parquet`,=20contract=20schema)=20with=20round-trip=20tests?= =?UTF-8?q?=20and=20local=20benchmark=20(adds=20the=20`parquet`=20crate)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 8 +- tools/curate-etl/src/bench.rs | 174 +++++++-- tools/curate-etl/src/parquet_bars.rs | 521 +++++++++++++++++++++++++-- 3 files changed, 650 insertions(+), 53 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 755bf94f..0c4c0f70 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -193,9 +193,9 @@ Rules: - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`). - Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary. - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. -3. **Sort & atomicity rules:** +3. **Sort, concurrency & atomicity rules:** - Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order. - - Every year partition writes to `part.parquet.tmp`, flushes, and calls `File::sync_all()` before any partition is renamed to `part.parquet`. On any error, all open writers are dropped and all created `part.parquet.tmp` files are removed while leaving pre-existing `part.parquet` files untouched. + - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and an exclusive `.write.lock` file. Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up until every partition rename succeeds; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed, and only staging files owned by the current run are unlinked. 4. **Typed errors (`ParquetBarsError`):** - `InvalidRowGroupRows` (`row_group_rows == 0`) - `InvalidZstdLevel { level }` @@ -208,7 +208,7 @@ Rules: - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-bars` - Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` (20 years `2006..=2025`) - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` - - Perf: `elapsed=1258.64 ms`, `throughput=3972536 rows/s`, `write=175.28 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` + - Perf: `elapsed=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` ## Local Benchmarks @@ -336,7 +336,7 @@ Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-pa - Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` -- Perf: `elapsed=1258.64 ms`, `throughput=3972536 rows/s`, `write=175.28 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` +- Perf: `elapsed=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` ## Deferred Follow-Ups (`M1.3+` / `M2`) diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 557059e1..4ab31613 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -3,10 +3,12 @@ use std::borrow::Cow; use std::fs::{self, File}; use std::hint::black_box; -use std::path::PathBuf; +use std::io; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; +use parquet::errors::ParquetError; use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; @@ -1634,16 +1636,30 @@ struct BenchTempDir { } impl BenchTempDir { - fn new() -> Result { - let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + fn new_in(base: &Path) -> Result { let pid = std::process::id(); - let path = std::env::temp_dir().join(format!("curate-etl-bench-pq-bars-{pid}-{seq}")); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).map_err(|source| ParquetBarsError::Io { - path: path.clone(), - source, - })?; - Ok(Self { path }) + 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}")); + 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(ParquetBarsError::Io { + path: base.to_path_buf(), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique benchmark temp directory names", + ), + }) + } + + fn new() -> Result { + Self::new_in(&std::env::temp_dir()) } } @@ -1796,6 +1812,53 @@ fn collect_bench_weekdays_2006_2025() -> Vec { days } +fn verify_parquet_bars_row_count( + out_dir: &Path, + years: impl IntoIterator, + expected_rows: usize, +) -> Result { + let mut read_back_rows = 0usize; + for year in years { + let path = out_dir.join(format!("bars_1d/year={year:04}/part.parquet")); + let file = File::open(&path).map_err(|source| ParquetBarsError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| { + ParquetBarsError::Parquet { + path: path.clone(), + source, + } + })?; + let file_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetBarsError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + read_back_rows = read_back_rows.checked_add(file_rows).ok_or_else(|| { + ParquetBarsError::Parquet { + path: path.clone(), + source: ParquetError::General("read-back row count overflow".to_string()), + } + })?; + } + + if read_back_rows != expected_rows { + return Err(ParquetBarsError::Parquet { + path: out_dir.join("bars_1d"), + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + fn run_parquet_bars_benchmark_tracked( rows: usize, ) -> Result<(ParquetBarsBenchReport, PathBuf), ParquetBarsError> { @@ -1808,9 +1871,11 @@ fn run_parquet_bars_benchmark_tracked( std::iter::empty::(), Bars1dWriteOptions::default(), )?; + let read_back_rows = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 0)?; let report = ParquetBarsBenchReport { rows: 0, - read_back_rows: stats.rows_written, + read_back_rows, listing_count: 0, files_written: stats.files_written, row_groups_written: stats.row_groups_written, @@ -1835,24 +1900,19 @@ fn run_parquet_bars_benchmark_tracked( let elapsed_secs = start.elapsed().as_secs_f64(); let elapsed_ms = elapsed_secs * 1_000.0; - let mut read_back_rows = 0usize; - for &year in stats.rows_by_year.keys() { - let path = temp - .path - .join(format!("bars_1d/year={year:04}/part.parquet")); - let file = File::open(&path).map_err(|source| ParquetBarsError::Io { - path: path.clone(), - source, - })?; - let reader = SerializedFileReader::new(file).map_err(|source| { - ParquetBarsError::Parquet { - path: path.clone(), - source, - } - })?; - read_back_rows += reader.metadata().file_metadata().num_rows() as usize; + if stats.rows_written != rows { + return Err(ParquetBarsError::Parquet { + path: temp.path.join("bars_1d"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); } + let read_back_rows = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 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 @@ -2270,4 +2330,64 @@ mod tests { assert_eq!(report.bytes_per_row, 0.0); assert_eq!(report.compression_ratio, 0.0); } + + #[test] + fn verify_parquet_bars_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new().unwrap(); + let weekdays = collect_bench_weekdays_2006_2025(); + let iter = ParquetBarsBenchIter::new(250, weekdays); + let stats = + write_bars_1d_dataset(&temp.path, iter, Bars1dWriteOptions::default()).unwrap(); + + let matched = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 250) + .unwrap(); + assert_eq!(matched, 250); + + let err = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 255) + .unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetBarsError::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}" + ); + + let err_zero = verify_parquet_bars_row_count(&temp.path, std::iter::empty(), 10) + .unwrap_err(); + let msg_zero = err_zero.to_string(); + assert!( + msg_zero.contains("10") && msg_zero.contains('0'), + "error must report expected (10) and actual (0) row counts, got: {msg_zero}" + ); + } + + #[test] + fn bench_temp_dir_retries_on_collision_and_preserves_existing_dir() { + let root = BenchTempDir::new().unwrap(); + let pid = std::process::id(); + let next_seq = BENCH_TEMP_DIR_SEQ.load(AtomicOrdering::Relaxed); + let colliding = root + .path + .join(format!("curate-etl-bench-pq-bars-{pid}-{next_seq}")); + fs::create_dir(&colliding).unwrap(); + let sentinel = colliding.join("keep.txt"); + fs::write(&sentinel, b"do-not-delete").unwrap(); + + let created_path = { + let dir = BenchTempDir::new_in(&root.path).unwrap(); + assert_ne!(dir.path, colliding); + assert!(dir.path.is_dir()); + assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete"); + dir.path.clone() + }; + + assert!(!created_path.exists()); + assert!(colliding.is_dir()); + assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete"); + } } diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs index 9a5aae37..1530654c 100644 --- a/tools/curate-etl/src/parquet_bars.rs +++ b/tools/curate-etl/src/parquet_bars.rs @@ -21,10 +21,13 @@ use std::cmp::Ordering; use std::collections::{BTreeMap, HashMap}; use std::error::Error; use std::fmt; -use std::fs::{self, File}; +use std::fs::{self, File, OpenOptions}; use std::io::{self, BufWriter, Write}; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::thread; +use std::time::Duration; use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; use parquet::column::writer::ColumnWriter; @@ -389,6 +392,127 @@ 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(bars_dir: &Path) -> Result { + let lock_path = bars_dir.join(".write.lock"); + 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 => { + thread::sleep(Duration::from_millis(backoff_ms)); + 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 choose_unique_backup_path(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::symlink_metadata(&bak_path) { + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(bak_path), + Ok(_) => continue, + 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, @@ -402,9 +526,10 @@ impl YearWriter { fn open( bars_dir: &Path, year: i32, + run_id: &str, schema: &TypePtr, props: &WriterPropertiesPtr, - created_tmp_paths: &mut Vec, + owned_tmp_paths: &mut Vec, ) -> Result { let year_dir = bars_dir.join(format!("year={year:04}")); fs::create_dir_all(&year_dir).map_err(|source| ParquetBarsError::Io { @@ -412,13 +537,9 @@ impl YearWriter { source, })?; - let tmp_path = year_dir.join("part.parquet.tmp"); + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + owned_tmp_paths.push(tmp_path.clone()); let final_path = year_dir.join("part.parquet"); - let file = File::create(&tmp_path).map_err(|source| ParquetBarsError::Io { - path: tmp_path.clone(), - source, - })?; - created_tmp_paths.push(tmp_path.clone()); let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( @@ -690,20 +811,41 @@ fn write_interned_str_col( }) } -fn cleanup_temp_files(tmp_paths: &[PathBuf]) { - for path in tmp_paths { +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]) { + for part in published.iter().rev() { + match &part.backup_path { + Some(bak) => { + let _ = fs::rename(bak, &part.final_path); + } + None => { + let _ = fs::remove_file(&part.final_path); + } + } + } +} + /// Streams strictly ascending `(listing_id, session_date)` rows into year-partitioned Zstd /// Parquet files at `/bars_1d/year=YYYY/part.parquet`. /// -/// # Atomicity -/// Every year partition is written to `part.parquet.tmp`, flushed, and `sync_all`'d before any -/// partition is renamed to `part.parquet`. On any validation, Parquet, or I/O error, all open -/// writers are closed and all created `.tmp` files are removed, leaving pre-existing -/// `part.parquet` files untouched. +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/bars_1d` directory are serialized via an +/// in-process per-dataset mutex and an exclusive `.write.lock` file. Every year partition is +/// written to an exclusively created per-run staging file (`part.parquet..tmp`), flushed, +/// and `sync_all`'d before publication. During publication, pre-existing `part.parquet` files +/// are moved to per-run backups until every partition rename succeeds; on any error, all open +/// writers are dropped, replaced partitions are restored from backup, newly published partitions +/// are removed, and only staging files owned by the current run are unlinked. pub fn write_bars_1d_dataset( out_dir: P, rows: I, @@ -723,6 +865,24 @@ where } })?; + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(Bars1dWriteStats::default()); + }; + { + let first_row = first_item.borrow(); + let (first_year, _, _) = epoch_days_to_ymd(first_row.session_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&first_year) { + return Err(ParquetBarsError::SessionYearOutOfRange { + listing_id: first_row.listing_id, + session_date: first_row.session_date, + year: first_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + let out_dir = out_dir.as_ref(); let bars_dir = out_dir.join("bars_1d"); let schema = bars_1d_parquet_schema().map_err(|source| ParquetBarsError::Parquet { @@ -731,14 +891,27 @@ where })?; let props = build_writer_properties(zstd_level); + fs::create_dir_all(&bars_dir).map_err(|source| ParquetBarsError::Io { + path: bars_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(&bars_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire(&bars_dir)?; + + let run_id = next_run_id(); let mut writers: BTreeMap = BTreeMap::new(); - let mut created_tmp_paths: Vec = Vec::new(); + let mut owned_tmp_paths: Vec = Vec::new(); let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); let write_result: Result, ParquetBarsError> = (|| { let mut prev_key: Option<(i32, i32)> = None; - for item in rows { + for item in std::iter::once(first_item).chain(row_iter) { let row = item.borrow(); if let Some((prev_listing_id, prev_session_date)) = prev_key { match (row.listing_id, row.session_date).cmp(&(prev_listing_id, prev_session_date)) @@ -779,9 +952,10 @@ where let opened = YearWriter::open( &bars_dir, year, + &run_id, &schema, &props, - &mut created_tmp_paths, + &mut owned_tmp_paths, )?; entry.insert(opened) } @@ -805,22 +979,66 @@ where let synced_files = match write_result { Ok(files) => files, Err(err) => { - // Drop all open writers before unlinking temporary files. + // Drop all open writers before unlinking temporary files owned by this run. drop(writers); - cleanup_temp_files(&created_tmp_paths); + cleanup_owned_files(&owned_tmp_paths); return Err(err); } }; let mut stats = Bars1dWriteStats::default(); + let mut published: Vec = Vec::with_capacity(synced_files.len()); for (year, file) in synced_files { + let backup_path = match fs::symlink_metadata(&file.final_path) { + Ok(meta) if !meta.is_dir() => { + let bak = match choose_unique_backup_path(&file.final_path, &run_id) { + Ok(path) => path, + Err(err) => { + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); + return Err(err); + } + }; + if let Err(source) = fs::rename(&file.final_path, &bak) { + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); + return Err(ParquetBarsError::Io { + path: file.final_path, + source, + }); + } + Some(bak) + } + // Directory occupying final_path: leave it in place so the rename below fails + // cleanly and triggers rollback of all earlier partitions. + Ok(_) => None, + Err(err) if err.kind() == io::ErrorKind::NotFound => None, + Err(source) => { + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); + return Err(ParquetBarsError::Io { + path: file.final_path, + source, + }); + } + }; + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { - cleanup_temp_files(&created_tmp_paths); + if let Some(bak) = backup_path { + let _ = fs::rename(&bak, &file.final_path); + } + rollback_published(&published); + cleanup_owned_files(&owned_tmp_paths); return Err(ParquetBarsError::Io { path: file.final_path, source, }); } + + published.push(PublishedPartition { + final_path: file.final_path, + backup_path, + }); stats.rows_written += file.rows_written; stats.files_written += 1; stats.row_groups_written += file.row_groups_written; @@ -828,6 +1046,12 @@ where stats.rows_by_year.insert(year, file.rows_written); } + for part in &published { + if let Some(bak) = &part.backup_path { + let _ = fs::remove_file(bak); + } + } + Ok(stats) } @@ -869,6 +1093,7 @@ mod tests { } } + #[allow(clippy::too_many_arguments)] fn make_row( listing_id: i32, year: i32, @@ -1498,6 +1723,258 @@ mod tests { assert!(!tmp.path().join("bars_1d/year=2023/part.parquet").exists()); assert!(!existing_tmp.exists()); assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + fn assert_no_transient_files(bars_dir: &Path) { + if !bars_dir.exists() { + return; + } + assert!( + !bars_dir.join(".write.lock").exists(), + "stale .write.lock left in {}", + bars_dir.display() + ); + for entry in fs::read_dir(bars_dir).expect("read bars_dir") { + let entry = entry.expect("bars_dir entry"); + let path = entry.path(); + if path.is_dir() { + for sub in fs::read_dir(&path).expect("read year dir") { + let sub = sub.expect("year dir entry"); + let name = sub.file_name(); + let name_str = name.to_string_lossy(); + assert!( + !name_str.ends_with(".tmp") && !name_str.ends_with(".bak"), + "stale transient file left behind: {}", + sub.path().display() + ); + } + } + } + } + + #[test] + fn publication_rename_failure_rolls_back_replaced_and_new_partitions() { + let tmp = TempDirGuard::new("rename-rollback"); + + // Seed an existing 2023 partition. + let initial_2023 = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial_2023, Bars1dWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + // Occupy 2024's final path with a directory so the third partition's rename fails + // after 2022 (new) and 2023 (replaced) have already been renamed into place. + let blocker_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![ + make_row(1, 2022, 6, 1, 50.0, 1_000.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 6, 1, 99.0, 2_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 120.0, 3_000.0, None, "USD", "eod_unadj"), + ]; + + let err = write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!( + matches!(&err, ParquetBarsError::Io { path, .. } if path == &blocker_2024), + "expected Io error at {}, got {err:?}", + blocker_2024.display() + ); + + // Newly published 2022 partition must be removed on rollback. + assert!( + !tmp.path().join("bars_1d/year=2022/part.parquet").exists(), + "newly published 2022 partition must be rolled back" + ); + // Existing 2023 partition must be restored byte-for-byte from backup. + assert_eq!( + fs::read(&path_2023).unwrap(), + original_2023_bytes, + "existing 2023 partition must be restored byte-identical" + ); + // Occupying directory at 2024 must remain untouched. + assert!(blocker_2024.is_dir()); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn overlapping_writers_serialize_without_corruption_or_mixed_generations() { + use std::sync::mpsc; + + let tmp = TempDirGuard::new("overlap"); + let out_dir = tmp.path().to_path_buf(); + + let rows_a = vec![ + make_row(1, 2023, 3, 1, 100.0, 1_000.0, Some(100.0), "USD", "eod_unadj"), + make_row(1, 2024, 3, 1, 101.0, 1_100.0, Some(101.0), "USD", "eod_unadj"), + make_row(2, 2023, 3, 1, 102.0, 1_200.0, None, "CAD", "eod_unadj"), + make_row(2, 2024, 3, 1, 103.0, 1_300.0, None, "CAD", "eod_unadj"), + ]; + let rows_b = vec![ + make_row(1, 2023, 4, 1, 200.0, 2_000.0, Some(200.0), "USD", "qm_raw"), + make_row(1, 2024, 4, 1, 201.0, 2_100.0, Some(201.0), "USD", "qm_raw"), + make_row(2, 2023, 4, 1, 202.0, 2_200.0, None, "CAD", "qm_raw"), + make_row(2, 2024, 4, 1, 203.0, 2_300.0, None, "CAD", "qm_raw"), + ]; + + struct SignalingIter { + rows: std::vec::IntoIter, + seen: usize, + on_second: Option>, + on_end: Option>, + } + + impl Iterator for SignalingIter { + type Item = Bars1dParquetRow; + fn next(&mut self) -> Option { + self.seen += 1; + if self.seen == 2 { + if let Some(cb) = self.on_second.take() { + cb(); + } + } + let item = self.rows.next(); + if item.is_none() { + if let Some(cb) = self.on_end.take() { + cb(); + } + } + item + } + } + + let events = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let (t1_locked_tx, t1_locked_rx) = mpsc::channel::<()>(); + let (t2_started_tx, t2_started_rx) = mpsc::channel::<()>(); + + let out_dir_1 = out_dir.clone(); + let events_1 = Arc::clone(&events); + let events_1_end = Arc::clone(&events); + let rows_a_clone = rows_a.clone(); + let handle_1 = thread::spawn(move || { + let iter = SignalingIter { + rows: rows_a_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + events_1.lock().unwrap().push("t1_row2"); + let _ = t1_locked_tx.send(()); + // Wait briefly for thread 2 to enter write_bars_1d_dataset and block on lock. + let _ = t2_started_rx.recv_timeout(Duration::from_secs(2)); + thread::sleep(Duration::from_millis(30)); + })), + on_end: Some(Box::new(move || { + events_1_end.lock().unwrap().push("t1_iter_end"); + })), + }; + write_bars_1d_dataset(&out_dir_1, iter, Bars1dWriteOptions::default()) + }); + + let out_dir_2 = out_dir.clone(); + let events_2 = Arc::clone(&events); + let rows_b_clone = rows_b.clone(); + let handle_2 = thread::spawn(move || { + t1_locked_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + let _ = t2_started_tx.send(()); + let iter = SignalingIter { + rows: rows_b_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + events_2.lock().unwrap().push("t2_row2"); + })), + on_end: None, + }; + write_bars_1d_dataset(&out_dir_2, iter, Bars1dWriteOptions::default()) + }); + + let stats_1 = handle_1.join().unwrap().unwrap(); + let stats_2 = handle_2.join().unwrap().unwrap(); + assert_eq!(stats_1.rows_written, rows_a.len()); + assert_eq!(stats_2.rows_written, rows_b.len()); + + // Thread 1 must have finished its entire stream before Thread 2 could pull row 2 under the lock. + let recorded = events.lock().unwrap(); + let pos_t1_end = recorded + .iter() + .position(|&e| e == "t1_iter_end") + .expect("t1_iter_end recorded"); + let pos_t2_row2 = recorded + .iter() + .position(|&e| e == "t2_row2") + .expect("t2_row2 recorded"); + assert!( + pos_t1_end < pos_t2_row2, + "expected strict serialization, got events: {recorded:?}" + ); + + // Final on-disk partitions must match Thread 2 across all years (no mixed generations). + for year in [2023, 2024] { + let actual = read_parquet_rows( + &out_dir.join(format!("bars_1d/year={year:04}/part.parquet")), + ); + let expected: Vec<&Bars1dParquetRow> = rows_b + .iter() + .filter(|r| epoch_days_to_ymd(r.session_date).0 == year) + .collect(); + assert_eq!(actual.len(), expected.len()); + for (a, e) in actual.iter().zip(expected.iter()) { + assert_row_bitwise_eq(a, e); + } + } + assert_no_transient_files(&out_dir.join("bars_1d")); + } + + #[test] + fn exclusive_staging_and_cleanup_preserve_unowned_tmp_files() { + let tmp = TempDirGuard::new("unowned-tmp"); + let year_dir = tmp.path().join("bars_1d/year=2024"); + fs::create_dir_all(&year_dir).unwrap(); + + let foreign_tmp_1 = year_dir.join("part.parquet.tmp"); + let foreign_tmp_2 = year_dir.join("part.parquet.foreign.tmp"); + fs::write(&foreign_tmp_1, b"foreign-staging-1").unwrap(); + fs::write(&foreign_tmp_2, b"foreign-staging-2").unwrap(); + + // Failing run must clean up only its own staging file and never touch unowned .tmp files. + let unsorted = vec![ + make_row(2, 2024, 5, 1, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 2, 51.0, 200.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &unsorted, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::UnsortedInput { .. })); + assert_eq!(fs::read(&foreign_tmp_1).unwrap(), b"foreign-staging-1"); + assert_eq!(fs::read(&foreign_tmp_2).unwrap(), b"foreign-staging-2"); + + // Succeeding run must also preserve unowned .tmp files and leave only part.parquet + foreign files. + let valid = vec![make_row( + 1, + 2024, + 5, + 1, + 50.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &valid, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(fs::read(&foreign_tmp_1).unwrap(), b"foreign-staging-1"); + assert_eq!(fs::read(&foreign_tmp_2).unwrap(), b"foreign-staging-2"); + assert_eq!( + read_parquet_rows(&year_dir.join("part.parquet")).len(), + 1 + ); } #[test]