T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate)

This commit is contained in:
Studio 2026-11-28 11:32:43 -05:00
parent 62f47cf3e8
commit fd943851b4
3 changed files with 410 additions and 47 deletions

View file

@ -195,20 +195,22 @@ Rules:
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
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.
- Concurrent writers targeting the same `<out_dir>/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.<run>.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.
- Concurrent writers targeting the same `<out_dir>/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked.
4. **Typed errors (`ParquetBarsError`):**
- `InvalidRowGroupRows` (`row_group_rows == 0`)
- `InvalidZstdLevel { level }`
- `UnsortedInput { prev_listing_id, prev_session_date, listing_id, session_date }`
- `DuplicateKey { listing_id, session_date }`
- `SessionYearOutOfRange { listing_id, session_date, year, min_year, max_year }`
- `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-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=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
## Local Benchmarks
@ -336,7 +338,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=1432.74 ms`, `throughput=3489815 rows/s`, `write=153.98 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x`
## Deferred Follow-Ups (`M1.3+` / `M2`)

View file

@ -39,8 +39,8 @@ pub use fx::{
};
pub use parquet_bars::{
bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions,
Bars1dWriteStats, ParquetBarsError, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL,
MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS,
DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
};
pub use provider_mapping::{
MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow,

View file

@ -27,7 +27,7 @@ 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;
use std::time::{Duration, Instant};
use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel};
use parquet::column::writer::ColumnWriter;
@ -54,6 +54,7 @@ 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)]
@ -98,6 +99,34 @@ pub struct Bars1dWriteStats {
pub rows_by_year: BTreeMap<i32, usize>,
}
/// Single failure encountered while rolling back a partial publication.
#[derive(Debug)]
pub struct RollbackFailure {
pub final_path: PathBuf,
pub backup_path: Option<PathBuf>,
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 {
@ -122,6 +151,14 @@ pub enum ParquetBarsError {
min_year: i32,
max_year: i32,
},
LockTimeout {
path: PathBuf,
waited: Duration,
},
RollbackFailed {
cause: Box<ParquetBarsError>,
failures: Vec<RollbackFailure>,
},
Io {
path: PathBuf,
source: io::Error,
@ -167,6 +204,23 @@ impl fmt::Display for ParquetBarsError {
f,
"session_date {session_date} (year {year}) for listing_id {listing_id} is outside allowed range {min_year}..={max_year}"
),
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())
}
@ -180,6 +234,7 @@ impl fmt::Display for ParquetBarsError {
impl Error for ParquetBarsError {
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,
@ -409,8 +464,9 @@ struct DatasetFileLock {
}
impl DatasetFileLock {
fn acquire(bars_dir: &Path) -> Result<Self, ParquetBarsError> {
fn acquire_with_timeout(bars_dir: &Path, timeout: Duration) -> Result<Self, ParquetBarsError> {
let lock_path = bars_dir.join(".write.lock");
let start = Instant::now();
let mut backoff_ms = 2u64;
loop {
match OpenOptions::new()
@ -424,7 +480,15 @@ impl DatasetFileLock {
return Ok(Self { path: lock_path });
}
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
thread::sleep(Duration::from_millis(backoff_ms));
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) => {
@ -484,7 +548,36 @@ fn create_exclusive_tmp_file(
})
}
fn choose_unique_backup_path(final_path: &Path, run_id: &str) -> Result<PathBuf, ParquetBarsError> {
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<PathBuf, ParquetBarsError> {
let parent = final_path.parent().unwrap_or_else(|| Path::new("."));
for attempt in 0..1024u32 {
let file_name = if attempt == 0 {
@ -493,9 +586,21 @@ fn choose_unique_backup_path(final_path: &Path, run_id: &str) -> Result<PathBuf,
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,
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,
@ -822,17 +927,53 @@ struct PublishedPartition {
backup_path: Option<PathBuf>,
}
fn rollback_published(published: &[PublishedPartition]) {
fn rollback_published(published: &[PublishedPartition]) -> Vec<RollbackFailure> {
let mut failures = Vec::new();
for part in published.iter().rev() {
match &part.backup_path {
Some(bak) => {
let _ = fs::rename(bak, &part.final_path);
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 => {
let _ = fs::remove_file(&part.final_path);
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],
extra_failure: Option<RollbackFailure>,
owned_tmp_paths: &[PathBuf],
) -> ParquetBarsError {
let mut failures = Vec::new();
if let Some(failure) = extra_failure {
failures.push(failure);
}
failures.extend(rollback_published(published));
cleanup_owned_files(owned_tmp_paths);
if failures.is_empty() {
cause
} else {
ParquetBarsError::RollbackFailed {
cause: Box::new(cause),
failures,
}
}
}
/// Streams strictly ascending `(listing_id, session_date)` rows into year-partitioned Zstd
@ -840,12 +981,14 @@ fn rollback_published(published: &[PublishedPartition]) {
///
/// # Concurrency & Atomicity
/// Concurrent writers targeting the same `<out_dir>/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.<run>.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.
/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year
/// partition is written to an exclusively created per-run staging file (`part.parquet.<run>.tmp`),
/// flushed, and `sync_all`'d before publication. During publication, pre-existing `part.parquet`
/// files are backed up in place (via hard link, or exclusive copy fallback) so the live path
/// remains readable until replaced by a single atomic `rename`; on any error, all open writers
/// are dropped, replaced partitions are restored from backup, newly published partitions are
/// removed (with any rollback failures reported alongside the original error), and only staging
/// files owned by the current run are unlinked.
pub fn write_bars_1d_dataset<P, I, R>(
out_dir: P,
rows: I,
@ -855,6 +998,28 @@ where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<Bars1dParquetRow>,
{
write_bars_1d_dataset_with_hooks(
out_dir,
rows,
options,
DEFAULT_LOCK_TIMEOUT,
|_, _, _| {},
)
}
fn write_bars_1d_dataset_with_hooks<P, I, R, F>(
out_dir: P,
rows: I,
options: Bars1dWriteOptions,
lock_timeout: Duration,
mut on_after_backup: F,
) -> Result<Bars1dWriteStats, ParquetBarsError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<Bars1dParquetRow>,
F: FnMut(i32, &Path, Option<&Path>),
{
if options.row_group_rows == 0 {
return Err(ParquetBarsError::InvalidRowGroupRows);
@ -901,7 +1066,7 @@ where
// 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 _file_lock = DatasetFileLock::acquire_with_timeout(&bars_dir, lock_timeout)?;
let run_id = next_run_id();
let mut writers: BTreeMap<i32, YearWriter> = BTreeMap::new();
@ -991,48 +1156,48 @@ where
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,
match create_backup_preserving_live(&file.final_path, &run_id) {
Ok(bak) => Some(bak),
Err(err) => {
rollback_published(&published);
cleanup_owned_files(&owned_tmp_paths);
return Err(err);
return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths));
}
};
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 {
let err = ParquetBarsError::Io {
path: file.final_path,
source,
});
};
return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths));
}
};
on_after_backup(year, &file.final_path, backup_path.as_deref());
if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) {
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 {
// `file.final_path` was never moved during backup creation, so it remains intact;
// only remove the backup created for this partition before rolling back earlier ones.
let extra_failure = backup_path.and_then(|bak| {
fs::remove_file(&bak).err().map(|remove_err| RollbackFailure {
final_path: file.final_path.clone(),
backup_path: Some(bak),
source: remove_err,
})
});
let err = ParquetBarsError::Io {
path: file.final_path,
source,
});
};
return Err(finish_with_rollback(
err,
&published,
extra_failure,
&owned_tmp_paths,
));
}
published.push(PublishedPartition {
@ -2018,4 +2183,200 @@ mod tests {
assert_row_bitwise_eq(actual, expected);
}
}
#[test]
fn existing_partition_remains_readable_between_backup_and_replacement() {
let tmp = TempDirGuard::new("live-readable");
let initial = 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, Bars1dWriteOptions::default()).unwrap();
let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet");
let original_bytes = fs::read(&path_2023).unwrap();
let refresh = vec![
make_row(1, 2023, 6, 1, 99.0, 20_000.0, Some(98.5), "USD", "eod_unadj"),
make_row(2, 2023, 6, 2, 101.0, 30_000.0, None, "CAD", "qm_raw"),
];
let mut observed_mid_publish = false;
let stats = write_bars_1d_dataset_with_hooks(
tmp.path(),
&refresh,
Bars1dWriteOptions::default(),
DEFAULT_LOCK_TIMEOUT,
|year, final_path, backup_path| {
assert_eq!(year, 2023);
let bak = backup_path.expect("backup must be created for existing partition");
assert!(bak.exists(), "backup must exist before replacement");
assert!(
final_path.exists(),
"live partition must remain present after backup creation"
);
assert_eq!(
fs::read(final_path).expect("read live partition before rename"),
original_bytes
);
let live_rows = read_parquet_rows(final_path);
assert_eq!(live_rows.len(), initial.len());
assert_row_bitwise_eq(&live_rows[0], &initial[0]);
observed_mid_publish = true;
},
)
.unwrap();
assert!(observed_mid_publish, "on_after_backup hook must run");
assert_eq!(stats.rows_written, refresh.len());
let updated_rows = read_parquet_rows(&path_2023);
assert_eq!(updated_rows.len(), refresh.len());
for (actual, expected) in updated_rows.iter().zip(refresh.iter()) {
assert_row_bitwise_eq(actual, expected);
}
assert_no_transient_files(&tmp.path().join("bars_1d"));
}
#[test]
fn abandoned_write_lock_times_out_with_actionable_error() {
let tmp = TempDirGuard::new("abandoned-lock");
let initial = vec![make_row(
1,
2024,
1,
2,
100.0,
5_000.0,
Some(99.5),
"USD",
"eod_unadj",
)];
write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap();
let existing_path = tmp.path().join("bars_1d/year=2024/part.parquet");
let original_bytes = fs::read(&existing_path).unwrap();
// Simulate a crashed writer that left `.write.lock` behind.
let lock_path = tmp.path().join("bars_1d/.write.lock");
fs::write(&lock_path, b"999999\n").unwrap();
let timeout = Duration::from_millis(40);
let refresh = vec![make_row(
1,
2024,
2,
1,
105.0,
6_000.0,
None,
"USD",
"eod_unadj",
)];
let err = write_bars_1d_dataset_with_hooks(
tmp.path(),
&refresh,
Bars1dWriteOptions::default(),
timeout,
|_, _, _| {},
)
.unwrap_err();
match &err {
ParquetBarsError::LockTimeout { path, waited } => {
assert_eq!(path, &lock_path);
assert!(*waited >= timeout);
}
other => panic!("expected LockTimeout, got {other:?}"),
}
let msg = err.to_string();
assert!(
msg.contains(&lock_path.display().to_string()),
"LockTimeout message must include lock path, got: {msg}"
);
// Abandoned lock is not unowned-deleted, and existing partition is untouched.
assert_eq!(fs::read(&lock_path).unwrap(), b"999999\n");
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// Clean up simulated lock so assert_no_transient_files checks for stray .tmp/.bak.
fs::remove_file(&lock_path).unwrap();
assert_no_transient_files(&tmp.path().join("bars_1d"));
}
#[test]
fn rollback_failure_reports_original_error_and_partition_backup_paths() {
let tmp = TempDirGuard::new("rollback-failure");
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();
// Block 2024 publication with a directory so 2024 rename fails after 2023 is replaced.
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, 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 mut captured_2023_backup: Option<PathBuf> = None;
let path_2023_for_hook = path_2023.clone();
let err = write_bars_1d_dataset_with_hooks(
tmp.path(),
&refresh,
Bars1dWriteOptions::default(),
DEFAULT_LOCK_TIMEOUT,
|year, _final_path, backup_path| {
if year == 2023 {
captured_2023_backup = backup_path.map(Path::to_path_buf);
} else if year == 2024 {
// Replace already-published 2023 file with a directory so rollback's
// `fs::rename(bak, path_2023)` deterministically fails.
fs::remove_file(&path_2023_for_hook).unwrap();
fs::create_dir(&path_2023_for_hook).unwrap();
}
},
)
.unwrap_err();
let expected_bak = captured_2023_backup.expect("2023 backup path recorded");
match &err {
ParquetBarsError::RollbackFailed { cause, failures } => {
assert!(
matches!(cause.as_ref(), ParquetBarsError::Io { path, .. } if path == &blocker_2024),
"expected original cause at {}, got {cause:?}",
blocker_2024.display()
);
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].final_path, path_2023);
assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path()));
}
other => panic!("expected RollbackFailed, got {other:?}"),
}
let msg = err.to_string();
assert!(msg.contains(&blocker_2024.display().to_string()), "{msg}");
assert!(msg.contains(&path_2023.display().to_string()), "{msg}");
assert!(msg.contains(&expected_bak.display().to_string()), "{msg}");
assert!(err.source().is_some());
// Original backup remains intact on disk for operator recovery.
assert_eq!(fs::read(&expected_bak).unwrap(), original_2023_bytes);
}
}