T-92: M1.2j — tools/curate-etl: Zstd Parquet writer for shorts/part.parquet (contract schema, atomic single-file publish) with round-trip tests and local benchmark (no new crates)

This commit is contained in:
Studio 2026-11-28 14:01:04 -05:00
parent 9f2bcd181a
commit d99c3c0648
3 changed files with 129 additions and 42 deletions

View file

@ -9,7 +9,7 @@ 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::sync::{Arc, Mutex, OnceLock, Weak};
use std::thread;
use std::time::{Duration, Instant};
@ -112,16 +112,20 @@ impl StringInterner {
}
}
static DATASET_LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
static DATASET_LOCKS: OnceLock<Mutex<HashMap<PathBuf, Weak<Mutex<()>>>>> = OnceLock::new();
static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0);
pub(crate) fn dataset_mutex(dataset_dir: &Path) -> Arc<Mutex<()>> {
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()
map.retain(|_, weak| weak.strong_count() > 0);
if let Some(existing) = map.get(&key).and_then(Weak::upgrade) {
return existing;
}
let lock = Arc::new(Mutex::new(()));
map.insert(key, Arc::downgrade(&lock));
lock
}
pub(crate) struct DatasetFileLock {
@ -292,6 +296,30 @@ pub(crate) fn cleanup_owned_files(owned_paths: &[PathBuf]) {
}
}
/// Drop guard that removes an exclusively created staging file unless disarmed
/// after successful publication.
pub(crate) struct StagingFileGuard {
path: Option<PathBuf>,
}
impl StagingFileGuard {
pub(crate) fn new(path: PathBuf) -> Self {
Self { path: Some(path) }
}
pub(crate) fn disarm(&mut self) {
self.path = None;
}
}
impl Drop for StagingFileGuard {
fn drop(&mut self) {
if let Some(path) = self.path.take() {
let _ = fs::remove_file(path);
}
}
}
pub(crate) struct PublishedPartition {
pub(crate) final_path: PathBuf,
pub(crate) backup_path: Option<PathBuf>,
@ -415,3 +443,39 @@ pub(crate) fn write_interned_str_col(
}
col.close()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dataset_mutex_shares_active_lock_and_prunes_expired_entries() {
let dir_a = PathBuf::from(format!(
"/tmp/curate-etl-weak-lock-a-{}-{}",
std::process::id(),
next_run_id()
));
let dir_b = PathBuf::from(format!(
"/tmp/curate-etl-weak-lock-b-{}-{}",
std::process::id(),
next_run_id()
));
let lock_a1 = dataset_mutex(&dir_a);
let lock_a2 = dataset_mutex(&dir_a);
assert!(Arc::ptr_eq(&lock_a1, &lock_a2));
drop(lock_a1);
drop(lock_a2);
// Next acquisition prunes the expired entry for `dir_a`.
let _lock_b = dataset_mutex(&dir_b);
let map = DATASET_LOCKS
.get()
.expect("registry initialized")
.lock()
.unwrap_or_else(|err| err.into_inner());
assert!(!map.contains_key(&dir_a));
assert!(map.contains_key(&dir_b));
}
}

View file

@ -29,9 +29,9 @@ 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,
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, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT,
FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS,
};
pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL};
@ -441,17 +441,13 @@ struct ShortsFileWriter {
}
impl ShortsFileWriter {
fn open(
shorts_dir: &Path,
run_id: &str,
fn from_file(
tmp_path: PathBuf,
final_path: PathBuf,
file: File,
schema: &TypePtr,
props: &WriterPropertiesPtr,
owned_tmp_paths: &mut Vec<PathBuf>,
) -> Result<Self, ParquetShortsError> {
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 {
@ -661,18 +657,22 @@ where
let _file_lock = DatasetFileLock::acquire_with_timeout(&shorts_dir, lock_timeout)?;
let run_id = next_run_id();
let mut owned_tmp_paths: Vec<PathBuf> = Vec::new();
let (tmp_path, tmp_file) = create_exclusive_tmp_file(&shorts_dir, &run_id)?;
// Declared before `file_writer` so Rust's reverse drop order closes the file handle
// before the guard unlinks the staging file on error or panic unwind, while `_file_lock`
// and `_in_process_guard` are still held.
let mut staging_guard = StagingFileGuard::new(tmp_path.clone());
let mut scratch: Vec<ByteArray> = Vec::with_capacity(STRING_WRITE_BATCH_ROWS);
let mut file_writer = Some(ShortsFileWriter::open(
&shorts_dir,
&run_id,
let mut file_writer = Some(ShortsFileWriter::from_file(
tmp_path,
shorts_dir.join("part.parquet"),
tmp_file,
&schema,
&props,
&mut owned_tmp_paths,
)?);
let write_result: Result<SyncedShortsFile, ParquetShortsError> = (|| {
let synced = {
let mut prev_key: Option<(i32, i32)> = None;
let writer = file_writer.as_mut().expect("writer initialized");
@ -707,33 +707,17 @@ where
}
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);
}
writer.finish_and_sync(&mut scratch)?
};
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());
}
}
Some(create_backup_preserving_live(&synced.final_path, &run_id)?)
}
// Directory occupying final_path: leave it in place so the rename below fails cleanly.
Ok(_) => None,
Err(err) if err.kind() == io::ErrorKind::NotFound => None,
Err(source) => {
cleanup_owned_files(&owned_tmp_paths);
return Err(ParquetShortsError::Io {
path: synced.final_path,
source,
@ -745,7 +729,7 @@ where
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.
// remove the backup created for this run. `staging_guard` unlinks our staging file on drop.
let backup_remove_failure = backup_path.and_then(|bak| {
fs::remove_file(&bak).err().map(|remove_err| RollbackFailure {
final_path: synced.final_path.clone(),
@ -753,7 +737,6 @@ where
source: remove_err,
})
});
cleanup_owned_files(&owned_tmp_paths);
let cause = ParquetShortsError::Io {
path: synced.final_path,
source,
@ -767,6 +750,8 @@ where
};
}
staging_guard.disarm();
if let Some(bak) = backup_path {
let _ = fs::remove_file(bak);
}

View file

@ -531,3 +531,41 @@ fn concurrent_in_process_writers_serialize_cleanly() {
assert!(got.iter().all(|r| r.source == SHORTS_SOURCE_CEO));
assert_no_transient_files(&tmp.path().join("shorts"));
}
#[test]
fn panicking_iterator_cleans_up_staging_file_and_releases_lock() {
let tmp = TempDirGuard::new("panic-unwind");
let (part, before) = seed_existing(tmp.path());
let out = tmp.path().to_path_buf();
let opts = ShortsWriteOptions {
row_group_rows: 2,
..ShortsWriteOptions::default()
};
let result = std::panic::catch_unwind(move || {
let base = day(2024, 3, 15);
let iter = (0..5_i32).map(move |i| {
if i == 3 {
panic!("simulated iterator panic after row-group flush");
}
make_row(10, base + i * 15, 1_000.0 + f64::from(i), Some(1.0), None)
});
let _ = write_shorts_dataset(&out, iter, opts);
});
assert!(result.is_err(), "iterator must have panicked");
// Pre-existing live file stays byte-identical and both staging `.tmp` and `.write.lock`
// are removed during unwind.
assert_eq!(fs::read(&part).unwrap(), before);
assert_no_transient_files(&tmp.path().join("shorts"));
// Subsequent writer succeeds immediately without hanging on a stale lock.
let replacement = vec![make_row(99, day(2024, 6, 15), 250.0, None, Some(0.5))];
let stats = write_shorts_dataset(tmp.path(), &replacement, ShortsWriteOptions::default())
.unwrap();
assert_eq!(stats.rows_written, 1);
let got = read_parquet_rows(&part);
assert_eq!(got.len(), 1);
assert_row_bitwise_eq(&got[0], &replacement[0]);
assert_no_transient_files(&tmp.path().join("shorts"));
}