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

1944 lines
74 KiB
Rust

//! Pure, in-memory `adj_factors` curation stage joining
//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::adj::build_adj_factors`],
//! [`crate::session_close::et_session_close_utc_micros`], and
//! [`crate::parquet_adj::write_adj_factors_dataset`] into contract [`AdjFactorsParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - **Map before build:** every source-keyed `qmSplits` and `qmDividends` event is resolved via
//! `(mapping_source, source_key, ex_date) -> listing_id: i32` *before* calling
//! [`build_adj_factors`] on `i32` listing keys. Cumulative factors (`cum_split_factor`,
//! `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker
//! renames, while ticker reuse across distinct `listing_id`s produces independent chains.
//! - **Unmapped events:** splits and dividends with no covering `provider_mapping` range on
//! `ex_date` are dropped and counted separately in `splits_dropped_unmapped` and
//! `dividends_dropped_unmapped`.
//! - **Cross-key collision policy (fail closed on conflict):** after mapping, events on the same
//! `(listing_id, ex_date)` are grouped deterministically:
//! - Single-source-key groups pass through unchanged to [`build_adj_factors`] (preserving
//! same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and
//! zero-cash dividend drops).
//! - Multi-source-key groups whose payloads are bitwise identical collapse to one event and are
//! counted in `splits_collision_collapsed` / `dividends_collision_collapsed` and
//! `listing_collision_collapsed`.
//! - Multi-source-key groups with conflicting split ratios or conflicting dividend fields return
//! [`CurateAdjError::ConflictingCrossKeySplit`] /
//! [`CurateAdjError::ConflictingCrossKeyDividend`] rather than silently dropping or doubling an
//! event that would corrupt every earlier cumulative factor.
//! - **Conservative `known_at` & point-in-time snapshot contract:**
//! - Every row's `known_at_micros` is stamped with
//! `et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` /
//! `America/Toronto` on `ex_date`: `21:00 UTC` in EST, `20:00 UTC` in EDT).
//! Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns
//! [`CurateAdjError::ExDateOutOfRange`] naming `(listing_id, ex_date)` without panicking.
//! - Because [`build_adj_factors`] computes right-to-left suffix products
//! (`cum_split_factor`, `cum_total_factor`), later splits and dividends are compounded into
//! earlier rows. Consequently, [`curate_adj_factors`] produces an explicitly tagged
//! [`AdjSnapshotKind::RetrospectiveSnapshot`] (full-history snapshot): slicing it with a bare
//! `known_at <= as_of` filter would still admit earlier rows whose cumulative factors embed
//! future or held-out vault actions.
//! - For point-in-time and vault-fenced reads, callers MUST use [`curate_adj_factors_as_of`] /
//! [`curate_and_write_adj_factors_as_of`] with an [`AdjPointInTimeFence`] (`as_of_micros`
//! inclusive `<=`, `vault_cutoff_micros` exclusive `<`), which fences source events *before*
//! compaction and compounding and tags the output as [`AdjSnapshotKind::PointInTimeFenced`].
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::HashMap;
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 parquet::basic::{Compression, ZstdLevel};
use parquet::column::reader::ColumnReader;
use parquet::data_type::ByteArray;
use parquet::errors::ParquetError;
use parquet::file::metadata::KeyValue;
use parquet::file::properties::WriterProperties;
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::file::writer::SerializedFileWriter;
use parquet::schema::types::ColumnPath;
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
use crate::parquet_adj::{
adj_factors_parquet_schema, AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats,
ParquetAdjError, RollbackFailure,
};
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_optional_interned_str_col, DatasetFileLock,
StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES,
STRING_WRITE_BATCH_ROWS,
};
use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable};
use crate::session_close::{et_session_close_utc_micros, SessionCloseError};
use crate::split::SplitEvent;
/// Current format version embedded in `adj_factors/part.parquet` footer `key_value_metadata`.
pub const ADJ_SNAPSHOT_FORMAT_VERSION: u32 = 1;
const KV_PREFIX: &str = "stock_bot.adj_factors.";
const KV_FORMAT_VERSION: &str = "stock_bot.adj_factors.format_version";
const KV_SNAPSHOT_KIND: &str = "stock_bot.adj_factors.snapshot_kind";
const KV_AS_OF_MICROS: &str = "stock_bot.adj_factors.as_of_micros";
const KV_VAULT_CUTOFF_MICROS: &str = "stock_bot.adj_factors.vault_cutoff_micros";
const KV_ROWS_WRITTEN: &str = "stock_bot.adj_factors.rows_written";
const KV_SNAPSHOT_CHECKSUM: &str = "stock_bot.adj_factors.snapshot_checksum";
/// Point-in-time and Vault holdout fence applied to source events *before*
/// [`build_adj_factors`] computes right-to-left cumulative suffix factors.
///
/// - `as_of_micros`: inclusive UTC microsecond upper bound (`event_known_at <= as_of_micros`).
/// - `vault_cutoff_micros`: exclusive UTC microsecond Vault holdout boundary
/// (`event_known_at < vault_cutoff_micros`), matching `design/DATA-CONTRACTS.md` §4.
///
/// When both bounds are set, an event must satisfy both (`known_at <= as_of_micros` AND
/// `known_at < vault_cutoff_micros`), so the vault cutoff always wins even if `as_of_micros` is
/// at or past `vault_cutoff_micros`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AdjPointInTimeFence {
pub as_of_micros: Option<i64>,
pub vault_cutoff_micros: Option<i64>,
}
impl AdjPointInTimeFence {
/// Unbounded retrospective full-history snapshot (no `as_of` or vault fence).
#[inline]
pub const fn retrospective() -> Self {
Self {
as_of_micros: None,
vault_cutoff_micros: None,
}
}
/// Inclusive `known_at <= as_of_micros` fence without a separate vault cutoff.
#[inline]
pub const fn as_of(as_of_micros: i64) -> Self {
Self {
as_of_micros: Some(as_of_micros),
vault_cutoff_micros: None,
}
}
/// Exclusive `known_at < vault_cutoff_micros` vault holdout fence.
#[inline]
pub const fn vault_fenced(vault_cutoff_micros: i64) -> Self {
Self {
as_of_micros: None,
vault_cutoff_micros: Some(vault_cutoff_micros),
}
}
/// Combined `known_at <= as_of_micros` and `known_at < vault_cutoff_micros` fence.
#[inline]
pub const fn as_of_with_vault_cutoff(as_of_micros: i64, vault_cutoff_micros: i64) -> Self {
Self {
as_of_micros: Some(as_of_micros),
vault_cutoff_micros: Some(vault_cutoff_micros),
}
}
/// Returns `true` when neither an `as_of` nor a `vault_cutoff` bound is set.
#[inline]
pub const fn is_retrospective(&self) -> bool {
self.as_of_micros.is_none() && self.vault_cutoff_micros.is_none()
}
/// Returns `true` iff an event with `known_at_micros` is admitted by this fence.
#[inline]
pub const fn admits(&self, known_at_micros: i64) -> bool {
if let Some(as_of) = self.as_of_micros {
if known_at_micros > as_of {
return false;
}
}
if let Some(vault_cutoff) = self.vault_cutoff_micros {
if known_at_micros >= vault_cutoff {
return false;
}
}
true
}
}
/// Identifies whether a curated `adj_factors` output is an unfenced retrospective full-history
/// snapshot or a point-in-time / vault-fenced snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdjSnapshotKind {
/// Built from the full input history with no `as_of` or vault fence. Earlier rows embed
/// later actions in `cum_split_factor` / `cum_total_factor`; do not slice with a bare
/// `known_at <= as_of` filter for point-in-time research reads.
RetrospectiveSnapshot,
/// Built after fencing source events by the attached [`AdjPointInTimeFence`] before
/// compaction and compounding, so no action beyond the fence is embedded in any row.
PointInTimeFenced(AdjPointInTimeFence),
}
/// Accounting summary produced alongside [`CurateAdjFactorsOutput::rows`].
///
/// Conservation invariants:
/// - `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in`
/// - `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in`
/// - `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed`
/// - `rows_out == builder.rows_out`
/// - `listings_out == builder.keys_out`
/// - For [`AdjSnapshotKind::RetrospectiveSnapshot`], `splits_dropped_fenced == 0` and
/// `dividends_dropped_fenced == 0`.
/// - `builder` independently satisfies all [`AdjBuildStats`] invariants.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CurateAdjFactorsStats {
pub builder: AdjBuildStats,
pub splits_in: usize,
pub dividends_in: usize,
pub splits_dropped_unmapped: usize,
pub dividends_dropped_unmapped: usize,
pub splits_dropped_fenced: usize,
pub dividends_dropped_fenced: usize,
pub splits_collision_collapsed: usize,
pub dividends_collision_collapsed: usize,
pub listing_collision_collapsed: usize,
pub rows_out: usize,
pub listings_out: usize,
}
/// Output of [`curate_adj_factors`] / [`curate_adj_factors_as_of`]: contract Parquet rows sorted
/// and unique by `(listing_id, ex_date)`, explicit snapshot classification, and full stage +
/// builder stats.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateAdjFactorsOutput {
pub rows: Vec<AdjFactorsParquetRow>,
pub stats: CurateAdjFactorsStats,
pub snapshot_kind: AdjSnapshotKind,
}
/// Typed errors returned by [`curate_adj_factors`].
#[derive(Debug, Clone, PartialEq)]
pub enum CurateAdjError {
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
EmptyMappingSource,
/// Validation or compounding error propagated from [`build_adj_factors`].
Adj(AdjError),
/// Two distinct source keys mapped to the same `(listing_id, ex_date)` with conflicting split
/// ratios.
ConflictingCrossKeySplit {
listing_id: i32,
ex_date: i32,
first_key: String,
first_ratio: f64,
second_key: String,
second_ratio: f64,
},
/// Two distinct source keys mapped to the same `(listing_id, ex_date)` with differing dividend
/// payloads (`cash`, `currency`, `prev_close`, or `prev_close_currency`).
ConflictingCrossKeyDividend {
listing_id: i32,
ex_date: i32,
first_key: String,
second_key: String,
},
/// A curated row's `ex_date` fell outside [`et_session_close_utc_micros`]'s supported
/// `1976-01-01..=2030-12-31` window.
ExDateOutOfRange {
listing_id: i32,
ex_date: i32,
source: SessionCloseError,
},
}
impl fmt::Display for CurateAdjError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyMappingSource => {
write!(f, "mapping_source must not be empty or blank")
}
Self::Adj(err) => write!(f, "{err}"),
Self::ConflictingCrossKeySplit {
listing_id,
ex_date,
first_key,
first_ratio,
second_key,
second_ratio,
} => write!(
f,
"conflicting cross-key splits for listing_id {listing_id} on epoch day {ex_date}: key '{first_key}' ratio {first_ratio} vs key '{second_key}' ratio {second_ratio}"
),
Self::ConflictingCrossKeyDividend {
listing_id,
ex_date,
first_key,
second_key,
} => write!(
f,
"conflicting cross-key dividends for listing_id {listing_id} on epoch day {ex_date}: key '{first_key}' vs key '{second_key}'"
),
Self::ExDateOutOfRange {
listing_id,
ex_date,
source,
} => write!(
f,
"adj_factors ex_date {ex_date} for listing_id {listing_id} out of range: {source}"
),
}
}
}
impl Error for CurateAdjError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Adj(err) => Some(err),
Self::ExDateOutOfRange { source, .. } => Some(source),
Self::EmptyMappingSource
| Self::ConflictingCrossKeySplit { .. }
| Self::ConflictingCrossKeyDividend { .. } => None,
}
}
}
impl From<AdjError> for CurateAdjError {
fn from(err: AdjError) -> Self {
Self::Adj(err)
}
}
/// Combined stats returned by [`curate_and_write_adj_factors`] and
/// [`curate_and_write_adj_factors_as_of`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurateAdjFactorsWriteReport {
pub curate_stats: CurateAdjFactorsStats,
pub write_stats: AdjFactorsWriteStats,
pub snapshot_kind: AdjSnapshotKind,
}
/// Typed error returned by [`curate_and_write_adj_factors`] and
/// [`curate_and_write_adj_factors_as_of`].
#[derive(Debug)]
pub enum CurateAdjWriteError {
Curate(CurateAdjError),
Parquet(ParquetAdjError),
}
impl fmt::Display for CurateAdjWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "adj_factors curation failed: {err}"),
Self::Parquet(err) => write!(f, "adj_factors Parquet write failed: {err}"),
}
}
}
impl Error for CurateAdjWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateAdjError> for CurateAdjWriteError {
fn from(err: CurateAdjError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetAdjError> for CurateAdjWriteError {
fn from(err: ParquetAdjError) -> Self {
Self::Parquet(err)
}
}
struct MappedSplit<K> {
listing_id: i32,
ex_date: i32,
source_key: K,
ratio: f64,
}
struct MappedDividend<K> {
listing_id: i32,
source_key: K,
event: DividendEvent,
}
#[inline]
fn resolve_with_cache<'a>(
cache: &mut HashMap<String, ProviderMappingCursor<'a>>,
mapping: &'a ProviderMappingTable,
mapping_source: &str,
key_str: &str,
ex_date: i32,
) -> Option<i32> {
if let Some(cursor) = cache.get_mut(key_str) {
return cursor.resolve(ex_date);
}
let mut cursor = mapping.cursor_for(mapping_source, key_str);
let resolved = cursor.resolve(ex_date);
cache.insert(key_str.to_owned(), cursor);
resolved
}
#[inline]
fn cmp_opt_f64(a: Option<f64>, b: Option<f64>) -> Ordering {
match (a, b) {
(None, None) => Ordering::Equal,
(None, Some(_)) => Ordering::Less,
(Some(_), None) => Ordering::Greater,
(Some(x), Some(y)) => x.total_cmp(&y),
}
}
#[inline]
fn cmp_dividend_event(a: &DividendEvent, b: &DividendEvent) -> Ordering {
a.ex_date
.cmp(&b.ex_date)
.then_with(|| a.cash.total_cmp(&b.cash))
.then_with(|| a.currency.cmp(&b.currency))
.then_with(|| cmp_opt_f64(a.prev_close, b.prev_close))
.then_with(|| a.prev_close_currency.cmp(&b.prev_close_currency))
}
#[inline]
fn dividend_event_bit_eq(a: &DividendEvent, b: &DividendEvent) -> bool {
a.ex_date == b.ex_date
&& a.cash.to_bits() == b.cash.to_bits()
&& a.currency == b.currency
&& a.prev_close.map(f64::to_bits) == b.prev_close.map(f64::to_bits)
&& a.prev_close_currency == b.prev_close_currency
}
fn compact_mapped_splits<K: AsRef<str>>(
mut mapped: Vec<MappedSplit<K>>,
) -> Result<(Vec<(i32, SplitEvent)>, usize), CurateAdjError> {
mapped.sort_unstable_by(|a, b| {
a.listing_id
.cmp(&b.listing_id)
.then_with(|| a.ex_date.cmp(&b.ex_date))
.then_with(|| a.source_key.as_ref().cmp(b.source_key.as_ref()))
.then_with(|| a.ratio.total_cmp(&b.ratio))
});
let mut out: Vec<(i32, SplitEvent)> = Vec::with_capacity(mapped.len());
let mut collapsed_total = 0usize;
let mut iter = mapped.into_iter().peekable();
let mut group: Vec<MappedSplit<K>> = Vec::with_capacity(4);
while let Some(first) = iter.next() {
let listing_id = first.listing_id;
let ex_date = first.ex_date;
group.clear();
group.push(first);
while let Some(next) = iter.peek() {
if next.listing_id == listing_id && next.ex_date == ex_date {
group.push(iter.next().expect("peeked split"));
} else {
break;
}
}
let group_len = group.len();
if group_len == 1 {
let item = group.pop().expect("single split");
out.push((
listing_id,
SplitEvent {
ex_date,
ratio: item.ratio,
},
));
continue;
}
let first_key = group[0].source_key.as_ref();
let last_key = group[group_len - 1].source_key.as_ref();
if first_key == last_key {
// Single source key: pass every event through unchanged to preserve `build_adj_factors`
// same-day split semantics.
for item in group.drain(..) {
out.push((
listing_id,
SplitEvent {
ex_date,
ratio: item.ratio,
},
));
}
continue;
}
let first_ratio = group[0].ratio;
let first_ratio_bits = first_ratio.to_bits();
let all_identical = group[1..]
.iter()
.all(|other| other.ratio.to_bits() == first_ratio_bits);
if all_identical {
collapsed_total += group_len - 1;
out.push((
listing_id,
SplitEvent {
ex_date,
ratio: first_ratio,
},
));
} else {
// Find a deterministic pair with distinct source keys and differing ratios.
let (lhs, rhs) = if let Some(other) = group[1..]
.iter()
.find(|e| e.source_key.as_ref() != first_key && e.ratio.to_bits() != first_ratio_bits)
{
(&group[0], other)
} else {
let bad = group[1..]
.iter()
.find(|e| e.ratio.to_bits() != first_ratio_bits)
.expect("non-identical split exists");
let other_key = group[1..]
.iter()
.find(|e| e.source_key.as_ref() != first_key)
.expect("distinct source key exists");
(bad, other_key)
};
return Err(CurateAdjError::ConflictingCrossKeySplit {
listing_id,
ex_date,
first_key: lhs.source_key.as_ref().to_owned(),
first_ratio: lhs.ratio,
second_key: rhs.source_key.as_ref().to_owned(),
second_ratio: rhs.ratio,
});
}
}
Ok((out, collapsed_total))
}
fn compact_mapped_dividends<K: AsRef<str>>(
mut mapped: Vec<MappedDividend<K>>,
) -> Result<(Vec<(i32, DividendEvent)>, usize), CurateAdjError> {
mapped.sort_unstable_by(|a, b| {
a.listing_id
.cmp(&b.listing_id)
.then_with(|| a.event.ex_date.cmp(&b.event.ex_date))
.then_with(|| a.source_key.as_ref().cmp(b.source_key.as_ref()))
.then_with(|| cmp_dividend_event(&a.event, &b.event))
});
let mut out: Vec<(i32, DividendEvent)> = Vec::with_capacity(mapped.len());
let mut collapsed_total = 0usize;
let mut iter = mapped.into_iter().peekable();
let mut group: Vec<MappedDividend<K>> = Vec::with_capacity(4);
while let Some(first) = iter.next() {
let listing_id = first.listing_id;
let ex_date = first.event.ex_date;
group.clear();
group.push(first);
while let Some(next) = iter.peek() {
if next.listing_id == listing_id && next.event.ex_date == ex_date {
group.push(iter.next().expect("peeked dividend"));
} else {
break;
}
}
let group_len = group.len();
if group_len == 1 {
let item = group.pop().expect("single dividend");
out.push((listing_id, item.event));
continue;
}
let first_key = group[0].source_key.as_ref();
let last_key = group[group_len - 1].source_key.as_ref();
if first_key == last_key {
// Single source key: pass every event through unchanged to preserve `build_adj_factors`
// same-day multi-dividend semantics (e.g. regular + special dividend).
for item in group.drain(..) {
out.push((listing_id, item.event));
}
continue;
}
let all_identical = group[1..]
.iter()
.all(|other| dividend_event_bit_eq(&group[0].event, &other.event));
if all_identical {
collapsed_total += group_len - 1;
let first = group.swap_remove(0);
out.push((listing_id, first.event));
} else {
let other_key = group[1..]
.iter()
.find(|e| {
e.source_key.as_ref() != first_key && !dividend_event_bit_eq(&group[0].event, &e.event)
})
.or_else(|| {
group[1..]
.iter()
.find(|e| e.source_key.as_ref() != first_key)
})
.expect("distinct source key exists");
return Err(CurateAdjError::ConflictingCrossKeyDividend {
listing_id,
ex_date,
first_key: first_key.to_owned(),
second_key: other_key.source_key.as_ref().to_owned(),
});
}
}
Ok((out, collapsed_total))
}
/// Pure `adj_factors` curation stage producing a **retrospective full-history snapshot**
/// ([`AdjSnapshotKind::RetrospectiveSnapshot`]).
///
/// Resolves source-keyed `qmSplits` and `qmDividends` through `provider_mapping` to permanent
/// `listing_id: i32` keys *before* factor building, compacts cross-key collisions (collapsing
/// bitwise-identical aliases and failing closed on conflicts), computes cumulative factors via
/// [`build_adj_factors`] unchanged, and stamps conservative `16:00 ET` `known_at` timestamps via
/// [`et_session_close_utc_micros`].
///
/// **Point-in-time warning:** because `cum_split_factor` and `cum_total_factor` compound all later
/// actions in the input into earlier rows, filtering this retrospective snapshot by
/// `known_at <= as_of` leaks future or held-out vault actions into earlier bars. Use
/// [`curate_adj_factors_as_of`] to fence source events by `as_of` and `vault_cutoff` *before*
/// compounding.
///
/// Output rows are sorted strictly ascending and unique by `(listing_id, ex_date)`.
pub fn curate_adj_factors<K, S, D>(
mapping: &ProviderMappingTable,
mapping_source: &str,
splits: S,
dividends: D,
) -> Result<CurateAdjFactorsOutput, CurateAdjError>
where
K: AsRef<str> + Ord + Clone,
S: IntoIterator<Item = (K, SplitEvent)>,
D: IntoIterator<Item = (K, DividendEvent)>,
{
curate_adj_factors_as_of(
mapping,
mapping_source,
splits,
dividends,
AdjPointInTimeFence::retrospective(),
)
}
/// Point-in-time and vault-fenced `adj_factors` curation stage.
///
/// Applies `fence` (`known_at <= as_of_micros` and/or `known_at < vault_cutoff_micros`, where each
/// event's `known_at` is `et_session_close_utc_micros(ex_date)`) to mapped source events *before*
/// cross-key compaction and *before* [`build_adj_factors`] compounds cumulative suffix factors.
/// Appending any future or held-out vault action beyond `fence` therefore leaves the curated rows
/// and adjusted reads bitwise identical.
///
/// When `fence.is_retrospective()` is `true`, this behaves identically to [`curate_adj_factors`]
/// and tags the output as [`AdjSnapshotKind::RetrospectiveSnapshot`]; otherwise it tags the output
/// as [`AdjSnapshotKind::PointInTimeFenced`].
pub fn curate_adj_factors_as_of<K, S, D>(
mapping: &ProviderMappingTable,
mapping_source: &str,
splits: S,
dividends: D,
fence: AdjPointInTimeFence,
) -> Result<CurateAdjFactorsOutput, CurateAdjError>
where
K: AsRef<str> + Ord + Clone,
S: IntoIterator<Item = (K, SplitEvent)>,
D: IntoIterator<Item = (K, DividendEvent)>,
{
if mapping_source.trim().is_empty() {
return Err(CurateAdjError::EmptyMappingSource);
}
let is_fenced = !fence.is_retrospective();
let splits_iter = splits.into_iter();
let divs_iter = dividends.into_iter();
let mut stats = CurateAdjFactorsStats::default();
let mut cursor_cache: HashMap<String, ProviderMappingCursor<'_>> = HashMap::new();
let mut mapped_splits: Vec<MappedSplit<K>> = Vec::with_capacity(splits_iter.size_hint().0);
for (key, event) in splits_iter {
stats.splits_in += 1;
let Some(listing_id) = resolve_with_cache(
&mut cursor_cache,
mapping,
mapping_source,
key.as_ref(),
event.ex_date,
) else {
stats.splits_dropped_unmapped += 1;
continue;
};
if is_fenced {
let known_at = et_session_close_utc_micros(event.ex_date).map_err(|source| {
CurateAdjError::ExDateOutOfRange {
listing_id,
ex_date: event.ex_date,
source,
}
})?;
if !fence.admits(known_at) {
stats.splits_dropped_fenced += 1;
continue;
}
}
mapped_splits.push(MappedSplit {
listing_id,
ex_date: event.ex_date,
source_key: key,
ratio: event.ratio,
});
}
let mut mapped_divs: Vec<MappedDividend<K>> = Vec::with_capacity(divs_iter.size_hint().0);
for (key, event) in divs_iter {
stats.dividends_in += 1;
let Some(listing_id) = resolve_with_cache(
&mut cursor_cache,
mapping,
mapping_source,
key.as_ref(),
event.ex_date,
) else {
stats.dividends_dropped_unmapped += 1;
continue;
};
if is_fenced {
let known_at = et_session_close_utc_micros(event.ex_date).map_err(|source| {
CurateAdjError::ExDateOutOfRange {
listing_id,
ex_date: event.ex_date,
source,
}
})?;
if !fence.admits(known_at) {
stats.dividends_dropped_fenced += 1;
continue;
}
}
mapped_divs.push(MappedDividend {
listing_id,
source_key: key,
event,
});
}
drop(cursor_cache);
let (compacted_splits, splits_collapsed) = compact_mapped_splits(mapped_splits)?;
let (compacted_divs, divs_collapsed) = compact_mapped_dividends(mapped_divs)?;
stats.splits_collision_collapsed = splits_collapsed;
stats.dividends_collision_collapsed = divs_collapsed;
stats.listing_collision_collapsed = splits_collapsed + divs_collapsed;
let built = build_adj_factors::<i32, _, _>(compacted_splits, compacted_divs)?;
let mut rows: Vec<AdjFactorsParquetRow> = Vec::with_capacity(built.rows.len());
for row in &built.rows {
let known_at_micros = et_session_close_utc_micros(row.ex_date).map_err(|source| {
CurateAdjError::ExDateOutOfRange {
listing_id: row.key,
ex_date: row.ex_date,
source,
}
})?;
rows.push(AdjFactorsParquetRow::from_adj_row(row, known_at_micros));
}
stats.builder = built.stats;
stats.rows_out = rows.len();
stats.listings_out = built.stats.keys_out;
let snapshot_kind = if is_fenced {
AdjSnapshotKind::PointInTimeFenced(fence)
} else {
AdjSnapshotKind::RetrospectiveSnapshot
};
Ok(CurateAdjFactorsOutput {
rows,
stats,
snapshot_kind,
})
}
/// Zero-allocation binary-search helper returning `(cum_split_factor, cum_total_factor)` of the
/// first curated row for `listing_id` with `ex_date > bar_date`, or `(1.0, 1.0)` if no such row
/// exists.
///
/// Assumes `rows` is sorted ascending by `(listing_id, ex_date)` (as produced by
/// [`curate_adj_factors`] or [`curate_adj_factors_as_of`]). For point-in-time reads, pass rows
/// produced by [`curate_adj_factors_as_of`] with the desired `as_of` / `vault_cutoff` fence.
#[inline]
pub fn adj_factors_for_bar(
rows: &[AdjFactorsParquetRow],
listing_id: i32,
bar_date: i32,
) -> (f64, f64) {
let idx = rows.partition_point(|row| match row.listing_id.cmp(&listing_id) {
Ordering::Less => true,
Ordering::Equal => row.ex_date <= bar_date,
Ordering::Greater => false,
});
match rows.get(idx) {
Some(row) if row.listing_id == listing_id => (row.cum_split_factor, row.cum_total_factor),
_ => (1.0, 1.0),
}
}
/// Thin end-to-end wrapper running [`curate_adj_factors`] (retrospective full-history snapshot)
/// and atomically publishing `<out_dir>/adj_factors/part.parquet` with snapshot metadata embedded
/// in the Parquet footer `key_value_metadata`.
///
/// Any [`CurateAdjError`] returns before touching `out_dir`, leaving any existing snapshot
/// untouched and publishing no `adj_factors/part.parquet`.
pub fn curate_and_write_adj_factors<P, K, S, D>(
out_dir: P,
mapping: &ProviderMappingTable,
mapping_source: &str,
splits: S,
dividends: D,
options: AdjFactorsWriteOptions,
) -> Result<CurateAdjFactorsWriteReport, CurateAdjWriteError>
where
P: AsRef<Path>,
K: AsRef<str> + Ord + Clone,
S: IntoIterator<Item = (K, SplitEvent)>,
D: IntoIterator<Item = (K, DividendEvent)>,
{
curate_and_write_adj_factors_as_of(
out_dir,
mapping,
mapping_source,
splits,
dividends,
AdjPointInTimeFence::retrospective(),
options,
)
}
/// Point-in-time / vault-fenced end-to-end wrapper running [`curate_adj_factors_as_of`] and
/// atomically publishing `<out_dir>/adj_factors/part.parquet` in a single file commit with snapshot
/// metadata embedded in the Parquet footer `key_value_metadata`.
///
/// - Any [`CurateAdjError`] returns before touching `out_dir`, leaving any existing snapshot
/// untouched and publishing no files.
/// - When the curated result has 0 rows (e.g. a fence excludes every event), an explicit 0-row
/// Zstd Parquet file with the contract [`adj_factors_parquet_schema`] and embedded footer
/// metadata is atomically published so any previously published `part.parquet` is superseded
/// rather than left stale on disk.
/// - The Parquet footer `key_value_metadata` binds `format_version`, `snapshot_kind`, exact
/// `as_of_micros` / `vault_cutoff_micros`, `rows_written`, and `snapshot_checksum` into the
/// single atomic file commit, allowing [`read_adj_factors_dataset_as_of`] to verify integrity,
/// per-row fence admission, and cumulative-chain consistency when reopening the artifact.
pub fn curate_and_write_adj_factors_as_of<P, K, S, D>(
out_dir: P,
mapping: &ProviderMappingTable,
mapping_source: &str,
splits: S,
dividends: D,
fence: AdjPointInTimeFence,
options: AdjFactorsWriteOptions,
) -> Result<CurateAdjFactorsWriteReport, CurateAdjWriteError>
where
P: AsRef<Path>,
K: AsRef<str> + Ord + Clone,
S: IntoIterator<Item = (K, SplitEvent)>,
D: IntoIterator<Item = (K, DividendEvent)>,
{
let curated = curate_adj_factors_as_of(mapping, mapping_source, splits, dividends, fence)?;
let write_stats = write_adj_factors_snapshot_parquet(
out_dir.as_ref(),
&curated.rows,
curated.snapshot_kind,
options,
)?;
Ok(CurateAdjFactorsWriteReport {
curate_stats: curated.stats,
write_stats,
snapshot_kind: curated.snapshot_kind,
})
}
/// Verified `adj_factors` snapshot reopened from `<out_dir>/adj_factors/part.parquet`.
#[derive(Debug, Clone, PartialEq)]
pub struct AdjFactorsSnapshot {
pub rows: Vec<AdjFactorsParquetRow>,
pub snapshot_kind: AdjSnapshotKind,
}
impl AdjFactorsSnapshot {
/// Returns `(cum_split_factor, cum_total_factor)` of the first row for `listing_id` with
/// `ex_date > bar_date`, or `(1.0, 1.0)` if no such row exists.
#[inline]
pub fn factors_for_bar(&self, listing_id: i32, bar_date: i32) -> (f64, f64) {
adj_factors_for_bar(&self.rows, listing_id, bar_date)
}
}
/// Typed error returned by [`read_adj_factors_dataset`] and [`read_adj_factors_dataset_as_of`].
#[derive(Debug)]
pub enum CurateAdjReadError {
/// Caller passed an unfenced (`retrospective`) fence to [`read_adj_factors_dataset_as_of`].
UnfencedReadRequested,
/// `<out_dir>/adj_factors/part.parquet` footer carries no `stock_bot.adj_factors.*` metadata
/// keys; refusing to open an unverified Parquet file.
MissingSnapshotMetadata { path: PathBuf },
/// `<out_dir>/adj_factors/part.parquet` footer metadata has partial, duplicate, unknown, or
/// malformed `stock_bot.adj_factors.*` keys.
InvalidSnapshotMetadata { path: PathBuf, message: String },
/// `<out_dir>/adj_factors/part.parquet` footer metadata carries an unsupported `format_version`.
UnsupportedSnapshotVersion {
path: PathBuf,
version: u32,
supported: u32,
},
/// Point-in-time reader refused to open a retrospective full-history snapshot.
RetrospectiveSnapshotRejected { path: PathBuf },
/// Point-in-time reader refused a snapshot whose persisted fence does not match the requested
/// fence.
IncompatibleFence {
path: PathBuf,
actual: AdjPointInTimeFence,
required: AdjPointInTimeFence,
},
/// A decoded row's `known_at_micros` fell outside the snapshot's verified point-in-time /
/// vault fence.
RowOutsideFence {
path: PathBuf,
listing_id: i32,
ex_date: i32,
known_at_micros: i64,
fence: AdjPointInTimeFence,
},
/// `<out_dir>/adj_factors/part.parquet` schema did not match [`adj_factors_parquet_schema`].
SchemaMismatch { path: PathBuf },
/// `<out_dir>/adj_factors/part.parquet` failed row-count, ordering, cumulative-split chain,
/// or bound snapshot checksum verification.
SnapshotIntegrityMismatch { path: PathBuf, detail: String },
/// I/O error reading `part.parquet`.
Io { path: PathBuf, source: io::Error },
/// Parquet decoding error reading `part.parquet`.
Parquet { path: PathBuf, source: ParquetError },
}
impl fmt::Display for CurateAdjReadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnfencedReadRequested => write!(
f,
"read_adj_factors_dataset_as_of requires a non-retrospective point-in-time or vault fence"
),
Self::MissingSnapshotMetadata { path } => write!(
f,
"missing adj_factors snapshot metadata in Parquet footer at '{}' (refusing to open unverified Parquet)",
path.display()
),
Self::InvalidSnapshotMetadata { path, message } => write!(
f,
"invalid adj_factors snapshot metadata in Parquet footer at '{}': {message}",
path.display()
),
Self::UnsupportedSnapshotVersion {
path,
version,
supported,
} => write!(
f,
"unsupported adj_factors snapshot metadata version {version} at '{}' (supported: {supported})",
path.display()
),
Self::RetrospectiveSnapshotRejected { path } => write!(
f,
"point-in-time reader rejected retrospective adj_factors snapshot at '{}'",
path.display()
),
Self::IncompatibleFence {
path,
actual,
required,
} => write!(
f,
"point-in-time reader rejected adj_factors snapshot at '{}': persisted fence {:?} does not match required fence {:?}",
path.display(),
actual,
required
),
Self::RowOutsideFence {
path,
listing_id,
ex_date,
known_at_micros,
fence,
} => write!(
f,
"adj_factors row (listing_id={listing_id}, ex_date={ex_date}, known_at_micros={known_at_micros}) in '{}' falls outside fence {:?}",
path.display(),
fence
),
Self::SchemaMismatch { path } => write!(
f,
"adj_factors Parquet schema mismatch at '{}'",
path.display()
),
Self::SnapshotIntegrityMismatch { path, detail } => write!(
f,
"adj_factors snapshot integrity mismatch at '{}': {detail}",
path.display()
),
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 CurateAdjReadError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Parquet { source, .. } => Some(source),
_ => None,
}
}
}
/// Reopens a published `adj_factors` artifact from `<out_dir>/adj_factors/part.parquet` for
/// point-in-time research reads, requiring persisted [`AdjSnapshotKind::PointInTimeFenced`] footer
/// metadata whose exact fence matches `required_fence`.
///
/// Fails closed if `required_fence` is retrospective, the Parquet footer lacks valid
/// `stock_bot.adj_factors.*` metadata, the published artifact is a
/// [`AdjSnapshotKind::RetrospectiveSnapshot`], the persisted fence differs from `required_fence`,
/// any row's `known_at` falls outside the fence, per-listing `cum_split_factor` suffix products
/// are inconsistent, or the bound snapshot checksum does not match.
pub fn read_adj_factors_dataset_as_of<P: AsRef<Path>>(
out_dir: P,
required_fence: AdjPointInTimeFence,
) -> Result<AdjFactorsSnapshot, CurateAdjReadError> {
if required_fence.is_retrospective() {
return Err(CurateAdjReadError::UnfencedReadRequested);
}
let part_path = out_dir.as_ref().join("adj_factors").join("part.parquet");
let reader = open_parquet_reader(&part_path)?;
let metadata = parse_snapshot_key_value_metadata(
&part_path,
reader.metadata().file_metadata().key_value_metadata(),
)?;
match metadata.snapshot_kind {
AdjSnapshotKind::RetrospectiveSnapshot => {
return Err(CurateAdjReadError::RetrospectiveSnapshotRejected { path: part_path });
}
AdjSnapshotKind::PointInTimeFenced(actual) if actual != required_fence => {
return Err(CurateAdjReadError::IncompatibleFence {
path: part_path,
actual,
required: required_fence,
});
}
AdjSnapshotKind::PointInTimeFenced(_) => {}
}
load_verified_parquet_snapshot(&part_path, &reader, &metadata)
}
/// Reopens a published `adj_factors` artifact from `<out_dir>/adj_factors/part.parquet`, returning
/// its rows together with its verified [`AdjSnapshotKind`].
///
/// Requires valid `stock_bot.adj_factors.*` Parquet footer metadata and verifies schema, row
/// count, sort order, per-row fence admission (for fenced snapshots), per-listing
/// `cum_split_factor` suffix-product consistency, and the bound snapshot checksum. For
/// point-in-time research reads, prefer [`read_adj_factors_dataset_as_of`].
pub fn read_adj_factors_dataset<P: AsRef<Path>>(
out_dir: P,
) -> Result<AdjFactorsSnapshot, CurateAdjReadError> {
let part_path = out_dir.as_ref().join("adj_factors").join("part.parquet");
let reader = open_parquet_reader(&part_path)?;
let metadata = parse_snapshot_key_value_metadata(
&part_path,
reader.metadata().file_metadata().key_value_metadata(),
)?;
load_verified_parquet_snapshot(&part_path, &reader, &metadata)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PersistedAdjSnapshotMetadata {
format_version: u32,
snapshot_kind: AdjSnapshotKind,
rows_written: usize,
snapshot_checksum: u64,
}
fn fnv1a_update(mut hash: u64, bytes: &[u8]) -> u64 {
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
fn fnv1a_update_opt_i64(hash: u64, val: Option<i64>) -> u64 {
match val {
Some(v) => {
let hash = fnv1a_update(hash, &[1]);
fnv1a_update(hash, &v.to_le_bytes())
}
None => fnv1a_update(hash, &[0]),
}
}
fn compute_snapshot_checksum(
format_version: u32,
snapshot_kind: AdjSnapshotKind,
rows: &[AdjFactorsParquetRow],
) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
hash = fnv1a_update(hash, &format_version.to_le_bytes());
let (kind_tag, as_of, vault_cutoff) = match snapshot_kind {
AdjSnapshotKind::RetrospectiveSnapshot => (0u8, None, None),
AdjSnapshotKind::PointInTimeFenced(fence) => {
(1u8, fence.as_of_micros, fence.vault_cutoff_micros)
}
};
hash = fnv1a_update(hash, &[kind_tag]);
hash = fnv1a_update_opt_i64(hash, as_of);
hash = fnv1a_update_opt_i64(hash, vault_cutoff);
hash = fnv1a_update(hash, &(rows.len() as u64).to_le_bytes());
for row in rows {
hash = fnv1a_update(hash, &row.listing_id.to_le_bytes());
hash = fnv1a_update(hash, &row.ex_date.to_le_bytes());
hash = fnv1a_update(hash, &row.split_factor.to_bits().to_le_bytes());
hash = fnv1a_update(hash, &row.div_cash.to_bits().to_le_bytes());
match row.div_currency.as_deref() {
Some(curr) => {
hash = fnv1a_update(hash, &[1]);
hash = fnv1a_update(hash, &(curr.len() as u64).to_le_bytes());
hash = fnv1a_update(hash, curr.as_bytes());
}
None => {
hash = fnv1a_update(hash, &[0]);
}
}
hash = fnv1a_update(hash, &row.cum_split_factor.to_bits().to_le_bytes());
hash = fnv1a_update(hash, &row.cum_total_factor.to_bits().to_le_bytes());
hash = fnv1a_update(hash, &row.known_at_micros.to_le_bytes());
}
hash
}
fn format_opt_i64_kv(val: Option<i64>) -> String {
match val {
Some(v) => v.to_string(),
None => "none".to_string(),
}
}
fn build_snapshot_key_value_metadata(
format_version: u32,
snapshot_kind: AdjSnapshotKind,
rows_written: usize,
snapshot_checksum: u64,
) -> Vec<KeyValue> {
let (kind_str, as_of, vault_cutoff) = match snapshot_kind {
AdjSnapshotKind::RetrospectiveSnapshot => ("retrospective", None, None),
AdjSnapshotKind::PointInTimeFenced(fence) => (
"point_in_time_fenced",
fence.as_of_micros,
fence.vault_cutoff_micros,
),
};
vec![
KeyValue::new(KV_FORMAT_VERSION.to_string(), format_version.to_string()),
KeyValue::new(KV_SNAPSHOT_KIND.to_string(), kind_str.to_string()),
KeyValue::new(KV_AS_OF_MICROS.to_string(), format_opt_i64_kv(as_of)),
KeyValue::new(
KV_VAULT_CUTOFF_MICROS.to_string(),
format_opt_i64_kv(vault_cutoff),
),
KeyValue::new(KV_ROWS_WRITTEN.to_string(), rows_written.to_string()),
KeyValue::new(
KV_SNAPSHOT_CHECKSUM.to_string(),
format!("0x{snapshot_checksum:016x}"),
),
]
}
fn write_adj_factors_snapshot_parquet(
out_dir: &Path,
rows: &[AdjFactorsParquetRow],
snapshot_kind: AdjSnapshotKind,
options: AdjFactorsWriteOptions,
) -> Result<AdjFactorsWriteStats, ParquetAdjError> {
write_adj_factors_snapshot_parquet_impl(out_dir, rows, snapshot_kind, options, |_, _| Ok(()))
}
#[cfg(test)]
fn write_adj_factors_snapshot_parquet_with_hooks<F>(
out_dir: &Path,
rows: &[AdjFactorsParquetRow],
snapshot_kind: AdjSnapshotKind,
options: AdjFactorsWriteOptions,
on_before_rename: F,
) -> Result<AdjFactorsWriteStats, ParquetAdjError>
where
F: FnMut(&Path, Option<&Path>) -> io::Result<()>,
{
write_adj_factors_snapshot_parquet_impl(
out_dir,
rows,
snapshot_kind,
options,
on_before_rename,
)
}
fn write_adj_factors_snapshot_parquet_impl<F>(
out_dir: &Path,
rows: &[AdjFactorsParquetRow],
snapshot_kind: AdjSnapshotKind,
options: AdjFactorsWriteOptions,
mut on_before_rename: F,
) -> Result<AdjFactorsWriteStats, ParquetAdjError>
where
F: FnMut(&Path, Option<&Path>) -> io::Result<()>,
{
if options.row_group_rows == 0 {
return Err(ParquetAdjError::InvalidRowGroupRows);
}
let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| {
ParquetAdjError::InvalidZstdLevel {
level: options.zstd_level,
}
})?;
let adj_dir = out_dir.join("adj_factors");
let schema = adj_factors_parquet_schema().map_err(|source| ParquetAdjError::Parquet {
path: adj_dir.clone(),
source,
})?;
let snapshot_checksum =
compute_snapshot_checksum(ADJ_SNAPSHOT_FORMAT_VERSION, snapshot_kind, rows);
let kv_metadata = build_snapshot_key_value_metadata(
ADJ_SNAPSHOT_FORMAT_VERSION,
snapshot_kind,
rows.len(),
snapshot_checksum,
);
let props = Arc::new(
WriterProperties::builder()
.set_compression(Compression::ZSTD(zstd_level))
.set_column_dictionary_enabled(ColumnPath::from("div_currency"), true)
.set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION")))
.set_key_value_metadata(Some(kv_metadata))
.build(),
);
fs::create_dir_all(&adj_dir).map_err(|source| ParquetAdjError::Io {
path: adj_dir.clone(),
source,
})?;
let dataset_mu = dataset_mutex(&adj_dir);
let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner());
let _file_lock = DatasetFileLock::acquire_with_timeout(&adj_dir, DEFAULT_LOCK_TIMEOUT)?;
let run_id = next_run_id();
let (tmp_path, tmp_file) = create_exclusive_tmp_file(&adj_dir, &run_id)?;
let mut staging_guard = StagingFileGuard::new(tmp_path.clone());
let final_path = adj_dir.join("part.parquet");
let map_pq = |source: ParquetError| ParquetAdjError::Parquet {
path: tmp_path.clone(),
source,
};
let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, tmp_file);
let mut writer = SerializedFileWriter::new(buf_writer, schema, props).map_err(map_pq)?;
let mut row_groups_written = 0usize;
if !rows.is_empty() {
let cap = rows.len().min(options.row_group_rows);
let mut listing_id = Vec::with_capacity(cap);
let mut ex_date = Vec::with_capacity(cap);
let mut split_factor = Vec::with_capacity(cap);
let mut div_cash = Vec::with_capacity(cap);
let mut div_currency_ids = Vec::with_capacity(cap);
let mut div_currency_def_levels = Vec::with_capacity(cap);
let mut div_currency_interner = StringInterner::default();
let mut cum_split_factor = Vec::with_capacity(cap);
let mut cum_total_factor = Vec::with_capacity(cap);
let mut known_at_micros = Vec::with_capacity(cap);
let mut scratch: Vec<ByteArray> = Vec::with_capacity(STRING_WRITE_BATCH_ROWS);
for chunk in rows.chunks(options.row_group_rows) {
listing_id.clear();
ex_date.clear();
split_factor.clear();
div_cash.clear();
div_currency_ids.clear();
div_currency_def_levels.clear();
div_currency_interner.clear();
cum_split_factor.clear();
cum_total_factor.clear();
known_at_micros.clear();
for row in chunk {
listing_id.push(row.listing_id);
ex_date.push(row.ex_date);
split_factor.push(row.split_factor);
div_cash.push(row.div_cash);
match row.div_currency.as_deref() {
Some(currency) => {
let id = div_currency_interner.intern(currency);
div_currency_ids.push(id);
div_currency_def_levels.push(1);
}
None => {
div_currency_def_levels.push(0);
}
}
cum_split_factor.push(row.cum_split_factor);
cum_total_factor.push(row.cum_total_factor);
known_at_micros.push(row.known_at_micros);
}
let mut rg_writer = writer.next_row_group().map_err(map_pq)?;
write_i32_col(&mut rg_writer, &listing_id).map_err(map_pq)?;
write_i32_col(&mut rg_writer, &ex_date).map_err(map_pq)?;
write_f64_col(&mut rg_writer, &split_factor, None).map_err(map_pq)?;
write_f64_col(&mut rg_writer, &div_cash, None).map_err(map_pq)?;
write_optional_interned_str_col(
&mut rg_writer,
&div_currency_ids,
&div_currency_def_levels,
&div_currency_interner,
&mut scratch,
)
.map_err(map_pq)?;
write_f64_col(&mut rg_writer, &cum_split_factor, None).map_err(map_pq)?;
write_f64_col(&mut rg_writer, &cum_total_factor, None).map_err(map_pq)?;
write_i64_col(&mut rg_writer, &known_at_micros).map_err(map_pq)?;
rg_writer.close().map_err(map_pq)?;
row_groups_written += 1;
}
}
let mut buf_writer = writer.into_inner().map_err(map_pq)?;
buf_writer.flush().map_err(|source| ParquetAdjError::Io {
path: tmp_path.clone(),
source,
})?;
let file = buf_writer
.into_inner()
.map_err(|err| ParquetAdjError::Io {
path: tmp_path.clone(),
source: err.into_error(),
})?;
file.sync_all().map_err(|source| ParquetAdjError::Io {
path: tmp_path.clone(),
source,
})?;
let bytes = file
.metadata()
.map_err(|source| ParquetAdjError::Io {
path: tmp_path.clone(),
source,
})?
.len();
drop(file);
let backup_path = match fs::symlink_metadata(&final_path) {
Ok(meta) if !meta.is_dir() => Some(create_backup_preserving_live(&final_path, &run_id)?),
Ok(_) => None,
Err(err) if err.kind() == io::ErrorKind::NotFound => None,
Err(source) => {
return Err(ParquetAdjError::Io {
path: final_path,
source,
});
}
};
let commit_result = on_before_rename(&final_path, backup_path.as_deref())
.and_then(|()| fs::rename(&tmp_path, &final_path));
if let Err(source) = commit_result {
let backup_remove_failure = backup_path.and_then(|bak| {
fs::remove_file(&bak).err().map(|remove_err| RollbackFailure {
final_path: final_path.clone(),
backup_path: Some(bak),
source: remove_err,
})
});
let cause = ParquetAdjError::Io {
path: final_path,
source,
};
return match backup_remove_failure {
Some(failure) => Err(ParquetAdjError::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) = fs::remove_file(&bak) {
let cause = ParquetAdjError::Io {
path: bak.clone(),
source: remove_err,
};
return match fs::rename(&bak, &final_path) {
Ok(()) => Err(cause),
Err(restore_err) => Err(ParquetAdjError::RollbackFailed {
cause: Box::new(cause),
failures: vec![RollbackFailure {
final_path,
backup_path: Some(bak),
source: restore_err,
}],
}),
};
}
}
Ok(AdjFactorsWriteStats {
rows_written: rows.len(),
files_written: 1,
row_groups_written,
bytes_written: bytes,
})
}
fn open_parquet_reader(part_path: &Path) -> Result<SerializedFileReader<File>, CurateAdjReadError> {
let file = File::open(part_path).map_err(|source| CurateAdjReadError::Io {
path: part_path.to_path_buf(),
source,
})?;
SerializedFileReader::new(file).map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})
}
fn parse_opt_i64_kv(
value: &str,
field: &str,
path: &Path,
) -> Result<Option<i64>, CurateAdjReadError> {
if value == "none" {
return Ok(None);
}
value
.parse::<i64>()
.map(Some)
.map_err(|_| CurateAdjReadError::InvalidSnapshotMetadata {
path: path.to_path_buf(),
message: format!("invalid i64 value '{value}' for '{field}'"),
})
}
fn parse_snapshot_key_value_metadata(
path: &Path,
kv_meta: Option<&Vec<KeyValue>>,
) -> Result<PersistedAdjSnapshotMetadata, CurateAdjReadError> {
let invalid = |msg: &str| CurateAdjReadError::InvalidSnapshotMetadata {
path: path.to_path_buf(),
message: msg.to_string(),
};
let Some(entries) = kv_meta else {
return Err(CurateAdjReadError::MissingSnapshotMetadata {
path: path.to_path_buf(),
});
};
let mut found_any = false;
let mut format_version: Option<u32> = None;
let mut snapshot_kind_str: Option<&str> = None;
let mut as_of_micros: Option<Option<i64>> = None;
let mut vault_cutoff_micros: Option<Option<i64>> = None;
let mut rows_written: Option<usize> = None;
let mut snapshot_checksum: Option<u64> = None;
for kv in entries {
if !kv.key.starts_with(KV_PREFIX) {
continue;
}
found_any = true;
let val = kv.value.as_deref().ok_or_else(|| {
CurateAdjReadError::InvalidSnapshotMetadata {
path: path.to_path_buf(),
message: format!("missing value for metadata key '{}'", kv.key),
}
})?;
match kv.key.as_str() {
KV_FORMAT_VERSION => {
if format_version.is_some() {
return Err(invalid("duplicate 'stock_bot.adj_factors.format_version' key"));
}
format_version = Some(
val.parse::<u32>()
.map_err(|_| invalid("invalid 'stock_bot.adj_factors.format_version'"))?,
);
}
KV_SNAPSHOT_KIND => {
if snapshot_kind_str.is_some() {
return Err(invalid("duplicate 'stock_bot.adj_factors.snapshot_kind' key"));
}
snapshot_kind_str = Some(val);
}
KV_AS_OF_MICROS => {
if as_of_micros.is_some() {
return Err(invalid("duplicate 'stock_bot.adj_factors.as_of_micros' key"));
}
as_of_micros = Some(parse_opt_i64_kv(val, KV_AS_OF_MICROS, path)?);
}
KV_VAULT_CUTOFF_MICROS => {
if vault_cutoff_micros.is_some() {
return Err(invalid(
"duplicate 'stock_bot.adj_factors.vault_cutoff_micros' key",
));
}
vault_cutoff_micros = Some(parse_opt_i64_kv(val, KV_VAULT_CUTOFF_MICROS, path)?);
}
KV_ROWS_WRITTEN => {
if rows_written.is_some() {
return Err(invalid("duplicate 'stock_bot.adj_factors.rows_written' key"));
}
rows_written = Some(
val.parse::<usize>()
.map_err(|_| invalid("invalid 'stock_bot.adj_factors.rows_written'"))?,
);
}
KV_SNAPSHOT_CHECKSUM => {
if snapshot_checksum.is_some() {
return Err(invalid(
"duplicate 'stock_bot.adj_factors.snapshot_checksum' key",
));
}
let hex = val.strip_prefix("0x").ok_or_else(|| {
invalid("'stock_bot.adj_factors.snapshot_checksum' must start with '0x'")
})?;
if hex.len() != 16 {
return Err(invalid(
"'stock_bot.adj_factors.snapshot_checksum' must be 16 hex digits",
));
}
snapshot_checksum = Some(
u64::from_str_radix(hex, 16)
.map_err(|_| invalid("invalid hex in 'stock_bot.adj_factors.snapshot_checksum'"))?,
);
}
other => {
return Err(CurateAdjReadError::InvalidSnapshotMetadata {
path: path.to_path_buf(),
message: format!("unknown metadata key '{other}'"),
});
}
}
}
if !found_any {
return Err(CurateAdjReadError::MissingSnapshotMetadata {
path: path.to_path_buf(),
});
}
let format_version = format_version
.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.format_version'"))?;
if format_version != ADJ_SNAPSHOT_FORMAT_VERSION {
return Err(CurateAdjReadError::UnsupportedSnapshotVersion {
path: path.to_path_buf(),
version: format_version,
supported: ADJ_SNAPSHOT_FORMAT_VERSION,
});
}
let snapshot_kind_str = snapshot_kind_str
.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.snapshot_kind'"))?;
let as_of_micros =
as_of_micros.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.as_of_micros'"))?;
let vault_cutoff_micros = vault_cutoff_micros
.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.vault_cutoff_micros'"))?;
let rows_written =
rows_written.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.rows_written'"))?;
let snapshot_checksum = snapshot_checksum
.ok_or_else(|| invalid("missing 'stock_bot.adj_factors.snapshot_checksum'"))?;
let snapshot_kind = match snapshot_kind_str {
"retrospective" => {
if as_of_micros.is_some() || vault_cutoff_micros.is_some() {
return Err(invalid(
"retrospective snapshot must have 'none' as_of_micros and vault_cutoff_micros",
));
}
AdjSnapshotKind::RetrospectiveSnapshot
}
"point_in_time_fenced" => {
let fence = AdjPointInTimeFence {
as_of_micros,
vault_cutoff_micros,
};
if fence.is_retrospective() {
return Err(invalid(
"point_in_time_fenced snapshot must specify as_of_micros and/or vault_cutoff_micros",
));
}
AdjSnapshotKind::PointInTimeFenced(fence)
}
other => {
return Err(CurateAdjReadError::InvalidSnapshotMetadata {
path: path.to_path_buf(),
message: format!("unknown snapshot_kind '{other}'"),
});
}
};
Ok(PersistedAdjSnapshotMetadata {
format_version,
snapshot_kind,
rows_written,
snapshot_checksum,
})
}
fn load_verified_parquet_snapshot(
part_path: &Path,
reader: &SerializedFileReader<File>,
metadata: &PersistedAdjSnapshotMetadata,
) -> Result<AdjFactorsSnapshot, CurateAdjReadError> {
let expected_schema = adj_factors_parquet_schema().map_err(|source| {
CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
}
})?;
if reader.metadata().file_metadata().schema_descr().root_schema() != expected_schema.as_ref() {
return Err(CurateAdjReadError::SchemaMismatch {
path: part_path.to_path_buf(),
});
}
let footer_rows =
usize::try_from(reader.metadata().file_metadata().num_rows()).map_err(|_| {
CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"negative or overflowing Parquet footer row count {}",
reader.metadata().file_metadata().num_rows()
),
}
})?;
if footer_rows != metadata.rows_written {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"parquet footer row count {footer_rows} does not match metadata rows_written {}",
metadata.rows_written
),
});
}
let mut rows = Vec::with_capacity(footer_rows);
let file_meta = reader.metadata();
for rg_idx in 0..file_meta.num_row_groups() {
let rg_reader =
reader
.get_row_group(rg_idx)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})?;
let num_rows = usize::try_from(file_meta.row_group(rg_idx).num_rows()).map_err(|_| {
CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: "negative or overflowing row-group row count".to_string(),
}
})?;
let read_i32 = |col_idx: usize| -> Result<Vec<i32>, CurateAdjReadError> {
let mut vals = Vec::with_capacity(num_rows);
match rg_reader
.get_column_reader(col_idx)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})? {
ColumnReader::Int32ColumnReader(mut r) => {
let (read, _, _) = r
.read_records(num_rows, None, None, &mut vals)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})?;
if read != num_rows {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"column {col_idx} returned {read} rows, expected {num_rows}"
),
});
}
}
_ => {
return Err(CurateAdjReadError::SchemaMismatch {
path: part_path.to_path_buf(),
});
}
}
Ok(vals)
};
let read_i64 = |col_idx: usize| -> Result<Vec<i64>, CurateAdjReadError> {
let mut vals = Vec::with_capacity(num_rows);
match rg_reader
.get_column_reader(col_idx)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})? {
ColumnReader::Int64ColumnReader(mut r) => {
let (read, _, _) = r
.read_records(num_rows, None, None, &mut vals)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})?;
if read != num_rows {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"column {col_idx} returned {read} rows, expected {num_rows}"
),
});
}
}
_ => {
return Err(CurateAdjReadError::SchemaMismatch {
path: part_path.to_path_buf(),
});
}
}
Ok(vals)
};
let read_f64 = |col_idx: usize| -> Result<Vec<f64>, CurateAdjReadError> {
let mut vals = Vec::with_capacity(num_rows);
match rg_reader
.get_column_reader(col_idx)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})? {
ColumnReader::DoubleColumnReader(mut r) => {
let (read, _, _) = r
.read_records(num_rows, None, None, &mut vals)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})?;
if read != num_rows {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"column {col_idx} returned {read} rows, expected {num_rows}"
),
});
}
}
_ => {
return Err(CurateAdjReadError::SchemaMismatch {
path: part_path.to_path_buf(),
});
}
}
Ok(vals)
};
let read_opt_str = |col_idx: usize| -> Result<Vec<Option<String>>, CurateAdjReadError> {
let mut vals = Vec::with_capacity(num_rows);
let mut def_levels = Vec::with_capacity(num_rows);
match rg_reader
.get_column_reader(col_idx)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})? {
ColumnReader::ByteArrayColumnReader(mut r) => {
let (read, _, levels_read) = r
.read_records(num_rows, Some(&mut def_levels), None, &mut vals)
.map_err(|source| CurateAdjReadError::Parquet {
path: part_path.to_path_buf(),
source,
})?;
if read != num_rows || levels_read != num_rows {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"column {col_idx} returned ({read}, {levels_read}) rows, expected {num_rows}"
),
});
}
}
_ => {
return Err(CurateAdjReadError::SchemaMismatch {
path: part_path.to_path_buf(),
});
}
}
let mut val_idx = 0usize;
let mut out = Vec::with_capacity(num_rows);
for def in def_levels {
match def {
0 => out.push(None),
1 => {
let bytes = vals.get(val_idx).ok_or_else(|| {
CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: "definition levels exceeded byte array values".to_string(),
}
})?;
let text = std::str::from_utf8(bytes.data())
.map_err(|_| CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: "non-UTF8 div_currency value in Parquet".to_string(),
})?
.to_owned();
val_idx += 1;
out.push(Some(text));
}
other => {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!("unexpected definition level {other} in div_currency"),
});
}
}
}
Ok(out)
};
let listing_id = read_i32(0)?;
let ex_date = read_i32(1)?;
let split_factor = read_f64(2)?;
let div_cash = read_f64(3)?;
let div_currency = read_opt_str(4)?;
let cum_split_factor = read_f64(5)?;
let cum_total_factor = read_f64(6)?;
let known_at_micros = read_i64(7)?;
for i in 0..num_rows {
rows.push(AdjFactorsParquetRow {
listing_id: listing_id[i],
ex_date: ex_date[i],
split_factor: split_factor[i],
div_cash: div_cash[i],
div_currency: div_currency[i].clone().map(Cow::Owned),
cum_split_factor: cum_split_factor[i],
cum_total_factor: cum_total_factor[i],
known_at_micros: known_at_micros[i],
});
}
}
if rows.len() != metadata.rows_written {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"decoded {} rows, metadata declared {}",
rows.len(),
metadata.rows_written
),
});
}
for pair in rows.windows(2) {
if (pair[0].listing_id, pair[0].ex_date) >= (pair[1].listing_id, pair[1].ex_date) {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"rows are not strictly ascending by (listing_id, ex_date): ({}, {}) followed by ({}, {})",
pair[0].listing_id, pair[0].ex_date, pair[1].listing_id, pair[1].ex_date
),
});
}
}
// 1. Verify every row's known_at falls inside the verified fence (for fenced snapshots).
if let AdjSnapshotKind::PointInTimeFenced(fence) = metadata.snapshot_kind {
for row in &rows {
if !fence.admits(row.known_at_micros) {
return Err(CurateAdjReadError::RowOutsideFence {
path: part_path.to_path_buf(),
listing_id: row.listing_id,
ex_date: row.ex_date,
known_at_micros: row.known_at_micros,
fence,
});
}
}
}
// 2. Verify per-listing cum_split_factor suffix-product consistency in reverse.
let mut start = 0usize;
while start < rows.len() {
let listing_id = rows[start].listing_id;
let mut end = start + 1;
while end < rows.len() && rows[end].listing_id == listing_id {
end += 1;
}
let mut running_split = 1.0_f64;
for row in rows[start..end].iter().rev() {
if row.split_factor != 1.0 {
running_split *= row.split_factor;
}
if row.cum_split_factor.to_bits() != running_split.to_bits() {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"cum_split_factor mismatch for (listing_id={}, ex_date={}): persisted {} != recomputed {}",
row.listing_id, row.ex_date, row.cum_split_factor, running_split
),
});
}
}
start = end;
}
// 3. Verify bound snapshot checksum covering format_version, snapshot_kind/fence, and all rows.
let actual_checksum =
compute_snapshot_checksum(metadata.format_version, metadata.snapshot_kind, &rows);
if actual_checksum != metadata.snapshot_checksum {
return Err(CurateAdjReadError::SnapshotIntegrityMismatch {
path: part_path.to_path_buf(),
detail: format!(
"snapshot checksum 0x{actual_checksum:016x} does not match footer 0x{:016x}",
metadata.snapshot_checksum
),
});
}
Ok(AdjFactorsSnapshot {
rows,
snapshot_kind: metadata.snapshot_kind,
})
}
#[cfg(test)]
#[path = "curate_adj_tests.rs"]
mod tests;