1310 lines
43 KiB
Rust
1310 lines
43 KiB
Rust
//! Streaming, atomic Zstd Parquet writer for `fx_1d`.
|
|
//!
|
|
//! Writes `<out_dir>/fx_1d/part.parquet` matching the 9-column contract schema in
|
|
//! `design/DATA-CONTRACTS.md` (§3A):
|
|
//!
|
|
//! 1. `pair` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
|
|
//! 2. `session_date` (`INT32`, `REQUIRED`, `DATE`)
|
|
//! 3. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
|
|
//! 4. `open` (`DOUBLE`, `REQUIRED`)
|
|
//! 5. `high` (`DOUBLE`, `REQUIRED`)
|
|
//! 6. `low` (`DOUBLE`, `REQUIRED`)
|
|
//! 7. `close` (`DOUBLE`, `REQUIRED`)
|
|
//! 8. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
|
|
//! 9. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
|
|
|
|
use std::borrow::{Borrow, Cow};
|
|
use std::cmp::Ordering;
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
use std::fs::{self, File};
|
|
use std::io::{self, BufWriter, Write};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel};
|
|
use parquet::data_type::ByteArray;
|
|
use parquet::errors::ParquetError;
|
|
use parquet::file::properties::{WriterProperties, WriterPropertiesPtr};
|
|
use parquet::file::writer::SerializedFileWriter;
|
|
use parquet::schema::types::{ColumnPath, Type, TypePtr};
|
|
|
|
use crate::fx::Fx1dRow;
|
|
use crate::parquet_publish::{
|
|
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};
|
|
|
|
const MICROS_PER_DAY: i128 = 86_400_000_000;
|
|
|
|
/// Single `fx_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Fx1dParquetRow {
|
|
pub pair: Cow<'static, str>,
|
|
pub session_date: i32,
|
|
pub ts_micros: i64,
|
|
pub open: f64,
|
|
pub high: f64,
|
|
pub low: f64,
|
|
pub close: f64,
|
|
pub source: Cow<'static, str>,
|
|
pub known_at_micros: i64,
|
|
}
|
|
|
|
impl Fx1dParquetRow {
|
|
/// Builds a [`Fx1dParquetRow`] from a curated [`Fx1dRow`] and caller-supplied UTC microsecond
|
|
/// timestamps without heap allocation.
|
|
#[inline]
|
|
pub fn from_fx_row(row: &Fx1dRow, ts_micros: i64, known_at_micros: i64) -> Self {
|
|
Self {
|
|
pair: Cow::Borrowed(row.pair),
|
|
session_date: row.session_date,
|
|
ts_micros,
|
|
open: row.open,
|
|
high: row.high,
|
|
low: row.low,
|
|
close: row.close,
|
|
source: Cow::Borrowed(row.source.as_str()),
|
|
known_at_micros,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Configuration for [`write_fx_1d_dataset`].
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Fx1dWriteOptions {
|
|
pub row_group_rows: usize,
|
|
pub zstd_level: i32,
|
|
}
|
|
|
|
impl Default for Fx1dWriteOptions {
|
|
fn default() -> Self {
|
|
Self {
|
|
row_group_rows: DEFAULT_ROW_GROUP_ROWS,
|
|
zstd_level: DEFAULT_ZSTD_LEVEL,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Accounting summary returned by [`write_fx_1d_dataset`].
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct Fx1dWriteStats {
|
|
pub rows_written: usize,
|
|
pub files_written: usize,
|
|
pub row_groups_written: usize,
|
|
pub bytes_written: u64,
|
|
}
|
|
|
|
/// Typed error returned by [`write_fx_1d_dataset`].
|
|
#[derive(Debug)]
|
|
pub enum ParquetFxError {
|
|
InvalidRowGroupRows,
|
|
InvalidZstdLevel {
|
|
level: i32,
|
|
},
|
|
UnsortedInput {
|
|
prev_pair: String,
|
|
prev_session_date: i32,
|
|
pair: String,
|
|
session_date: i32,
|
|
},
|
|
DuplicateKey {
|
|
pair: String,
|
|
session_date: i32,
|
|
},
|
|
EmptyPair {
|
|
session_date: i32,
|
|
},
|
|
EmptySource {
|
|
pair: String,
|
|
session_date: i32,
|
|
},
|
|
InvalidOhlc {
|
|
pair: String,
|
|
session_date: i32,
|
|
open: f64,
|
|
high: f64,
|
|
low: f64,
|
|
close: f64,
|
|
},
|
|
InconsistentOhlc {
|
|
pair: String,
|
|
session_date: i32,
|
|
open: f64,
|
|
high: f64,
|
|
low: f64,
|
|
close: f64,
|
|
},
|
|
TsOutsideSessionDate {
|
|
pair: String,
|
|
session_date: i32,
|
|
ts_micros: i64,
|
|
},
|
|
KnownAtBeforeTs {
|
|
pair: String,
|
|
session_date: i32,
|
|
ts_micros: i64,
|
|
known_at_micros: i64,
|
|
},
|
|
LockTimeout {
|
|
path: PathBuf,
|
|
waited: Duration,
|
|
},
|
|
RollbackFailed {
|
|
cause: Box<ParquetFxError>,
|
|
failures: Vec<RollbackFailure>,
|
|
},
|
|
Io {
|
|
path: PathBuf,
|
|
source: io::Error,
|
|
},
|
|
Parquet {
|
|
path: PathBuf,
|
|
source: ParquetError,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for ParquetFxError {
|
|
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_pair,
|
|
prev_session_date,
|
|
pair,
|
|
session_date,
|
|
} => write!(
|
|
f,
|
|
"unsorted input: ({pair}, {session_date}) follows ({prev_pair}, {prev_session_date})"
|
|
),
|
|
Self::DuplicateKey { pair, session_date } => {
|
|
write!(f, "duplicate (pair, session_date) key: ({pair}, {session_date})")
|
|
}
|
|
Self::EmptyPair { session_date } => {
|
|
write!(f, "empty pair for session_date {session_date}: must be non-empty")
|
|
}
|
|
Self::EmptySource { pair, session_date } => {
|
|
write!(f, "empty source for ({pair}, {session_date}): must be non-empty")
|
|
}
|
|
Self::InvalidOhlc {
|
|
pair,
|
|
session_date,
|
|
open,
|
|
high,
|
|
low,
|
|
close,
|
|
} => write!(
|
|
f,
|
|
"invalid OHLC ({open}, {high}, {low}, {close}) for ({pair}, {session_date}): all values must be finite and > 0"
|
|
),
|
|
Self::InconsistentOhlc {
|
|
pair,
|
|
session_date,
|
|
open,
|
|
high,
|
|
low,
|
|
close,
|
|
} => write!(
|
|
f,
|
|
"inconsistent OHLC ({open}, {high}, {low}, {close}) for ({pair}, {session_date}): must satisfy high >= low and open, close in [low, high]"
|
|
),
|
|
Self::TsOutsideSessionDate {
|
|
pair,
|
|
session_date,
|
|
ts_micros,
|
|
} => write!(
|
|
f,
|
|
"ts {ts_micros} is outside UTC day of session_date {session_date} for pair '{pair}'"
|
|
),
|
|
Self::KnownAtBeforeTs {
|
|
pair,
|
|
session_date,
|
|
ts_micros,
|
|
known_at_micros,
|
|
} => write!(
|
|
f,
|
|
"known_at {known_at_micros} precedes ts {ts_micros} for ({pair}, {session_date})"
|
|
),
|
|
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 ParquetFxError {
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
match self {
|
|
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
|
|
Self::Io { source, .. } => Some(source),
|
|
Self::Parquet { source, .. } => Some(source),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<PublishIoError> for ParquetFxError {
|
|
fn from(err: PublishIoError) -> Self {
|
|
match err {
|
|
PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited },
|
|
PublishIoError::Io { path, source } => Self::Io { path, source },
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Builds the exact 9-column Parquet schema for `fx_1d` per `design/DATA-CONTRACTS.md` (§3A).
|
|
pub fn fx_1d_parquet_schema() -> Result<TypePtr, ParquetError> {
|
|
let fields: Vec<TypePtr> = vec![
|
|
Arc::new(
|
|
Type::primitive_type_builder("pair", PhysicalType::BYTE_ARRAY)
|
|
.with_repetition(Repetition::REQUIRED)
|
|
.with_logical_type(Some(LogicalType::String))
|
|
.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("ts", PhysicalType::INT64)
|
|
.with_repetition(Repetition::REQUIRED)
|
|
.with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS)))
|
|
.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("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("fx_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("pair"), true)
|
|
.set_column_dictionary_enabled(ColumnPath::from("source"), true)
|
|
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
|
|
.build(),
|
|
)
|
|
}
|
|
|
|
#[inline]
|
|
fn is_valid_rate(rate: f64) -> bool {
|
|
rate.is_finite() && rate > 0.0
|
|
}
|
|
|
|
#[inline]
|
|
fn validate_row(row: &Fx1dParquetRow) -> Result<(), ParquetFxError> {
|
|
if row.pair.trim().is_empty() {
|
|
return Err(ParquetFxError::EmptyPair {
|
|
session_date: row.session_date,
|
|
});
|
|
}
|
|
if row.source.trim().is_empty() {
|
|
return Err(ParquetFxError::EmptySource {
|
|
pair: row.pair.as_ref().to_owned(),
|
|
session_date: row.session_date,
|
|
});
|
|
}
|
|
if !is_valid_rate(row.open)
|
|
|| !is_valid_rate(row.high)
|
|
|| !is_valid_rate(row.low)
|
|
|| !is_valid_rate(row.close)
|
|
{
|
|
return Err(ParquetFxError::InvalidOhlc {
|
|
pair: row.pair.as_ref().to_owned(),
|
|
session_date: row.session_date,
|
|
open: row.open,
|
|
high: row.high,
|
|
low: row.low,
|
|
close: row.close,
|
|
});
|
|
}
|
|
if row.high < row.low
|
|
|| row.open < row.low
|
|
|| row.open > row.high
|
|
|| row.close < row.low
|
|
|| row.close > row.high
|
|
{
|
|
return Err(ParquetFxError::InconsistentOhlc {
|
|
pair: row.pair.as_ref().to_owned(),
|
|
session_date: row.session_date,
|
|
open: row.open,
|
|
high: row.high,
|
|
low: row.low,
|
|
close: row.close,
|
|
});
|
|
}
|
|
let day_start = i128::from(row.session_date) * MICROS_PER_DAY;
|
|
let day_end = day_start + MICROS_PER_DAY;
|
|
let ts = i128::from(row.ts_micros);
|
|
if ts < day_start || ts >= day_end {
|
|
return Err(ParquetFxError::TsOutsideSessionDate {
|
|
pair: row.pair.as_ref().to_owned(),
|
|
session_date: row.session_date,
|
|
ts_micros: row.ts_micros,
|
|
});
|
|
}
|
|
if row.known_at_micros < row.ts_micros {
|
|
return Err(ParquetFxError::KnownAtBeforeTs {
|
|
pair: row.pair.as_ref().to_owned(),
|
|
session_date: row.session_date,
|
|
ts_micros: row.ts_micros,
|
|
known_at_micros: row.known_at_micros,
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct RowGroupBuffer {
|
|
pair_ids: Vec<u32>,
|
|
pair_interner: StringInterner,
|
|
session_date: Vec<i32>,
|
|
ts_micros: Vec<i64>,
|
|
open: Vec<f64>,
|
|
high: Vec<f64>,
|
|
low: Vec<f64>,
|
|
close: Vec<f64>,
|
|
source_ids: Vec<u32>,
|
|
source_interner: StringInterner,
|
|
known_at_micros: Vec<i64>,
|
|
}
|
|
|
|
impl RowGroupBuffer {
|
|
#[inline]
|
|
fn len(&self) -> usize {
|
|
self.session_date.len()
|
|
}
|
|
|
|
fn push(&mut self, row: &Fx1dParquetRow) {
|
|
let pair_id = self.pair_interner.intern(row.pair.as_ref());
|
|
self.pair_ids.push(pair_id);
|
|
self.session_date.push(row.session_date);
|
|
self.ts_micros.push(row.ts_micros);
|
|
self.open.push(row.open);
|
|
self.high.push(row.high);
|
|
self.low.push(row.low);
|
|
self.close.push(row.close);
|
|
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.pair_ids.clear();
|
|
self.pair_interner.clear();
|
|
self.session_date.clear();
|
|
self.ts_micros.clear();
|
|
self.open.clear();
|
|
self.high.clear();
|
|
self.low.clear();
|
|
self.close.clear();
|
|
self.source_ids.clear();
|
|
self.source_interner.clear();
|
|
self.known_at_micros.clear();
|
|
}
|
|
}
|
|
|
|
struct Fx1dFileWriter {
|
|
tmp_path: PathBuf,
|
|
final_path: PathBuf,
|
|
writer: SerializedFileWriter<BufWriter<File>>,
|
|
buf: RowGroupBuffer,
|
|
rows_written: usize,
|
|
row_groups_written: usize,
|
|
}
|
|
|
|
impl Fx1dFileWriter {
|
|
fn from_file(
|
|
tmp_path: PathBuf,
|
|
final_path: PathBuf,
|
|
file: File,
|
|
schema: &TypePtr,
|
|
props: &WriterPropertiesPtr,
|
|
) -> Result<Self, ParquetFxError> {
|
|
let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file);
|
|
let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err(
|
|
|source| ParquetFxError::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<(), ParquetFxError> {
|
|
let row_count = self.buf.len();
|
|
if row_count == 0 {
|
|
return Ok(());
|
|
}
|
|
|
|
let map_pq = |source: ParquetError| ParquetFxError::Parquet {
|
|
path: self.tmp_path.clone(),
|
|
source,
|
|
};
|
|
|
|
let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?;
|
|
|
|
// 1. pair (BYTE_ARRAY, REQUIRED, STRING)
|
|
write_interned_str_col(
|
|
&mut rg_writer,
|
|
&self.buf.pair_ids,
|
|
&self.buf.pair_interner,
|
|
scratch,
|
|
)
|
|
.map_err(map_pq)?;
|
|
// 2. session_date (INT32, REQUIRED, DATE)
|
|
write_i32_col(&mut rg_writer, &self.buf.session_date).map_err(map_pq)?;
|
|
// 3. ts (INT64, REQUIRED, TIMESTAMP MICROS UTC)
|
|
write_i64_col(&mut rg_writer, &self.buf.ts_micros).map_err(map_pq)?;
|
|
// 4. open (DOUBLE, REQUIRED)
|
|
write_f64_col(&mut rg_writer, &self.buf.open, None).map_err(map_pq)?;
|
|
// 5. high (DOUBLE, REQUIRED)
|
|
write_f64_col(&mut rg_writer, &self.buf.high, None).map_err(map_pq)?;
|
|
// 6. low (DOUBLE, REQUIRED)
|
|
write_f64_col(&mut rg_writer, &self.buf.low, None).map_err(map_pq)?;
|
|
// 7. close (DOUBLE, REQUIRED)
|
|
write_f64_col(&mut rg_writer, &self.buf.close, None).map_err(map_pq)?;
|
|
// 8. source (BYTE_ARRAY, REQUIRED, STRING)
|
|
write_interned_str_col(
|
|
&mut rg_writer,
|
|
&self.buf.source_ids,
|
|
&self.buf.source_interner,
|
|
scratch,
|
|
)
|
|
.map_err(map_pq)?;
|
|
// 9. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC)
|
|
write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?;
|
|
|
|
rg_writer.close().map_err(map_pq)?;
|
|
|
|
self.rows_written += row_count;
|
|
self.row_groups_written += 1;
|
|
self.buf.clear();
|
|
Ok(())
|
|
}
|
|
|
|
fn finish_and_sync(
|
|
mut self,
|
|
scratch: &mut Vec<ByteArray>,
|
|
) -> Result<SyncedFx1dFile, ParquetFxError> {
|
|
self.flush_row_group(scratch)?;
|
|
|
|
let mut buf_writer =
|
|
self.writer
|
|
.into_inner()
|
|
.map_err(|source| ParquetFxError::Parquet {
|
|
path: self.tmp_path.clone(),
|
|
source,
|
|
})?;
|
|
buf_writer.flush().map_err(|source| ParquetFxError::Io {
|
|
path: self.tmp_path.clone(),
|
|
source,
|
|
})?;
|
|
let file = buf_writer
|
|
.into_inner()
|
|
.map_err(|err| ParquetFxError::Io {
|
|
path: self.tmp_path.clone(),
|
|
source: err.into_error(),
|
|
})?;
|
|
file.sync_all().map_err(|source| ParquetFxError::Io {
|
|
path: self.tmp_path.clone(),
|
|
source,
|
|
})?;
|
|
let bytes = file
|
|
.metadata()
|
|
.map_err(|source| ParquetFxError::Io {
|
|
path: self.tmp_path.clone(),
|
|
source,
|
|
})?
|
|
.len();
|
|
drop(file);
|
|
|
|
Ok(SyncedFx1dFile {
|
|
tmp_path: self.tmp_path,
|
|
final_path: self.final_path,
|
|
rows_written: self.rows_written,
|
|
row_groups_written: self.row_groups_written,
|
|
bytes,
|
|
})
|
|
}
|
|
}
|
|
|
|
struct SyncedFx1dFile {
|
|
tmp_path: PathBuf,
|
|
final_path: PathBuf,
|
|
rows_written: usize,
|
|
row_groups_written: usize,
|
|
bytes: u64,
|
|
}
|
|
|
|
/// Streams strictly ascending `(pair, session_date)` rows into a single Zstd Parquet file
|
|
/// at `<out_dir>/fx_1d/part.parquet`.
|
|
///
|
|
/// # Empty Input
|
|
/// Empty input returns `Ok(Fx1dWriteStats::default())` without creating `<out_dir>/fx_1d`
|
|
/// and without modifying or removing any pre-existing `part.parquet`.
|
|
///
|
|
/// # Concurrency & Atomicity
|
|
/// Concurrent writers targeting the same `<out_dir>/fx_1d` directory are serialized via an
|
|
/// in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. The file is
|
|
/// written to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flushed,
|
|
/// and `sync_all`'d before publication. If a pre-existing `part.parquet` regular file exists,
|
|
/// a live-preserving backup (`part.parquet.<run>.bak`) is created via hard link (or exclusive
|
|
/// copy fallback) so readers never observe a missing `part.parquet` before replacement by a
|
|
/// single atomic `rename`. On any error, the writer is dropped, any backup created by this run
|
|
/// is cleaned up (reporting cleanup failures via [`ParquetFxError::RollbackFailed`]), and
|
|
/// only staging files owned by this run are unlinked.
|
|
pub fn write_fx_1d_dataset<P, I, R>(
|
|
out_dir: P,
|
|
rows: I,
|
|
options: Fx1dWriteOptions,
|
|
) -> Result<Fx1dWriteStats, ParquetFxError>
|
|
where
|
|
P: AsRef<Path>,
|
|
I: IntoIterator<Item = R>,
|
|
R: Borrow<Fx1dParquetRow>,
|
|
{
|
|
write_fx_1d_dataset_with_hooks(
|
|
out_dir,
|
|
rows,
|
|
options,
|
|
DEFAULT_LOCK_TIMEOUT,
|
|
|_, _| {},
|
|
|path| fs::remove_file(path),
|
|
)
|
|
}
|
|
|
|
fn write_fx_1d_dataset_with_hooks<P, I, R, F, Rm>(
|
|
out_dir: P,
|
|
rows: I,
|
|
options: Fx1dWriteOptions,
|
|
lock_timeout: Duration,
|
|
mut on_after_backup: F,
|
|
mut remove_backup: Rm,
|
|
) -> Result<Fx1dWriteStats, ParquetFxError>
|
|
where
|
|
P: AsRef<Path>,
|
|
I: IntoIterator<Item = R>,
|
|
R: Borrow<Fx1dParquetRow>,
|
|
F: FnMut(&Path, Option<&Path>),
|
|
Rm: FnMut(&Path) -> io::Result<()>,
|
|
{
|
|
if options.row_group_rows == 0 {
|
|
return Err(ParquetFxError::InvalidRowGroupRows);
|
|
}
|
|
let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| {
|
|
ParquetFxError::InvalidZstdLevel {
|
|
level: options.zstd_level,
|
|
}
|
|
})?;
|
|
|
|
let mut row_iter = rows.into_iter();
|
|
let Some(first_item) = row_iter.next() else {
|
|
return Ok(Fx1dWriteStats::default());
|
|
};
|
|
validate_row(first_item.borrow())?;
|
|
|
|
let out_dir = out_dir.as_ref();
|
|
let fx_dir = out_dir.join("fx_1d");
|
|
let schema = fx_1d_parquet_schema().map_err(|source| ParquetFxError::Parquet {
|
|
path: fx_dir.clone(),
|
|
source,
|
|
})?;
|
|
let props = build_writer_properties(zstd_level);
|
|
|
|
fs::create_dir_all(&fx_dir).map_err(|source| ParquetFxError::Io {
|
|
path: fx_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(&fx_dir);
|
|
let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner());
|
|
let _file_lock = DatasetFileLock::acquire_with_timeout(&fx_dir, lock_timeout)?;
|
|
|
|
let run_id = next_run_id();
|
|
let (tmp_path, tmp_file) = create_exclusive_tmp_file(&fx_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(Fx1dFileWriter::from_file(
|
|
tmp_path,
|
|
fx_dir.join("part.parquet"),
|
|
tmp_file,
|
|
&schema,
|
|
&props,
|
|
)?);
|
|
|
|
let synced = {
|
|
let mut has_prev = false;
|
|
let mut prev_pair = String::new();
|
|
let mut prev_session_date = 0i32;
|
|
let writer = file_writer.as_mut().expect("writer initialized");
|
|
|
|
for item in std::iter::once(first_item).chain(row_iter) {
|
|
let row = item.borrow();
|
|
// Validate row fields before checking sort order so e.g. an empty pair
|
|
// is reported as EmptyPair rather than UnsortedInput.
|
|
validate_row(row)?;
|
|
let pair = row.pair.as_ref();
|
|
if has_prev {
|
|
match (pair, row.session_date).cmp(&(prev_pair.as_str(), prev_session_date)) {
|
|
Ordering::Equal => {
|
|
return Err(ParquetFxError::DuplicateKey {
|
|
pair: pair.to_owned(),
|
|
session_date: row.session_date,
|
|
});
|
|
}
|
|
Ordering::Less => {
|
|
return Err(ParquetFxError::UnsortedInput {
|
|
prev_pair,
|
|
prev_session_date,
|
|
pair: pair.to_owned(),
|
|
session_date: row.session_date,
|
|
});
|
|
}
|
|
Ordering::Greater => {}
|
|
}
|
|
}
|
|
if !has_prev || pair != prev_pair.as_str() {
|
|
prev_pair.clear();
|
|
prev_pair.push_str(pair);
|
|
}
|
|
prev_session_date = row.session_date;
|
|
has_prev = true;
|
|
|
|
writer.buf.push(row);
|
|
if writer.buf.len() == options.row_group_rows {
|
|
writer.flush_row_group(&mut scratch)?;
|
|
}
|
|
}
|
|
|
|
let writer = file_writer.take().expect("writer still present");
|
|
writer.finish_and_sync(&mut scratch)?
|
|
};
|
|
|
|
let backup_path = match fs::symlink_metadata(&synced.final_path) {
|
|
Ok(meta) if !meta.is_dir() => {
|
|
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) => {
|
|
return Err(ParquetFxError::Io {
|
|
path: synced.final_path,
|
|
source,
|
|
});
|
|
}
|
|
};
|
|
|
|
on_after_backup(&synced.final_path, backup_path.as_deref());
|
|
|
|
if let Err(source) = fs::rename(&synced.tmp_path, &synced.final_path) {
|
|
// `synced.final_path` was never moved during backup creation, so it remains intact;
|
|
// remove the backup created for this run. `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(),
|
|
backup_path: Some(bak),
|
|
source: remove_err,
|
|
})
|
|
});
|
|
let cause = ParquetFxError::Io {
|
|
path: synced.final_path,
|
|
source,
|
|
};
|
|
return match backup_remove_failure {
|
|
Some(failure) => Err(ParquetFxError::RollbackFailed {
|
|
cause: Box::new(cause),
|
|
failures: vec![failure],
|
|
}),
|
|
None => Err(cause),
|
|
};
|
|
}
|
|
|
|
staging_guard.disarm();
|
|
|
|
if let Some(bak) = backup_path {
|
|
if let Err(remove_err) = remove_backup(&bak) {
|
|
let cause = ParquetFxError::Io {
|
|
path: bak.clone(),
|
|
source: remove_err,
|
|
};
|
|
return match fs::rename(&bak, &synced.final_path) {
|
|
Ok(()) => Err(cause),
|
|
Err(restore_err) => Err(ParquetFxError::RollbackFailed {
|
|
cause: Box::new(cause),
|
|
failures: vec![RollbackFailure {
|
|
final_path: synced.final_path,
|
|
backup_path: Some(bak),
|
|
source: restore_err,
|
|
}],
|
|
}),
|
|
};
|
|
}
|
|
}
|
|
|
|
Ok(Fx1dWriteStats {
|
|
rows_written: synced.rows_written,
|
|
files_written: 1,
|
|
row_groups_written: synced.row_groups_written,
|
|
bytes_written: synced.bytes,
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
|
|
|
use parquet::basic::ConvertedType;
|
|
use parquet::column::reader::ColumnReader;
|
|
use parquet::file::reader::{FileReader, SerializedFileReader};
|
|
|
|
use super::*;
|
|
use crate::fx::{build_fx_1d, FxDailyBar, FxSource, FX_PAIR_USDCAD};
|
|
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-fx-test-{label}-{pid}-{seq}"));
|
|
let _ = fs::remove_dir_all(&path);
|
|
fs::create_dir_all(&path).expect("create test temp dir");
|
|
Self { path }
|
|
}
|
|
|
|
pub(super) fn path(&self) -> &Path {
|
|
&self.path
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDirGuard {
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
pub(super) fn day(y: i32, m: u32, d: u32) -> i32 {
|
|
ymd_to_epoch_days(y, m, d).expect("valid date")
|
|
}
|
|
|
|
pub(super) fn close_ts_micros(session_date: i32) -> i64 {
|
|
i64::from(session_date) * 86_400_000_000 + 22 * 3_600_000_000
|
|
}
|
|
|
|
pub(super) fn make_row(
|
|
pair: &'static str,
|
|
session_date: i32,
|
|
open: f64,
|
|
high: f64,
|
|
low: f64,
|
|
close: f64,
|
|
source: FxSource,
|
|
) -> Fx1dParquetRow {
|
|
let ts_micros = close_ts_micros(session_date);
|
|
Fx1dParquetRow {
|
|
pair: Cow::Borrowed(pair),
|
|
session_date,
|
|
ts_micros,
|
|
open,
|
|
high,
|
|
low,
|
|
close,
|
|
source: Cow::Borrowed(source.as_str()),
|
|
known_at_micros: ts_micros + 900_000_000,
|
|
}
|
|
}
|
|
|
|
pub(super) fn read_parquet_rows(path: &Path) -> Vec<Fx1dParquetRow> {
|
|
let file = File::open(path).expect("open parquet file");
|
|
let reader = SerializedFileReader::new(file).expect("open parquet reader");
|
|
let metadata = reader.metadata();
|
|
let mut out = Vec::new();
|
|
|
|
for rg_idx in 0..metadata.num_row_groups() {
|
|
let rg_reader = reader.get_row_group(rg_idx).expect("row group reader");
|
|
let num_rows = metadata.row_group(rg_idx).num_rows() as usize;
|
|
|
|
let read_i32 = |col_idx: usize| -> Vec<i32> {
|
|
let mut vals = Vec::with_capacity(num_rows);
|
|
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
|
ColumnReader::Int32ColumnReader(mut r) => {
|
|
let (read, _, _) = r
|
|
.read_records(num_rows, None, None, &mut vals)
|
|
.expect("read i32");
|
|
assert_eq!(read, num_rows);
|
|
}
|
|
_ => panic!("expected INT32 column at index {col_idx}"),
|
|
}
|
|
vals
|
|
};
|
|
let read_i64 = |col_idx: usize| -> Vec<i64> {
|
|
let mut vals = Vec::with_capacity(num_rows);
|
|
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
|
ColumnReader::Int64ColumnReader(mut r) => {
|
|
let (read, _, _) = r
|
|
.read_records(num_rows, None, None, &mut vals)
|
|
.expect("read i64");
|
|
assert_eq!(read, num_rows);
|
|
}
|
|
_ => panic!("expected INT64 column at index {col_idx}"),
|
|
}
|
|
vals
|
|
};
|
|
let read_f64 = |col_idx: usize| -> Vec<f64> {
|
|
let mut vals = Vec::with_capacity(num_rows);
|
|
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
|
ColumnReader::DoubleColumnReader(mut r) => {
|
|
let (read, _, _) = r
|
|
.read_records(num_rows, None, None, &mut vals)
|
|
.expect("read f64");
|
|
assert_eq!(read, num_rows);
|
|
}
|
|
_ => panic!("expected DOUBLE column at index {col_idx}"),
|
|
}
|
|
vals
|
|
};
|
|
let read_str = |col_idx: usize| -> Vec<String> {
|
|
let mut vals = Vec::with_capacity(num_rows);
|
|
match rg_reader.get_column_reader(col_idx).expect("col reader") {
|
|
ColumnReader::ByteArrayColumnReader(mut r) => {
|
|
let (read, _, _) = r
|
|
.read_records(num_rows, None, None, &mut vals)
|
|
.expect("read utf8");
|
|
assert_eq!(read, num_rows);
|
|
}
|
|
_ => panic!("expected BYTE_ARRAY column at index {col_idx}"),
|
|
}
|
|
vals.into_iter()
|
|
.map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_owned())
|
|
.collect()
|
|
};
|
|
|
|
let pair = read_str(0);
|
|
let session_date = read_i32(1);
|
|
let ts_micros = read_i64(2);
|
|
let open = read_f64(3);
|
|
let high = read_f64(4);
|
|
let low = read_f64(5);
|
|
let close = read_f64(6);
|
|
let source = read_str(7);
|
|
let known_at_micros = read_i64(8);
|
|
|
|
for i in 0..num_rows {
|
|
out.push(Fx1dParquetRow {
|
|
pair: Cow::Owned(pair[i].clone()),
|
|
session_date: session_date[i],
|
|
ts_micros: ts_micros[i],
|
|
open: open[i],
|
|
high: high[i],
|
|
low: low[i],
|
|
close: close[i],
|
|
source: Cow::Owned(source[i].clone()),
|
|
known_at_micros: known_at_micros[i],
|
|
});
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
pub(super) fn assert_row_bitwise_eq(actual: &Fx1dParquetRow, expected: &Fx1dParquetRow) {
|
|
assert_eq!(actual.pair, expected.pair);
|
|
assert_eq!(actual.session_date, expected.session_date);
|
|
assert_eq!(actual.ts_micros, expected.ts_micros);
|
|
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.source, expected.source);
|
|
assert_eq!(actual.known_at_micros, expected.known_at_micros);
|
|
}
|
|
|
|
pub(super) fn assert_no_transient_files(dir: &Path) {
|
|
if !dir.exists() {
|
|
return;
|
|
}
|
|
for entry in fs::read_dir(dir).expect("read dir") {
|
|
let entry = entry.expect("dir entry");
|
|
let name = entry.file_name().to_string_lossy().into_owned();
|
|
assert!(
|
|
!name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock",
|
|
"unexpected transient file remaining: {}",
|
|
entry.path().display()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn schema_matches_contract_names_types_nullability_and_order() {
|
|
let schema = fx_1d_parquet_schema().expect("build schema");
|
|
assert_eq!(schema.name(), "fx_1d");
|
|
let fields = schema.get_fields();
|
|
assert_eq!(fields.len(), 9);
|
|
|
|
let expected: [(
|
|
&str,
|
|
PhysicalType,
|
|
Repetition,
|
|
Option<LogicalType>,
|
|
ConvertedType,
|
|
); 9] = [
|
|
(
|
|
"pair",
|
|
PhysicalType::BYTE_ARRAY,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::String),
|
|
ConvertedType::UTF8,
|
|
),
|
|
(
|
|
"session_date",
|
|
PhysicalType::INT32,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::Date),
|
|
ConvertedType::DATE,
|
|
),
|
|
(
|
|
"ts",
|
|
PhysicalType::INT64,
|
|
Repetition::REQUIRED,
|
|
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
|
|
ConvertedType::TIMESTAMP_MICROS,
|
|
),
|
|
(
|
|
"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,
|
|
),
|
|
(
|
|
"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.into_iter().enumerate() {
|
|
let f = &fields[idx];
|
|
assert_eq!(f.name(), name, "field {idx} name");
|
|
assert_eq!(f.get_physical_type(), phys, "field {name} physical type");
|
|
assert_eq!(
|
|
f.get_basic_info().repetition(),
|
|
rep,
|
|
"field {name} repetition"
|
|
);
|
|
assert_eq!(
|
|
f.get_basic_info().logical_type_ref().cloned(),
|
|
logical,
|
|
"field {name} logical type"
|
|
);
|
|
assert_eq!(
|
|
f.get_basic_info().converted_type(),
|
|
converted,
|
|
"field {name} converted type"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn build_fx_1d_round_trip_bitwise_and_zstd_on_every_column_chunk() {
|
|
let tmp = TempDirGuard::new("round-trip");
|
|
let d0 = day(1969, 12, 31); // negative epoch day (-1)
|
|
let d1 = day(1971, 1, 4);
|
|
let d2 = day(2025, 1, 3);
|
|
let d3 = day(2026, 1, 2);
|
|
|
|
let eod = [
|
|
FxDailyBar {
|
|
session_date: d0,
|
|
open: 1.0731,
|
|
high: 1.0755,
|
|
low: 1.0710,
|
|
close: 1.0742,
|
|
},
|
|
FxDailyBar {
|
|
session_date: d1,
|
|
open: 1.0105,
|
|
high: 1.0120,
|
|
low: 1.0090,
|
|
close: 1.0112,
|
|
},
|
|
];
|
|
let te = [
|
|
FxDailyBar {
|
|
session_date: d2,
|
|
open: 1.4340,
|
|
high: 1.4395,
|
|
low: 1.4310,
|
|
close: 1.4375,
|
|
},
|
|
FxDailyBar {
|
|
session_date: d3,
|
|
open: 1.3805,
|
|
high: 1.3900,
|
|
low: 1.3750,
|
|
close: 1.3855,
|
|
},
|
|
];
|
|
|
|
let built = build_fx_1d(&eod, &te);
|
|
let rows: Vec<Fx1dParquetRow> = built
|
|
.rows
|
|
.iter()
|
|
.map(|r| {
|
|
let ts = close_ts_micros(r.session_date);
|
|
let row = Fx1dParquetRow::from_fx_row(r, ts, ts);
|
|
assert!(matches!(row.pair, Cow::Borrowed(_)));
|
|
assert!(matches!(row.source, Cow::Borrowed(_)));
|
|
row
|
|
})
|
|
.collect();
|
|
|
|
let opts = Fx1dWriteOptions {
|
|
row_group_rows: 2,
|
|
..Fx1dWriteOptions::default()
|
|
};
|
|
let stats = write_fx_1d_dataset(tmp.path(), &rows, opts).unwrap();
|
|
|
|
assert_eq!(stats.rows_written, 4);
|
|
assert_eq!(stats.files_written, 1);
|
|
assert_eq!(stats.row_groups_written, 2);
|
|
assert!(stats.bytes_written > 0);
|
|
|
|
let path = tmp.path().join("fx_1d/part.parquet");
|
|
assert_eq!(fs::metadata(&path).unwrap().len(), stats.bytes_written);
|
|
|
|
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
|
let meta = reader.metadata();
|
|
assert_eq!(meta.file_metadata().num_rows(), 4);
|
|
assert_eq!(meta.num_row_groups(), 2);
|
|
for rg in meta.row_groups() {
|
|
for col in rg.columns() {
|
|
assert!(
|
|
matches!(col.compression(), Compression::ZSTD(_)),
|
|
"column {} expected ZSTD, got {:?}",
|
|
col.column_path(),
|
|
col.compression()
|
|
);
|
|
}
|
|
}
|
|
|
|
let actual = read_parquet_rows(&path);
|
|
assert_eq!(actual.len(), rows.len());
|
|
for (a, e) in actual.iter().zip(&rows) {
|
|
assert_row_bitwise_eq(a, e);
|
|
}
|
|
assert_eq!(actual[0].session_date, -1);
|
|
assert_eq!(actual[0].source.as_ref(), FxSource::EodCadForex.as_str());
|
|
assert_eq!(actual[2].source.as_ref(), FxSource::TeUsdCad.as_str());
|
|
assert_no_transient_files(&tmp.path().join("fx_1d"));
|
|
}
|
|
|
|
#[test]
|
|
fn empty_input_creates_nothing_and_preserves_existing_part_parquet() {
|
|
let tmp = TempDirGuard::new("empty");
|
|
let fresh = tmp.path().join("fresh");
|
|
let stats = write_fx_1d_dataset(
|
|
&fresh,
|
|
std::iter::empty::<Fx1dParquetRow>(),
|
|
Fx1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(stats, Fx1dWriteStats::default());
|
|
assert!(!fresh.exists(), "empty input must not create out_dir");
|
|
|
|
let seeded = tmp.path().join("seeded");
|
|
let seed_rows = vec![make_row(
|
|
FX_PAIR_USDCAD,
|
|
day(2024, 3, 15),
|
|
1.350,
|
|
1.360,
|
|
1.345,
|
|
1.355,
|
|
FxSource::EodCadForex,
|
|
)];
|
|
write_fx_1d_dataset(&seeded, &seed_rows, Fx1dWriteOptions::default()).unwrap();
|
|
let part = seeded.join("fx_1d/part.parquet");
|
|
let before = fs::read(&part).unwrap();
|
|
|
|
let empty_stats = write_fx_1d_dataset(
|
|
&seeded,
|
|
std::iter::empty::<Fx1dParquetRow>(),
|
|
Fx1dWriteOptions::default(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(empty_stats, Fx1dWriteStats::default());
|
|
assert_eq!(fs::read(&part).unwrap(), before);
|
|
assert_no_transient_files(&seeded.join("fx_1d"));
|
|
}
|
|
|
|
#[test]
|
|
fn determinism_identical_rows_produce_byte_identical_files() {
|
|
let tmp = TempDirGuard::new("determinism");
|
|
let rows = vec![
|
|
make_row(
|
|
"EURUSD",
|
|
day(2024, 1, 15),
|
|
1.090,
|
|
1.095,
|
|
1.088,
|
|
1.092,
|
|
FxSource::EodCadForex,
|
|
),
|
|
make_row(
|
|
FX_PAIR_USDCAD,
|
|
day(2024, 1, 15),
|
|
1.340,
|
|
1.345,
|
|
1.338,
|
|
1.342,
|
|
FxSource::EodCadForex,
|
|
),
|
|
make_row(
|
|
FX_PAIR_USDCAD,
|
|
day(2024, 1, 16),
|
|
1.342,
|
|
1.350,
|
|
1.341,
|
|
1.348,
|
|
FxSource::TeUsdCad,
|
|
),
|
|
];
|
|
|
|
let out_a = tmp.path().join("a");
|
|
let out_b = tmp.path().join("b");
|
|
let opts = Fx1dWriteOptions {
|
|
row_group_rows: 2,
|
|
..Fx1dWriteOptions::default()
|
|
};
|
|
write_fx_1d_dataset(&out_a, &rows, opts).unwrap();
|
|
write_fx_1d_dataset(&out_b, &rows, opts).unwrap();
|
|
|
|
let bytes_a = fs::read(out_a.join("fx_1d/part.parquet")).unwrap();
|
|
let bytes_b = fs::read(out_b.join("fx_1d/part.parquet")).unwrap();
|
|
assert_eq!(bytes_a, bytes_b);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "parquet_fx_tests.rs"]
|
|
mod edge_case_tests;
|