stock-bot/tools/curate-etl/src/parquet_bars.rs

2386 lines
84 KiB
Rust

//! Streaming, atomic, year-partitioned Zstd Parquet writer for `bars_1d`.
//!
//! Writes `bars_1d/year=YYYY/part.parquet` files matching the 12-column contract schema in
//! `design/DATA-CONTRACTS.md` (§3A):
//!
//! 1. `listing_id` (`INT32`, `REQUIRED`)
//! 2. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
//! 3. `session_date` (`INT32`, `REQUIRED`, `DATE`)
//! 4. `open` (`DOUBLE`, `REQUIRED`)
//! 5. `high` (`DOUBLE`, `REQUIRED`)
//! 6. `low` (`DOUBLE`, `REQUIRED`)
//! 7. `close` (`DOUBLE`, `REQUIRED`)
//! 8. `volume` (`DOUBLE`, `REQUIRED`)
//! 9. `vwap` (`DOUBLE`, `OPTIONAL`)
//! 10. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 11. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 12. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::error::Error;
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::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::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 {
pub listing_id: i32,
pub ts_micros: i64,
pub session_date: i32,
pub open: f64,
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: f64,
pub vwap: Option<f64>,
pub currency: Cow<'static, str>,
pub source: Cow<'static, str>,
pub known_at_micros: i64,
}
/// Configuration for [`write_bars_1d_dataset`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Bars1dWriteOptions {
pub row_group_rows: usize,
pub zstd_level: i32,
}
impl Default for Bars1dWriteOptions {
fn default() -> Self {
Self {
row_group_rows: DEFAULT_ROW_GROUP_ROWS,
zstd_level: DEFAULT_ZSTD_LEVEL,
}
}
}
/// Accounting summary returned by [`write_bars_1d_dataset`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Bars1dWriteStats {
pub rows_written: usize,
pub files_written: usize,
pub row_groups_written: usize,
pub bytes_written: u64,
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 {
InvalidRowGroupRows,
InvalidZstdLevel {
level: i32,
},
UnsortedInput {
prev_listing_id: i32,
prev_session_date: i32,
listing_id: i32,
session_date: i32,
},
DuplicateKey {
listing_id: i32,
session_date: i32,
},
SessionYearOutOfRange {
listing_id: i32,
session_date: i32,
year: i32,
min_year: i32,
max_year: i32,
},
LockTimeout {
path: PathBuf,
waited: Duration,
},
RollbackFailed {
cause: Box<ParquetBarsError>,
failures: Vec<RollbackFailure>,
},
Io {
path: PathBuf,
source: io::Error,
},
Parquet {
path: PathBuf,
source: ParquetError,
},
}
impl fmt::Display for ParquetBarsError {
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_session_date,
listing_id,
session_date,
} => write!(
f,
"unsorted input: ({listing_id}, {session_date}) follows ({prev_listing_id}, {prev_session_date})"
),
Self::DuplicateKey {
listing_id,
session_date,
} => write!(
f,
"duplicate (listing_id, session_date) key: ({listing_id}, {session_date})"
),
Self::SessionYearOutOfRange {
listing_id,
session_date,
year,
min_year,
max_year,
} => write!(
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())
}
Self::Parquet { path, source } => {
write!(f, "Parquet error at '{}': {source}", path.display())
}
}
}
}
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,
}
}
}
/// Builds the exact 12-column Parquet schema for `bars_1d` per `design/DATA-CONTRACTS.md`.
pub fn bars_1d_parquet_schema() -> Result<TypePtr, ParquetError> {
let fields: Vec<TypePtr> = vec![
Arc::new(
Type::primitive_type_builder("listing_id", PhysicalType::INT32)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("ts", PhysicalType::INT64)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS)))
.build()?,
),
Arc::new(
Type::primitive_type_builder("session_date", PhysicalType::INT32)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::Date))
.build()?,
),
Arc::new(
Type::primitive_type_builder("open", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("high", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("low", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("close", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("volume", PhysicalType::DOUBLE)
.with_repetition(Repetition::REQUIRED)
.build()?,
),
Arc::new(
Type::primitive_type_builder("vwap", PhysicalType::DOUBLE)
.with_repetition(Repetition::OPTIONAL)
.build()?,
),
Arc::new(
Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("source", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.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()?,
),
];
Ok(Arc::new(
Type::group_type_builder("bars_1d")
.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("currency"), true)
.set_column_dictionary_enabled(ColumnPath::from("source"), true)
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
.build(),
)
}
#[derive(Default)]
struct StringInterner {
values: Vec<ByteArray>,
index: HashMap<String, u32>,
}
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<i32>,
ts_micros: Vec<i64>,
session_date: Vec<i32>,
open: Vec<f64>,
high: Vec<f64>,
low: Vec<f64>,
close: Vec<f64>,
volume: Vec<f64>,
vwap_values: Vec<f64>,
vwap_def_levels: Vec<i16>,
currency_ids: Vec<u32>,
currency_interner: StringInterner,
source_ids: Vec<u32>,
source_interner: StringInterner,
known_at_micros: Vec<i64>,
}
impl RowGroupBuffer {
#[inline]
fn len(&self) -> usize {
self.listing_id.len()
}
fn push(&mut self, row: &Bars1dParquetRow) {
self.listing_id.push(row.listing_id);
self.ts_micros.push(row.ts_micros);
self.session_date.push(row.session_date);
self.open.push(row.open);
self.high.push(row.high);
self.low.push(row.low);
self.close.push(row.close);
self.volume.push(row.volume);
match row.vwap {
Some(v) => {
self.vwap_values.push(v);
self.vwap_def_levels.push(1);
}
None => {
self.vwap_def_levels.push(0);
}
}
let currency_id = self.currency_interner.intern(row.currency.as_ref());
self.currency_ids.push(currency_id);
let source_id = self.source_interner.intern(row.source.as_ref());
self.source_ids.push(source_id);
self.known_at_micros.push(row.known_at_micros);
}
fn clear(&mut self) {
self.listing_id.clear();
self.ts_micros.clear();
self.session_date.clear();
self.open.clear();
self.high.clear();
self.low.clear();
self.close.clear();
self.volume.clear();
self.vwap_values.clear();
self.vwap_def_levels.clear();
self.currency_ids.clear();
self.currency_interner.clear();
self.source_ids.clear();
self.source_interner.clear();
self.known_at_micros.clear();
}
}
static DATASET_LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new();
static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0);
fn dataset_mutex(bars_dir: &Path) -> Arc<Mutex<()>> {
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<Self, ParquetBarsError> {
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<PathBuf, ParquetBarsError> {
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,
writer: SerializedFileWriter<BufWriter<File>>,
buf: RowGroupBuffer,
rows_written: usize,
row_groups_written: usize,
}
impl YearWriter {
fn open(
bars_dir: &Path,
year: i32,
run_id: &str,
schema: &TypePtr,
props: &WriterPropertiesPtr,
owned_tmp_paths: &mut Vec<PathBuf>,
) -> Result<Self, ParquetBarsError> {
let year_dir = bars_dir.join(format!("year={year:04}"));
fs::create_dir_all(&year_dir).map_err(|source| ParquetBarsError::Io {
path: year_dir.clone(),
source,
})?;
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 buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file);
let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err(
|source| ParquetBarsError::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<ByteArray>) -> Result<(), ParquetBarsError> {
let row_count = self.buf.len();
if row_count == 0 {
return Ok(());
}
let map_pq = |source: ParquetError| ParquetBarsError::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, &self.tmp_path)?;
// 2. ts (INT64, REQUIRED)
write_i64_col(&mut rg_writer, &self.buf.ts_micros, &self.tmp_path)?;
// 3. session_date (INT32, REQUIRED)
write_i32_col(&mut rg_writer, &self.buf.session_date, &self.tmp_path)?;
// 4. open (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.open, None, &self.tmp_path)?;
// 5. high (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.high, None, &self.tmp_path)?;
// 6. low (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.low, None, &self.tmp_path)?;
// 7. close (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.close, None, &self.tmp_path)?;
// 8. volume (DOUBLE, REQUIRED)
write_f64_col(&mut rg_writer, &self.buf.volume, None, &self.tmp_path)?;
// 9. vwap (DOUBLE, OPTIONAL)
write_f64_col(
&mut rg_writer,
&self.buf.vwap_values,
Some(&self.buf.vwap_def_levels),
&self.tmp_path,
)?;
// 10. currency (BYTE_ARRAY, REQUIRED)
write_interned_str_col(
&mut rg_writer,
&self.buf.currency_ids,
&self.buf.currency_interner,
scratch,
&self.tmp_path,
)?;
// 11. source (BYTE_ARRAY, REQUIRED)
write_interned_str_col(
&mut rg_writer,
&self.buf.source_ids,
&self.buf.source_interner,
scratch,
&self.tmp_path,
)?;
// 12. known_at (INT64, REQUIRED)
write_i64_col(&mut rg_writer, &self.buf.known_at_micros, &self.tmp_path)?;
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<ByteArray>) -> Result<SyncedYearFile, ParquetBarsError> {
self.flush_row_group(scratch)?;
let mut buf_writer = self
.writer
.into_inner()
.map_err(|source| ParquetBarsError::Parquet {
path: self.tmp_path.clone(),
source,
})?;
buf_writer.flush().map_err(|source| ParquetBarsError::Io {
path: self.tmp_path.clone(),
source,
})?;
let file = buf_writer
.into_inner()
.map_err(|err| ParquetBarsError::Io {
path: self.tmp_path.clone(),
source: err.into_error(),
})?;
file.sync_all().map_err(|source| ParquetBarsError::Io {
path: self.tmp_path.clone(),
source,
})?;
let bytes = file
.metadata()
.map_err(|source| ParquetBarsError::Io {
path: self.tmp_path.clone(),
source,
})?
.len();
drop(file);
Ok(SyncedYearFile {
tmp_path: self.tmp_path,
final_path: self.final_path,
rows_written: self.rows_written,
row_groups_written: self.row_groups_written,
bytes,
})
}
}
struct SyncedYearFile {
tmp_path: PathBuf,
final_path: PathBuf,
rows_written: usize,
row_groups_written: usize,
bytes: u64,
}
fn next_column<'a>(
rg_writer: &'a mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter<File>>,
path: &Path,
) -> Result<parquet::file::writer::SerializedColumnWriter<'a>, 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<File>>,
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<File>>,
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<File>>,
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<File>>,
ids: &[u32],
interner: &StringInterner,
scratch: &mut Vec<ByteArray>,
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<PathBuf>,
}
fn rollback_published(published: &[PublishedPartition]) -> Vec<RollbackFailure> {
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],
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
/// Parquet files at `<out_dir>/bars_1d/year=YYYY/part.parquet`.
///
/// # Concurrency & Atomicity
/// 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. 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,
options: Bars1dWriteOptions,
) -> Result<Bars1dWriteStats, ParquetBarsError>
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);
}
let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| {
ParquetBarsError::InvalidZstdLevel {
level: options.zstd_level,
}
})?;
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 {
path: bars_dir.clone(),
source,
})?;
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_with_timeout(&bars_dir, lock_timeout)?;
let run_id = next_run_id();
let mut writers: BTreeMap<i32, YearWriter> = BTreeMap::new();
let mut owned_tmp_paths: Vec<PathBuf> = Vec::new();
let mut scratch: Vec<ByteArray> = Vec::with_capacity(STRING_WRITE_BATCH_ROWS);
let write_result: Result<Vec<(i32, SyncedYearFile)>, ParquetBarsError> = (|| {
let mut prev_key: Option<(i32, i32)> = None;
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))
{
Ordering::Equal => {
return Err(ParquetBarsError::DuplicateKey {
listing_id: row.listing_id,
session_date: row.session_date,
});
}
Ordering::Less => {
return Err(ParquetBarsError::UnsortedInput {
prev_listing_id,
prev_session_date,
listing_id: row.listing_id,
session_date: row.session_date,
});
}
Ordering::Greater => {}
}
}
prev_key = Some((row.listing_id, row.session_date));
let (year, _, _) = epoch_days_to_ymd(row.session_date);
if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) {
return Err(ParquetBarsError::SessionYearOutOfRange {
listing_id: row.listing_id,
session_date: row.session_date,
year,
min_year: MIN_PARQUET_YEAR,
max_year: MAX_PARQUET_YEAR,
});
}
let yw = match writers.entry(year) {
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::btree_map::Entry::Vacant(entry) => {
let opened = YearWriter::open(
&bars_dir,
year,
&run_id,
&schema,
&props,
&mut owned_tmp_paths,
)?;
entry.insert(opened)
}
};
yw.buf.push(row);
if yw.buf.len() == options.row_group_rows {
yw.flush_row_group(&mut scratch)?;
}
}
let mut synced = Vec::with_capacity(writers.len());
let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect();
for (year, yw) in drained {
let file = yw.finish_and_sync(&mut scratch)?;
synced.push((year, file));
}
Ok(synced)
})();
let synced_files = match write_result {
Ok(files) => files,
Err(err) => {
// Drop all open writers before unlinking temporary files owned by this run.
drop(writers);
cleanup_owned_files(&owned_tmp_paths);
return Err(err);
}
};
let mut stats = Bars1dWriteStats::default();
let mut published: Vec<PublishedPartition> = 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() => {
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));
}
}
}
// 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) => {
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) {
// `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 {
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;
stats.bytes_written += file.bytes;
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)
}
#[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::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-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);
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn make_row(
listing_id: i32,
year: i32,
month: u32,
day: u32,
close: f64,
volume: f64,
vwap: Option<f64>,
currency: &'static str,
source: &'static str,
) -> Bars1dParquetRow {
let session_date = ymd_to_epoch_days(year, month, day).expect("valid date");
let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000;
let known_at_micros = ts_micros + 900_000_000;
Bars1dParquetRow {
listing_id,
ts_micros,
session_date,
open: close - 0.5,
high: close + 1.25,
low: close - 1.0,
close,
volume,
vwap,
currency: Cow::Borrowed(currency),
source: Cow::Borrowed(source),
known_at_micros,
}
}
pub(super) fn read_parquet_rows(path: &Path) -> Vec<Bars1dParquetRow> {
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 listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows);
let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows);
let session_date = read_i32_col(rg_reader.get_column_reader(2).unwrap(), num_rows);
let open = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows);
let high = read_req_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows);
let low = read_req_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows);
let close = read_req_f64_col(rg_reader.get_column_reader(6).unwrap(), num_rows);
let volume = read_req_f64_col(rg_reader.get_column_reader(7).unwrap(), num_rows);
let vwap = read_opt_f64_col(rg_reader.get_column_reader(8).unwrap(), num_rows);
let currency = read_str_col(rg_reader.get_column_reader(9).unwrap(), num_rows);
let source = read_str_col(rg_reader.get_column_reader(10).unwrap(), num_rows);
let known_at_micros = read_i64_col(rg_reader.get_column_reader(11).unwrap(), num_rows);
for i in 0..num_rows {
out.push(Bars1dParquetRow {
listing_id: listing_id[i],
ts_micros: ts_micros[i],
session_date: session_date[i],
open: open[i],
high: high[i],
low: low[i],
close: close[i],
volume: volume[i],
vwap: vwap[i],
currency: Cow::Owned(currency[i].clone()),
source: Cow::Owned(source[i].clone()),
known_at_micros: known_at_micros[i],
});
}
}
out
}
fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec<i32> {
let mut values = Vec::with_capacity(expected);
match reader {
ColumnReader::Int32ColumnReader(mut r) => {
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
assert_eq!(records, expected);
}
_ => panic!("expected Int32ColumnReader"),
}
values
}
fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec<i64> {
let mut values = Vec::with_capacity(expected);
match reader {
ColumnReader::Int64ColumnReader(mut r) => {
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
assert_eq!(records, expected);
}
_ => panic!("expected Int64ColumnReader"),
}
values
}
fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec<f64> {
let mut values = Vec::with_capacity(expected);
match reader {
ColumnReader::DoubleColumnReader(mut r) => {
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
assert_eq!(records, expected);
}
_ => panic!("expected DoubleColumnReader"),
}
values
}
fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec<Option<f64>> {
let mut raw_values = Vec::with_capacity(expected);
let mut def_levels = Vec::with_capacity(expected);
match reader {
ColumnReader::DoubleColumnReader(mut r) => {
let (records, _, levels) = r
.read_records(expected, Some(&mut def_levels), None, &mut raw_values)
.unwrap();
assert_eq!(records, expected);
assert_eq!(levels, expected);
}
_ => panic!("expected DoubleColumnReader"),
}
let mut out = Vec::with_capacity(expected);
let mut val_idx = 0usize;
for lvl in def_levels {
if lvl == 1 {
out.push(Some(raw_values[val_idx]));
val_idx += 1;
} else {
out.push(None);
}
}
assert_eq!(val_idx, raw_values.len());
out
}
fn read_str_col(reader: ColumnReader, expected: usize) -> Vec<String> {
let mut values = Vec::with_capacity(expected);
match reader {
ColumnReader::ByteArrayColumnReader(mut r) => {
let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap();
assert_eq!(records, expected);
}
_ => panic!("expected ByteArrayColumnReader"),
}
values
.into_iter()
.map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8"))
.collect()
}
pub(super) fn assert_row_bitwise_eq(actual: &Bars1dParquetRow, expected: &Bars1dParquetRow) {
assert_eq!(actual.listing_id, expected.listing_id);
assert_eq!(actual.ts_micros, expected.ts_micros);
assert_eq!(actual.session_date, expected.session_date);
assert_eq!(actual.open.to_bits(), expected.open.to_bits());
assert_eq!(actual.high.to_bits(), expected.high.to_bits());
assert_eq!(actual.low.to_bits(), expected.low.to_bits());
assert_eq!(actual.close.to_bits(), expected.close.to_bits());
assert_eq!(actual.volume.to_bits(), expected.volume.to_bits());
assert_eq!(
actual.vwap.map(f64::to_bits),
expected.vwap.map(f64::to_bits)
);
assert_eq!(actual.currency, expected.currency);
assert_eq!(actual.source, expected.source);
assert_eq!(actual.known_at_micros, expected.known_at_micros);
}
#[test]
fn round_trip_three_years_preserves_bitwise_values_and_order() {
let tmp = TempDirGuard::new("round-trip");
let rows = vec![
make_row(1, 2022, 6, 15, 100.25, 0.0, None, "USD", "eod_unadj"),
make_row(1, 2023, 3, 10, 112.50, 1_234_567.0, Some(112.42), "USD", "eod_unadj"),
make_row(1, 2024, 11, 1, 145.75, 987_654.0, Some(145.10), "USD", "qm_raw"),
make_row(2, 2022, 12, 30, 12.10, 50_000.0, Some(12.05), "CAD", "eod_unadj"),
make_row(2, 2024, 1, 2, 15.80, 0.0, None, "CAD", "eod_unadj"),
make_row(7, 2023, 7, 4, 42.00, 10_500.0, None, "USD", "ib_live"),
];
let stats =
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
assert_eq!(stats.rows_written, rows.len());
assert_eq!(stats.files_written, 3);
assert_eq!(stats.row_groups_written, 3);
assert!(stats.bytes_written > 0);
assert_eq!(stats.rows_by_year.get(&2022), Some(&2));
assert_eq!(stats.rows_by_year.get(&2023), Some(&2));
assert_eq!(stats.rows_by_year.get(&2024), Some(&2));
for year in [2022, 2023, 2024] {
let path = tmp
.path()
.join(format!("bars_1d/year={year:04}/part.parquet"));
assert!(path.exists(), "expected {}", path.display());
assert!(
!tmp.path()
.join(format!("bars_1d/year={year:04}/part.parquet.tmp"))
.exists()
);
let expected_year_rows: Vec<&Bars1dParquetRow> = rows
.iter()
.filter(|r| epoch_days_to_ymd(r.session_date).0 == year)
.collect();
let actual_year_rows = read_parquet_rows(&path);
assert_eq!(actual_year_rows.len(), expected_year_rows.len());
for (actual, expected) in actual_year_rows.iter().zip(expected_year_rows.iter()) {
assert_row_bitwise_eq(actual, expected);
assert!(actual.volume.is_sign_positive());
assert!(actual.currency.is_ascii());
assert!(actual.source.is_ascii());
}
}
}
#[test]
fn metadata_matches_contract_schema_and_zstd_compression() {
let tmp = TempDirGuard::new("schema");
let rows = vec![
make_row(10, 2024, 5, 20, 55.0, 250_000.0, Some(54.8), "USD", "eod_unadj"),
make_row(10, 2024, 5, 21, 56.0, 300_000.0, None, "CAD", "eod_unadj"),
];
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
let path = tmp.path().join("bars_1d/year=2024/part.parquet");
let file = File::open(&path).unwrap();
let reader = SerializedFileReader::new(file).unwrap();
let file_meta = reader.metadata().file_metadata();
let schema = file_meta.schema_descr();
assert_eq!(schema.name(), "bars_1d");
assert_eq!(schema.num_columns(), 12);
let expected: [(&str, PhysicalType, Repetition, Option<LogicalType>, ConvertedType); 12] = [
(
"listing_id",
PhysicalType::INT32,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"ts",
PhysicalType::INT64,
Repetition::REQUIRED,
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
ConvertedType::TIMESTAMP_MICROS,
),
(
"session_date",
PhysicalType::INT32,
Repetition::REQUIRED,
Some(LogicalType::Date),
ConvertedType::DATE,
),
(
"open",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"high",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"low",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"close",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"volume",
PhysicalType::DOUBLE,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"vwap",
PhysicalType::DOUBLE,
Repetition::OPTIONAL,
None,
ConvertedType::NONE,
),
(
"currency",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"source",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"known_at",
PhysicalType::INT64,
Repetition::REQUIRED,
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
ConvertedType::TIMESTAMP_MICROS,
),
];
for (idx, (name, phys, rep, logical, converted)) in expected.iter().enumerate() {
let col = schema.column(idx);
let field = col.self_type();
assert_eq!(col.name(), *name, "column {idx} name mismatch");
assert_eq!(col.physical_type(), *phys, "column {name} physical type");
assert_eq!(
field.get_basic_info().repetition(),
*rep,
"column {name} repetition"
);
assert_eq!(
field.get_basic_info().logical_type_ref(),
logical.as_ref(),
"column {name} logical type"
);
assert_eq!(
field.get_basic_info().converted_type(),
*converted,
"column {name} converted type"
);
}
assert_eq!(reader.metadata().num_row_groups(), 1);
let rg = reader.metadata().row_group(0);
for col_idx in 0..12 {
let chunk = rg.column(col_idx);
assert!(
matches!(chunk.compression(), Compression::ZSTD(_)),
"column {col_idx} must use ZSTD compression, got {:?}",
chunk.compression()
);
}
}
#[test]
fn partitioning_splits_dec31_and_jan01_and_omits_empty_years() {
let tmp = TempDirGuard::new("partition");
let rows = vec![
make_row(1, 2020, 12, 31, 10.0, 100.0, None, "USD", "eod_unadj"),
make_row(1, 2021, 1, 1, 10.5, 200.0, None, "USD", "eod_unadj"),
make_row(1, 2023, 6, 1, 12.0, 300.0, None, "USD", "eod_unadj"),
];
let stats =
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
assert_eq!(stats.files_written, 3);
assert!(tmp.path().join("bars_1d/year=2020/part.parquet").exists());
assert!(tmp.path().join("bars_1d/year=2021/part.parquet").exists());
assert!(!tmp.path().join("bars_1d/year=2022").exists());
assert!(tmp.path().join("bars_1d/year=2023/part.parquet").exists());
assert_eq!(
read_parquet_rows(&tmp.path().join("bars_1d/year=2020/part.parquet")).len(),
1
);
assert_eq!(
read_parquet_rows(&tmp.path().join("bars_1d/year=2021/part.parquet")).len(),
1
);
assert_eq!(
read_parquet_rows(&tmp.path().join("bars_1d/year=2023/part.parquet")).len(),
1
);
}
#[test]
fn row_groups_split_exact_sizes() {
let tmp = TempDirGuard::new("row-groups");
let base_date = ymd_to_epoch_days(2024, 1, 2).unwrap();
let mut rows = Vec::with_capacity(2_500);
for listing_id in 1..=25 {
for day_offset in 0..100 {
let session_date = base_date + day_offset;
let ts_micros = i64::from(session_date) * 86_400_000_000;
rows.push(Bars1dParquetRow {
listing_id,
ts_micros,
session_date,
open: 20.0,
high: 21.0,
low: 19.5,
close: 20.5,
volume: 10_000.0,
vwap: Some(20.25),
currency: Cow::Borrowed("USD"),
source: Cow::Borrowed("eod_unadj"),
known_at_micros: ts_micros,
});
}
}
let options = Bars1dWriteOptions {
row_group_rows: 1_000,
zstd_level: DEFAULT_ZSTD_LEVEL,
};
let stats = write_bars_1d_dataset(tmp.path(), &rows, options).unwrap();
assert_eq!(stats.rows_written, 2_500);
assert_eq!(stats.files_written, 1);
assert_eq!(stats.row_groups_written, 3);
let file = File::open(tmp.path().join("bars_1d/year=2024/part.parquet")).unwrap();
let reader = SerializedFileReader::new(file).unwrap();
assert_eq!(reader.metadata().num_row_groups(), 3);
assert_eq!(reader.metadata().row_group(0).num_rows(), 1_000);
assert_eq!(reader.metadata().row_group(1).num_rows(), 1_000);
assert_eq!(reader.metadata().row_group(2).num_rows(), 500);
}
#[test]
fn empty_input_returns_zero_stats_and_creates_nothing() {
let tmp = TempDirGuard::new("empty");
let empty: Vec<Bars1dParquetRow> = Vec::new();
let stats =
write_bars_1d_dataset(tmp.path(), &empty, Bars1dWriteOptions::default()).unwrap();
assert_eq!(stats, Bars1dWriteStats::default());
assert!(!tmp.path().join("bars_1d").exists());
}
#[test]
fn writing_same_rows_twice_is_byte_identical() {
let tmp_a = TempDirGuard::new("det-a");
let tmp_b = TempDirGuard::new("det-b");
let rows = vec![
make_row(1, 2023, 2, 1, 10.0, 1_000.0, Some(10.0), "USD", "eod_unadj"),
make_row(1, 2024, 2, 1, 11.0, 2_000.0, None, "USD", "eod_unadj"),
make_row(2, 2023, 2, 1, 20.0, 3_000.0, Some(19.9), "CAD", "qm_raw"),
make_row(2, 2024, 2, 1, 21.0, 4_000.0, None, "CAD", "qm_raw"),
];
let stats_a =
write_bars_1d_dataset(tmp_a.path(), &rows, Bars1dWriteOptions::default()).unwrap();
let stats_b =
write_bars_1d_dataset(tmp_b.path(), &rows, Bars1dWriteOptions::default()).unwrap();
assert_eq!(stats_a, stats_b);
for year in [2023, 2024] {
let bytes_a =
fs::read(tmp_a.path().join(format!("bars_1d/year={year:04}/part.parquet")))
.unwrap();
let bytes_b =
fs::read(tmp_b.path().join(format!("bars_1d/year={year:04}/part.parquet")))
.unwrap();
assert_eq!(bytes_a, bytes_b, "year {year} parquet bytes must match");
}
}
#[test]
fn failure_modes_return_typed_errors_and_preserve_existing_files() {
let tmp = TempDirGuard::new("failures");
// Seed a valid existing 2024 partition.
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 existing_tmp = tmp.path().join("bars_1d/year=2024/part.parquet.tmp");
let original_bytes = fs::read(&existing_path).unwrap();
// 1. Invalid row_group_rows = 0
let err = write_bars_1d_dataset(
tmp.path(),
&initial,
Bars1dWriteOptions {
row_group_rows: 0,
zstd_level: DEFAULT_ZSTD_LEVEL,
},
)
.unwrap_err();
assert!(matches!(err, ParquetBarsError::InvalidRowGroupRows));
assert!(!existing_tmp.exists());
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// 2. Invalid Zstd level
let err = write_bars_1d_dataset(
tmp.path(),
&initial,
Bars1dWriteOptions {
row_group_rows: 100,
zstd_level: 99,
},
)
.unwrap_err();
assert!(matches!(
err,
ParquetBarsError::InvalidZstdLevel { level: 99 }
));
assert!(!existing_tmp.exists());
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// 3. Unsorted input (after writing a valid row into 2024)
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 {
prev_listing_id: 2,
listing_id: 1,
..
}
));
assert!(!existing_tmp.exists());
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// 4. Duplicate (listing_id, session_date)
let dup = vec![
make_row(1, 2024, 6, 3, 50.0, 100.0, None, "USD", "eod_unadj"),
make_row(1, 2024, 6, 3, 50.0, 100.0, None, "USD", "eod_unadj"),
];
let err =
write_bars_1d_dataset(tmp.path(), &dup, Bars1dWriteOptions::default()).unwrap_err();
assert!(matches!(
err,
ParquetBarsError::DuplicateKey { listing_id: 1, .. }
));
assert!(!existing_tmp.exists());
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// 5. Session year out of range (< 1900 and > 2200)
let too_old = vec![
make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"),
make_row(2, 1899, 12, 31, 10.0, 100.0, None, "USD", "eod_unadj"),
];
let err = write_bars_1d_dataset(tmp.path(), &too_old, Bars1dWriteOptions::default())
.unwrap_err();
assert!(matches!(
err,
ParquetBarsError::SessionYearOutOfRange {
listing_id: 2,
year: 1899,
min_year: MIN_PARQUET_YEAR,
max_year: MAX_PARQUET_YEAR,
..
}
));
assert!(!existing_tmp.exists());
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
let too_new = vec![make_row(
3,
2201,
1,
1,
10.0,
100.0,
None,
"USD",
"eod_unadj",
)];
let err = write_bars_1d_dataset(tmp.path(), &too_new, Bars1dWriteOptions::default())
.unwrap_err();
assert!(matches!(
err,
ParquetBarsError::SessionYearOutOfRange {
listing_id: 3,
year: 2201,
..
}
));
assert!(!existing_tmp.exists());
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// 6. Unwritable out_dir (path is an existing regular file)
let blocker_file = tmp.path().join("not-a-dir");
fs::write(&blocker_file, b"file-content").unwrap();
let err =
write_bars_1d_dataset(&blocker_file, &initial, Bars1dWriteOptions::default())
.unwrap_err();
assert!(matches!(err, ParquetBarsError::Io { .. }));
assert_eq!(fs::read(&blocker_file).unwrap(), b"file-content");
assert_eq!(fs::read(&existing_path).unwrap(), original_bytes);
// 7. Mid-stream failure after flushing a full row group across multiple years
let multi_year_fail = vec![
make_row(1, 2023, 6, 1, 10.0, 100.0, None, "USD", "eod_unadj"),
make_row(1, 2024, 6, 1, 11.0, 200.0, None, "USD", "eod_unadj"),
make_row(2, 2024, 6, 1, 12.0, 300.0, None, "USD", "eod_unadj"),
// Out-of-order after year=2024 already flushed a 2-row group to part.parquet.tmp
make_row(2, 2023, 6, 1, 13.0, 400.0, None, "USD", "eod_unadj"),
];
let err = write_bars_1d_dataset(
tmp.path(),
&multi_year_fail,
Bars1dWriteOptions {
row_group_rows: 2,
zstd_level: DEFAULT_ZSTD_LEVEL,
},
)
.unwrap_err();
assert!(matches!(err, ParquetBarsError::UnsortedInput { .. }));
assert!(!tmp.path().join("bars_1d/year=2023/part.parquet.tmp").exists());
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"));
}
pub(super) 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<Bars1dParquetRow>,
seen: usize,
on_second: Option<Box<dyn FnOnce() + Send>>,
on_end: Option<Box<dyn FnOnce() + Send>>,
}
impl Iterator for SignalingIter {
type Item = Bars1dParquetRow;
fn next(&mut self) -> Option<Self::Item> {
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]
fn string_interner_handles_more_than_linear_limit_distinct_values() {
let tmp = TempDirGuard::new("many-strings");
let currencies = [
"USD", "CAD", "EUR", "GBP", "JPY", "CHF", "AUD", "NZD", "SEK", "NOK", "HKD", "SGD",
];
let mut rows = Vec::with_capacity(currencies.len() * 2);
for (i, &ccy) in currencies.iter().enumerate() {
rows.push(make_row(
(i + 1) as i32,
2024,
3,
1,
10.0 + i as f64,
1_000.0,
None,
ccy,
"eod_unadj",
));
rows.push(make_row(
(i + 1) as i32,
2024,
3,
2,
11.0 + i as f64,
2_000.0,
Some(10.5 + i as f64),
ccy,
"qm_raw",
));
}
let stats =
write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap();
assert_eq!(stats.rows_written, rows.len());
let read_back = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet"));
assert_eq!(read_back.len(), rows.len());
for (actual, expected) in read_back.iter().zip(rows.iter()) {
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);
}
}
#[cfg(test)]
#[path = "parquet_bars_tests.rs"]
mod edge_case_tests;