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

1376 lines
48 KiB
Rust

//! Streaming, atomic, year-partitioned Zstd Parquet writer for `events`.
//!
//! Writes `<out_dir>/events/year=YYYY/part.parquet` files matching the 7-column contract schema in
//! `design/DATA-CONTRACTS.md` (§3A):
//!
//! 1. `listing_id` (`INT32`, `REQUIRED`)
//! 2. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
//! 3. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`)
//! 4. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 5. `kind` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 6. `subtype` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
//! 7. `payload_json` (`BYTE_ARRAY`, `REQUIRED`, `STRING`)
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::collections::BTreeMap;
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::events::{partition_year_utc, EventRow};
pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR};
use crate::parquet_publish::{
create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id,
rollback_published, write_byte_array_col, write_i32_col, write_i64_col, write_interned_str_col,
DatasetFileLock, PublishIoError, PublishedPartition, 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};
/// Single `events` row matching the `design/DATA-CONTRACTS.md` Parquet schema.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventsParquetRow {
pub listing_id: i32,
pub ts_micros: i64,
pub known_at_micros: i64,
pub known_at_source: Cow<'static, str>,
pub kind: Cow<'static, str>,
pub subtype: String,
pub payload_json: String,
}
impl From<&EventRow<i32>> for EventsParquetRow {
fn from(row: &EventRow<i32>) -> Self {
Self {
listing_id: row.key,
ts_micros: row.ts_micros,
known_at_micros: row.known_at_micros,
known_at_source: Cow::Borrowed(row.known_at_source),
kind: Cow::Borrowed(row.kind),
subtype: row.subtype.clone(),
payload_json: row.payload_json.clone(),
}
}
}
impl From<EventRow<i32>> for EventsParquetRow {
fn from(row: EventRow<i32>) -> Self {
Self {
listing_id: row.key,
ts_micros: row.ts_micros,
known_at_micros: row.known_at_micros,
known_at_source: Cow::Borrowed(row.known_at_source),
kind: Cow::Borrowed(row.kind),
subtype: row.subtype,
payload_json: row.payload_json,
}
}
}
/// Configuration for [`write_events_dataset`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventsWriteOptions {
pub row_group_rows: usize,
pub zstd_level: i32,
}
impl Default for EventsWriteOptions {
fn default() -> Self {
Self {
row_group_rows: DEFAULT_ROW_GROUP_ROWS,
zstd_level: DEFAULT_ZSTD_LEVEL,
}
}
}
/// Accounting summary returned by [`write_events_dataset`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EventsWriteStats {
pub rows_written: usize,
pub files_written: usize,
pub row_groups_written: usize,
pub bytes_written: u64,
pub rows_by_year: BTreeMap<i32, usize>,
}
/// Typed error returned by [`write_events_dataset`].
#[derive(Debug)]
pub enum ParquetEventsError {
InvalidRowGroupRows,
InvalidZstdLevel {
level: i32,
},
UnsortedInput {
row_index: usize,
prev_listing_id: i32,
prev_ts_micros: i64,
listing_id: i32,
ts_micros: i64,
},
DuplicateRow {
row_index: usize,
listing_id: i32,
ts_micros: i64,
},
KnownAtBeforeTs {
row_index: usize,
listing_id: i32,
ts_micros: i64,
known_at_micros: i64,
},
PartitionYearOutOfRange {
row_index: usize,
listing_id: i32,
ts_micros: i64,
year: i32,
min_year: i32,
max_year: i32,
},
EmptyKnownAtSource {
row_index: usize,
listing_id: i32,
ts_micros: i64,
},
EmptyKind {
row_index: usize,
listing_id: i32,
ts_micros: i64,
},
EmptySubtype {
row_index: usize,
listing_id: i32,
ts_micros: i64,
},
EmptyPayloadJson {
row_index: usize,
listing_id: i32,
ts_micros: i64,
},
LockTimeout {
path: PathBuf,
waited: Duration,
},
RollbackFailed {
cause: Box<ParquetEventsError>,
failures: Vec<RollbackFailure>,
},
Io {
path: PathBuf,
source: io::Error,
},
Parquet {
path: PathBuf,
source: ParquetError,
},
}
impl fmt::Display for ParquetEventsError {
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 {
row_index,
prev_listing_id,
prev_ts_micros,
listing_id,
ts_micros,
} => write!(
f,
"unsorted input at row {row_index}: ({listing_id}, {ts_micros}) follows ({prev_listing_id}, {prev_ts_micros})"
),
Self::DuplicateRow {
row_index,
listing_id,
ts_micros,
} => write!(
f,
"duplicate event row at row {row_index}: (listing_id={listing_id}, ts_micros={ts_micros})"
),
Self::KnownAtBeforeTs {
row_index,
listing_id,
ts_micros,
known_at_micros,
} => write!(
f,
"known_at {known_at_micros} is before ts {ts_micros} at row {row_index} for listing_id {listing_id}"
),
Self::PartitionYearOutOfRange {
row_index,
listing_id,
ts_micros,
year,
min_year,
max_year,
} => write!(
f,
"partition year {year} (ts_micros {ts_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}"
),
Self::EmptyKnownAtSource {
row_index,
listing_id,
ts_micros,
} => write!(
f,
"empty known_at_source at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty"
),
Self::EmptyKind {
row_index,
listing_id,
ts_micros,
} => write!(
f,
"empty kind at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty"
),
Self::EmptySubtype {
row_index,
listing_id,
ts_micros,
} => write!(
f,
"empty subtype at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty"
),
Self::EmptyPayloadJson {
row_index,
listing_id,
ts_micros,
} => write!(
f,
"empty payload_json at row {row_index} for ({listing_id}, {ts_micros}): must be non-empty"
),
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 ParquetEventsError {
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 ParquetEventsError {
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 7-column Parquet schema for `events` per `design/DATA-CONTRACTS.md` (§3A).
pub fn events_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("known_at", PhysicalType::INT64)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS)))
.build()?,
),
Arc::new(
Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("kind", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("subtype", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
Arc::new(
Type::primitive_type_builder("payload_json", PhysicalType::BYTE_ARRAY)
.with_repetition(Repetition::REQUIRED)
.with_logical_type(Some(LogicalType::String))
.build()?,
),
];
Ok(Arc::new(
Type::group_type_builder("events")
.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("known_at_source"), true)
.set_column_dictionary_enabled(ColumnPath::from("kind"), true)
.set_column_dictionary_enabled(ColumnPath::from("subtype"), false)
.set_column_dictionary_enabled(ColumnPath::from("payload_json"), false)
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
.build(),
)
}
#[inline]
fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering {
a.listing_id
.cmp(&b.listing_id)
.then_with(|| a.ts_micros.cmp(&b.ts_micros))
.then_with(|| a.kind.as_ref().cmp(b.kind.as_ref()))
.then_with(|| a.subtype.cmp(&b.subtype))
.then_with(|| a.payload_json.cmp(&b.payload_json))
.then_with(|| a.known_at_micros.cmp(&b.known_at_micros))
.then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref()))
}
#[inline]
fn validate_row(row: &EventsParquetRow, row_index: usize) -> Result<i32, ParquetEventsError> {
if row.known_at_micros < row.ts_micros {
return Err(ParquetEventsError::KnownAtBeforeTs {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
known_at_micros: row.known_at_micros,
});
}
let year = partition_year_utc(row.ts_micros);
if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) {
return Err(ParquetEventsError::PartitionYearOutOfRange {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
year,
min_year: MIN_PARQUET_YEAR,
max_year: MAX_PARQUET_YEAR,
});
}
if row.known_at_source.trim().is_empty() {
return Err(ParquetEventsError::EmptyKnownAtSource {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
});
}
if row.kind.trim().is_empty() {
return Err(ParquetEventsError::EmptyKind {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
});
}
if row.subtype.trim().is_empty() {
return Err(ParquetEventsError::EmptySubtype {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
});
}
if row.payload_json.trim().is_empty() {
return Err(ParquetEventsError::EmptyPayloadJson {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
});
}
Ok(year)
}
#[derive(Default)]
struct RowGroupBuffer {
listing_id: Vec<i32>,
ts_micros: Vec<i64>,
known_at_micros: Vec<i64>,
known_at_source_ids: Vec<u32>,
known_at_source_interner: StringInterner,
kind_ids: Vec<u32>,
kind_interner: StringInterner,
subtype: Vec<ByteArray>,
payload_json: Vec<ByteArray>,
}
impl RowGroupBuffer {
#[inline]
fn len(&self) -> usize {
self.listing_id.len()
}
fn push(&mut self, row: &EventsParquetRow) {
self.listing_id.push(row.listing_id);
self.ts_micros.push(row.ts_micros);
self.known_at_micros.push(row.known_at_micros);
let kas_id = self
.known_at_source_interner
.intern(row.known_at_source.as_ref());
self.known_at_source_ids.push(kas_id);
let kind_id = self.kind_interner.intern(row.kind.as_ref());
self.kind_ids.push(kind_id);
self.subtype.push(ByteArray::from(row.subtype.as_str()));
self.payload_json
.push(ByteArray::from(row.payload_json.as_str()));
}
fn clear(&mut self) {
self.listing_id.clear();
self.ts_micros.clear();
self.known_at_micros.clear();
self.known_at_source_ids.clear();
self.known_at_source_interner.clear();
self.kind_ids.clear();
self.kind_interner.clear();
self.subtype.clear();
self.payload_json.clear();
}
}
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(
events_dir: &Path,
year: i32,
run_id: &str,
schema: &TypePtr,
props: &WriterPropertiesPtr,
staging_guards: &mut BTreeMap<i32, StagingFileGuard>,
) -> Result<Self, ParquetEventsError> {
let year_dir = events_dir.join(format!("year={year:04}"));
fs::create_dir_all(&year_dir).map_err(|source| ParquetEventsError::Io {
path: year_dir.clone(),
source,
})?;
let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?;
staging_guards.insert(year, StagingFileGuard::new(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| ParquetEventsError::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<(), ParquetEventsError> {
let row_count = self.buf.len();
if row_count == 0 {
return Ok(());
}
let map_pq = |source: ParquetError| ParquetEventsError::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).map_err(map_pq)?;
// 2. ts (INT64, REQUIRED, TIMESTAMP MICROS UTC)
write_i64_col(&mut rg_writer, &self.buf.ts_micros).map_err(map_pq)?;
// 3. known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC)
write_i64_col(&mut rg_writer, &self.buf.known_at_micros).map_err(map_pq)?;
// 4. known_at_source (BYTE_ARRAY, REQUIRED, STRING)
write_interned_str_col(
&mut rg_writer,
&self.buf.known_at_source_ids,
&self.buf.known_at_source_interner,
scratch,
)
.map_err(map_pq)?;
// 5. kind (BYTE_ARRAY, REQUIRED, STRING)
write_interned_str_col(
&mut rg_writer,
&self.buf.kind_ids,
&self.buf.kind_interner,
scratch,
)
.map_err(map_pq)?;
// 6. subtype (BYTE_ARRAY, REQUIRED, STRING)
write_byte_array_col(&mut rg_writer, &self.buf.subtype).map_err(map_pq)?;
// 7. payload_json (BYTE_ARRAY, REQUIRED, STRING)
write_byte_array_col(&mut rg_writer, &self.buf.payload_json).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<SyncedYearFile, ParquetEventsError> {
self.flush_row_group(scratch)?;
let mut buf_writer =
self.writer
.into_inner()
.map_err(|source| ParquetEventsError::Parquet {
path: self.tmp_path.clone(),
source,
})?;
buf_writer.flush().map_err(|source| ParquetEventsError::Io {
path: self.tmp_path.clone(),
source,
})?;
let file = buf_writer
.into_inner()
.map_err(|err| ParquetEventsError::Io {
path: self.tmp_path.clone(),
source: err.into_error(),
})?;
file.sync_all().map_err(|source| ParquetEventsError::Io {
path: self.tmp_path.clone(),
source,
})?;
let bytes = file
.metadata()
.map_err(|source| ParquetEventsError::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 finish_with_rollback(
cause: ParquetEventsError,
published: &[PublishedPartition],
extra_failure: Option<RollbackFailure>,
) -> ParquetEventsError {
let mut failures = Vec::new();
if let Some(failure) = extra_failure {
failures.push(failure);
}
failures.extend(rollback_published(published));
if failures.is_empty() {
cause
} else {
ParquetEventsError::RollbackFailed {
cause: Box::new(cause),
failures,
}
}
}
/// Streams strictly ascending `events` rows into year-partitioned Zstd Parquet files at
/// `<out_dir>/events/year=YYYY/part.parquet`.
///
/// # Sort Order & Validation
/// Input rows must be strictly ascending by the `build_events` sort key:
/// `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)`.
/// Out-of-order rows, exact duplicates, `known_at_micros < ts_micros`, partition years outside
/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, and empty (or whitespace-only) `known_at_source`,
/// `kind`, `subtype`, or `payload_json` return typed [`ParquetEventsError`] variants with nothing
/// published. Empty input returns `Ok(EventsWriteStats::default())` without creating
/// `<out_dir>/events` or touching pre-existing partitions.
///
/// # Concurrency & Atomicity
/// Concurrent writers targeting the same `<out_dir>/events` 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. Pre-existing `part.parquet` files are backed up
/// in place (hard link with exclusive copy fallback) so the live path remains readable until
/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before
/// owned staging files are unlinked, replaced partitions are restored from backup, and newly
/// published partitions are removed (reporting rollback errors via
/// [`ParquetEventsError::RollbackFailed`]).
pub fn write_events_dataset<P, I, R>(
out_dir: P,
rows: I,
options: EventsWriteOptions,
) -> Result<EventsWriteStats, ParquetEventsError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<EventsParquetRow>,
{
write_events_dataset_with_hooks(
out_dir,
rows,
options,
DEFAULT_LOCK_TIMEOUT,
|_, _, _| {},
)
}
fn write_events_dataset_with_hooks<P, I, R, F>(
out_dir: P,
rows: I,
options: EventsWriteOptions,
lock_timeout: Duration,
on_after_backup: F,
) -> Result<EventsWriteStats, ParquetEventsError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<EventsParquetRow>,
F: FnMut(i32, &Path, Option<&Path>),
{
write_events_dataset_with_lock_and_backup_hooks(
out_dir,
rows,
options,
lock_timeout,
|| {},
on_after_backup,
)
}
fn write_events_dataset_with_lock_and_backup_hooks<P, I, R, G, F>(
out_dir: P,
rows: I,
options: EventsWriteOptions,
lock_timeout: Duration,
mut on_lock_contended: G,
mut on_after_backup: F,
) -> Result<EventsWriteStats, ParquetEventsError>
where
P: AsRef<Path>,
I: IntoIterator<Item = R>,
R: Borrow<EventsParquetRow>,
G: FnMut(),
F: FnMut(i32, &Path, Option<&Path>),
{
if options.row_group_rows == 0 {
return Err(ParquetEventsError::InvalidRowGroupRows);
}
let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| {
ParquetEventsError::InvalidZstdLevel {
level: options.zstd_level,
}
})?;
let mut row_iter = rows.into_iter();
let Some(first_item) = row_iter.next() else {
return Ok(EventsWriteStats::default());
};
validate_row(first_item.borrow(), 0)?;
let out_dir = out_dir.as_ref();
let events_dir = out_dir.join("events");
let schema = events_parquet_schema().map_err(|source| ParquetEventsError::Parquet {
path: events_dir.clone(),
source,
})?;
let props = build_writer_properties(zstd_level);
fs::create_dir_all(&events_dir).map_err(|source| ParquetEventsError::Io {
path: events_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(&events_dir);
let _in_process_guard = match dataset_mu.try_lock() {
Ok(guard) => guard,
Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => {
on_lock_contended();
dataset_mu.lock().unwrap_or_else(|err| err.into_inner())
}
};
let _file_lock = DatasetFileLock::acquire_with_timeout(&events_dir, lock_timeout)?;
let run_id = next_run_id();
// Declared before `writers` so Rust's reverse drop order closes all Parquet file handles
// before unlinking owned `.tmp` staging files on error or panic unwind.
let mut staging_guards: BTreeMap<i32, StagingFileGuard> = BTreeMap::new();
let mut writers: BTreeMap<i32, YearWriter> = BTreeMap::new();
let mut scratch: Vec<ByteArray> = Vec::with_capacity(STRING_WRITE_BATCH_ROWS);
let synced_files: Vec<(i32, SyncedYearFile)> = {
let mut prev_item: Option<R> = None;
for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() {
let row = item.borrow();
if let Some(prev) = prev_item.as_ref() {
let prev_row = prev.borrow();
match compare_event_rows(row, prev_row) {
Ordering::Equal => {
return Err(ParquetEventsError::DuplicateRow {
row_index,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
});
}
Ordering::Less => {
return Err(ParquetEventsError::UnsortedInput {
row_index,
prev_listing_id: prev_row.listing_id,
prev_ts_micros: prev_row.ts_micros,
listing_id: row.listing_id,
ts_micros: row.ts_micros,
});
}
Ordering::Greater => {}
}
}
let year = validate_row(row, row_index)?;
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(
&events_dir,
year,
&run_id,
&schema,
&props,
&mut staging_guards,
)?;
entry.insert(opened)
}
};
yw.buf.push(row);
if yw.buf.len() == options.row_group_rows {
yw.flush_row_group(&mut scratch)?;
}
prev_item = Some(item);
}
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));
}
synced
};
let mut stats = EventsWriteStats::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.into(), &published, None));
}
}
}
// 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 = ParquetEventsError::Io {
path: file.final_path,
source,
};
return Err(finish_with_rollback(err, &published, None));
}
};
on_after_backup(year, &file.final_path, backup_path.as_deref());
if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) {
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 = ParquetEventsError::Io {
path: file.final_path,
source,
};
return Err(finish_with_rollback(err, &published, extra_failure));
}
if let Some(guard) = staging_guards.get_mut(&year) {
guard.disarm();
}
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, Encoding};
use parquet::column::reader::ColumnReader;
use parquet::file::reader::{FileReader, SerializedFileReader};
use super::*;
use crate::events::{
build_events, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING,
KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG,
};
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-events-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 utc_micros(
year: i32,
month: u32,
day: u32,
hour: u8,
minute: u8,
second: u8,
micro: i64,
) -> i64 {
let epoch_day = ymd_to_epoch_days(year, month, day).expect("valid test date");
let secs = i64::from(epoch_day) * 86_400
+ i64::from(hour) * 3_600
+ i64::from(minute) * 60
+ i64::from(second);
secs * 1_000_000 + micro
}
pub(super) fn make_event_row(
listing_id: i32,
ts_micros: i64,
known_at_micros: i64,
known_at_source: &'static str,
kind: &'static str,
subtype: &str,
payload_json: &str,
) -> EventsParquetRow {
EventsParquetRow {
listing_id,
ts_micros,
known_at_micros,
known_at_source: Cow::Borrowed(known_at_source),
kind: Cow::Borrowed(kind),
subtype: subtype.to_string(),
payload_json: payload_json.to_string(),
}
}
pub(super) fn read_parquet_rows(path: &Path) -> Vec<EventsParquetRow> {
let file = File::open(path).expect("open parquet file");
let reader = SerializedFileReader::new(file).expect("open parquet reader");
let meta = reader.metadata();
let mut out = Vec::new();
for rg_idx in 0..meta.num_row_groups() {
let rg_rows = meta.row_group(rg_idx).num_rows() as usize;
let rg_reader = reader.get_row_group(rg_idx).expect("row group reader");
let read_i32_col = |col_idx: usize| -> Vec<i32> {
let mut vals = Vec::with_capacity(rg_rows);
match rg_reader.get_column_reader(col_idx).expect("col reader") {
ColumnReader::Int32ColumnReader(mut typed) => {
let mut read = 0usize;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, None, None, &mut vals)
.expect("read i32 records");
assert!(n > 0, "unexpected short read in INT32 column {col_idx}");
read += n;
}
}
_ => panic!("expected INT32 column at index {col_idx}"),
}
vals
};
let read_i64_col = |col_idx: usize| -> Vec<i64> {
let mut vals = Vec::with_capacity(rg_rows);
match rg_reader.get_column_reader(col_idx).expect("col reader") {
ColumnReader::Int64ColumnReader(mut typed) => {
let mut read = 0usize;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, None, None, &mut vals)
.expect("read i64 records");
assert!(n > 0, "unexpected short read in INT64 column {col_idx}");
read += n;
}
}
_ => panic!("expected INT64 column at index {col_idx}"),
}
vals
};
let read_str_col = |col_idx: usize| -> Vec<String> {
let mut raw = Vec::with_capacity(rg_rows);
match rg_reader.get_column_reader(col_idx).expect("col reader") {
ColumnReader::ByteArrayColumnReader(mut typed) => {
let mut read = 0usize;
while read < rg_rows {
let (n, _, _) = typed
.read_records(rg_rows - read, None, None, &mut raw)
.expect("read byte_array records");
assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}");
read += n;
}
}
_ => panic!("expected BYTE_ARRAY column at index {col_idx}"),
}
raw.iter()
.map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string())
.collect()
};
let listing_ids = read_i32_col(0);
let ts = read_i64_col(1);
let known_at = read_i64_col(2);
let known_at_source = read_str_col(3);
let kind = read_str_col(4);
let subtype = read_str_col(5);
let payload_json = read_str_col(6);
for i in 0..rg_rows {
out.push(EventsParquetRow {
listing_id: listing_ids[i],
ts_micros: ts[i],
known_at_micros: known_at[i],
known_at_source: Cow::Owned(known_at_source[i].clone()),
kind: Cow::Owned(kind[i].clone()),
subtype: subtype[i].clone(),
payload_json: payload_json[i].clone(),
});
}
}
out
}
pub(super) fn assert_no_transient_files(dir: &Path) {
if !dir.exists() {
return;
}
fn walk(dir: &Path) {
for entry in fs::read_dir(dir).expect("read_dir") {
let path = entry.expect("dir entry").path();
if path.is_dir() {
walk(&path);
} else {
let name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or_default();
assert!(
!name.ends_with(".tmp")
&& !name.ends_with(".bak")
&& name != ".write.lock",
"unexpected transient file left behind: {}",
path.display()
);
}
}
}
walk(dir);
}
#[test]
fn schema_matches_contract_columns_types_and_order() {
let schema = events_parquet_schema().expect("build schema");
assert_eq!(schema.name(), "events");
let fields = schema.get_fields();
assert_eq!(fields.len(), 7);
let expected: [(
&str,
PhysicalType,
Repetition,
Option<LogicalType>,
ConvertedType,
); 7] = [
(
"listing_id",
PhysicalType::INT32,
Repetition::REQUIRED,
None,
ConvertedType::NONE,
),
(
"ts",
PhysicalType::INT64,
Repetition::REQUIRED,
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
ConvertedType::TIMESTAMP_MICROS,
),
(
"known_at",
PhysicalType::INT64,
Repetition::REQUIRED,
Some(LogicalType::timestamp(true, TimeUnit::MICROS)),
ConvertedType::TIMESTAMP_MICROS,
),
(
"known_at_source",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"kind",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"subtype",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
ConvertedType::UTF8,
),
(
"payload_json",
PhysicalType::BYTE_ARRAY,
Repetition::REQUIRED,
Some(LogicalType::String),
ConvertedType::UTF8,
),
];
for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() {
let field = &fields[idx];
assert_eq!(field.name(), name, "column {idx} name");
assert_eq!(field.get_physical_type(), phys, "column {idx} physical type");
assert_eq!(
field.get_basic_info().repetition(),
rep,
"column {idx} repetition"
);
assert_eq!(
field.get_basic_info().logical_type_ref().cloned(),
logical,
"column {idx} logical type"
);
assert_eq!(
field.get_basic_info().converted_type(),
converted,
"column {idx} converted type"
);
}
}
#[test]
fn build_events_round_trip_partitions_by_utc_year_with_zstd_and_multi_row_groups() {
let tmp = TempDirGuard::new("roundtrip");
let filings = vec![
// 2022 filing
QmFiling {
key: 10_i32,
timefiled: "2022-06-15T10:30:00 EDT".to_string(),
form_type: "10-Q".to_string(),
filing_id: Some("F-2022-01".to_string()),
url: Some("https://sec.example/2022-10q".to_string()),
},
// 2023 8-K linked to same-day earnings
QmFiling {
key: 10_i32,
timefiled: "2023-05-04T16:10:00 EDT".to_string(),
form_type: "8-K".to_string(),
filing_id: Some("F-2023-8K".to_string()),
url: Some("https://sec.example/2023-8k".to_string()),
},
// Second 2023 8-K so a single row group contains repeated `subtype = "8-k"` values
QmFiling {
key: 10_i32,
timefiled: "2023-05-05T10:00:00 EDT".to_string(),
form_type: "8-K".to_string(),
filing_id: Some("F-2023-8K-2".to_string()),
url: Some("https://sec.example/2023-8k-2".to_string()),
},
// Late-evening ET on 2024-12-31 21:30:00 EST -> 2025-01-01 02:30:00 UTC (year=2025)
QmFiling {
key: 10_i32,
timefiled: "2024-12-31T21:30:00 EST".to_string(),
form_type: "News release".to_string(),
filing_id: Some("F-2024-EVE".to_string()),
url: None,
},
// 2024 filing for listing 20
QmFiling {
key: 20_i32,
timefiled: "2024-03-15T08:00:00 EDT".to_string(),
form_type: "10-K/A".to_string(),
filing_id: Some("F-2024-10KA".to_string()),
url: Some("https://sec.example/2024-10ka".to_string()),
},
];
let earnings = vec![
// Linked to 2023-05-04 8-K
QmEarning {
key: 10_i32,
report_date: ymd_to_epoch_days(2023, 5, 4).unwrap(),
announce_time: "AMC".to_string(),
fiscal_period_end: Some(ymd_to_epoch_days(2023, 3, 31).unwrap()),
actual_eps: Some(1.42),
revenue: Some(9_500_000_000.0),
},
// Unlinked -> lagged to 2024-08-01 16:05 EDT (20:05 UTC, year=2024)
QmEarning {
key: 20_i32,
report_date: ymd_to_epoch_days(2024, 8, 1).unwrap(),
announce_time: "BTO".to_string(),
fiscal_period_end: Some(ymd_to_epoch_days(2024, 6, 30).unwrap()),
actual_eps: Some(0.85),
revenue: None,
},
];
let built = build_events(filings, earnings);
assert_eq!(built.stats.filings_out, 5);
assert_eq!(built.stats.earnings_linked_to_filing, 1);
assert_eq!(built.stats.earnings_lagged_1605, 1);
let rows_from_ref: Vec<EventsParquetRow> =
built.rows.iter().map(EventsParquetRow::from).collect();
let mut rows: Vec<EventsParquetRow> =
built.rows.into_iter().map(EventsParquetRow::from).collect();
assert_eq!(rows_from_ref, rows);
// Add exact UTC year boundary rows: 2023-12-31T23:59:59.999999Z and 2024-01-01T00:00:00.000000Z
rows.push(make_event_row(
30,
utc_micros(2023, 12, 31, 23, 59, 59, 999_999),
utc_micros(2023, 12, 31, 23, 59, 59, 999_999),
KNOWN_AT_SOURCE_FILING_TIMESTAMP,
EVENT_KIND_FILING,
"8-k",
r#"{"boundary":"end_2023"}"#,
));
rows.push(make_event_row(
30,
utc_micros(2024, 1, 1, 0, 0, 0, 0),
utc_micros(2024, 1, 1, 0, 0, 0, 0),
KNOWN_AT_SOURCE_FILING_TIMESTAMP,
EVENT_KIND_FILING,
"8-k",
r#"{"boundary":"start_2024"}"#,
));
// Also include a row where known_at_micros > ts_micros (e.g. lagged reporting).
rows.push(make_event_row(
30,
utc_micros(2025, 2, 10, 14, 0, 0, 0),
utc_micros(2025, 2, 10, 21, 5, 0, 0),
KNOWN_AT_SOURCE_STATUTORY_LAG,
EVENT_KIND_EARNINGS,
"amc",
r#"{"lagged":true}"#,
));
let opts = EventsWriteOptions {
row_group_rows: 2,
zstd_level: DEFAULT_ZSTD_LEVEL,
};
let stats = write_events_dataset(tmp.path(), &rows, opts).expect("write events");
let expected_by_year = BTreeMap::from([(2022, 1), (2023, 4), (2024, 3), (2025, 2)]);
assert_eq!(stats.rows_written, rows.len());
assert_eq!(stats.files_written, 4);
// 2022: 1 row (1 rg), 2023: 4 rows (2 rgs), 2024: 3 rows (2 rgs), 2025: 2 rows (1 rg)
assert_eq!(stats.row_groups_written, 6);
assert_eq!(stats.rows_by_year, expected_by_year);
let expected_schema = events_parquet_schema().unwrap();
let mut total_bytes = 0u64;
for (&year, &expected_count) in &expected_by_year {
let path = tmp
.path()
.join(format!("events/year={year:04}/part.parquet"));
assert!(path.is_file(), "missing {}", path.display());
total_bytes += fs::metadata(&path).unwrap().len();
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
let meta = reader.metadata();
assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref());
assert_eq!(meta.file_metadata().num_rows() as usize, expected_count);
for rg in meta.row_groups() {
for col in rg.columns() {
assert!(
matches!(col.compression(), Compression::ZSTD(_)),
"year {year} column {} must be ZSTD",
col.column_path()
);
}
for dict_col in [3usize, 4usize] {
assert!(
rg.column(dict_col).encodings().any(|e| matches!(
e,
Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY
)),
"year {year} column {dict_col} should use dictionary encoding"
);
}
for plain_col in [5usize, 6usize] {
assert!(
!rg.column(plain_col).encodings().any(|e| matches!(
e,
Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY
)),
"year {year} column {plain_col} must not use dictionary encoding"
);
assert!(
rg.column(plain_col)
.encodings()
.any(|e| e == Encoding::PLAIN),
"year {year} column {plain_col} should use PLAIN encoding"
);
}
}
let actual = read_parquet_rows(&path);
let expected: Vec<EventsParquetRow> = rows
.iter()
.filter(|r| partition_year_utc(r.ts_micros) == year)
.cloned()
.collect();
assert_eq!(actual, expected, "year {year} row mismatch");
}
assert_eq!(stats.bytes_written, total_bytes);
assert_no_transient_files(&tmp.path().join("events"));
}
}
#[cfg(test)]
#[path = "parquet_events_tests.rs"]
mod edge_case_tests;