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

1151 lines
42 KiB
Rust

//! File-to-file `curate-adj-factors` command runner (`M1.2aa`).
//!
//! Streams concatenated raw BSON `qmSplits` and `qmDividends` dump files alongside
//! `provider_mapping.tsv` and a curated `bars_1d/year=YYYY/part.parquet` dataset into an
//! atomically published retrospective `<out_dir>/adj_factors/part.parquet` snapshot via
//! [`curate_and_write_adj_factors`].
//!
//! # `prev_close` Information Boundary
//! - Loads only 4 of the 12 `bars_1d` columns (`listing_id`, `session_date`, `close`, `currency`)
//! in bounded `65_536`-row batches into a compact in-RAM [`PrevCloseIndex`] (`16 bytes/bar`,
//! currency strings interned to `u16`).
//! - For each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date)` via
//! [`ProviderMappingTable`]. When mapped, attaches the raw `close` and `currency` of the last
//! `bars_1d` session **strictly before** `ex_date` (`session_date < ex_date`); a bar on
//! `ex_date` itself is never used. When no earlier bar exists (or the dividend is unmapped),
//! `prev_close` and `prev_close_currency` are `None`.
//! - `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op
//! handling stays delegated unchanged to [`curate_and_write_adj_factors`].
//!
//! # Counter Conservation Invariants
//! Every successful [`CurateAdjFactorsRunReport`] satisfies:
//! - Splits:
//! `splits_docs_framed as usize == splits_decode.docs_in`
//! `splits_decode.docs_in == splits_decode.rejected_total() + curate_stats.splits_dropped_unmapped + curate_stats.splits_dropped_fenced + curate_stats.splits_collision_collapsed + curate_stats.builder.split_events_in`
//! - Dividends:
//! `dividends_docs_framed as usize == dividends_decode.docs_in`
//! `dividends_decode.docs_in == dividends_decode.rejected_total() + curate_stats.dividends_dropped_unmapped + curate_stats.dividends_dropped_fenced + curate_stats.dividends_collision_collapsed + curate_stats.builder.dividend_events_in`
//! `dividends_decode.decoded == dividends_with_prev_close + dividends_without_prev_close + curate_stats.dividends_dropped_unmapped`
//!
//! # Retrospective Snapshot Caveat
//! `curate-adj-factors` publishes an unfenced [`crate::curate_adj::AdjSnapshotKind::RetrospectiveSnapshot`]
//! whose earlier cumulative factors embed later splits/dividends. Point-in-time readers
//! (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically.
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use parquet::column::reader::ColumnReader;
use parquet::data_type::ByteArray;
use parquet::errors::ParquetError;
use parquet::file::reader::{FileReader, SerializedFileReader};
use crate::adj::DividendEvent;
use crate::bson_qm_actions::BsonQmActionDecodeStats;
use crate::bson_stream::{
decode_qm_dividend_chunks, decode_qm_split_chunks, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader,
};
use crate::curate_adj::{
curate_adj_factors, curate_and_write_adj_factors, curate_and_write_adj_factors_as_of,
write_adj_factors_snapshot_parquet, AdjPointInTimeFence, CurateAdjError,
CurateAdjFactorsStats, CurateAdjWriteError,
};
use crate::parquet_adj::{AdjFactorsParquetRow, AdjFactorsWriteOptions, AdjFactorsWriteStats};
use crate::parquet_bars::bars_1d_parquet_schema;
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
use crate::split::SplitEvent;
/// Bounded per-batch row count for column-projected `bars_1d` Parquet reads.
const BARS_READ_BATCH_ROWS: usize = 65_536;
/// Column indices in [`bars_1d_parquet_schema`].
const COL_BARS_LISTING_ID: usize = 0;
const COL_BARS_SESSION_DATE: usize = 2;
const COL_BARS_CLOSE: usize = 6;
const COL_BARS_CURRENCY: usize = 9;
/// Parsed arguments for the `curate-adj-factors` CLI command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateAdjFactorsArgs {
pub qm_splits: PathBuf,
pub qm_dividends: PathBuf,
pub provider_mapping: PathBuf,
pub bars_1d_dir: PathBuf,
pub out_dir: PathBuf,
}
/// Full run report produced by [`run_curate_adj_factors`].
///
/// Conservation invariants:
/// - `splits_docs_framed as usize == splits_decode.docs_in == splits_decode.rejected_total() + curate_stats.splits_dropped_unmapped + curate_stats.splits_dropped_fenced + curate_stats.splits_collision_collapsed + curate_stats.builder.split_events_in`
/// - `dividends_docs_framed as usize == dividends_decode.docs_in == dividends_decode.rejected_total() + curate_stats.dividends_dropped_unmapped + curate_stats.dividends_dropped_fenced + curate_stats.dividends_collision_collapsed + curate_stats.builder.dividend_events_in`
/// - `dividends_decode.decoded == dividends_with_prev_close + dividends_without_prev_close + curate_stats.dividends_dropped_unmapped`
#[derive(Debug, Clone, PartialEq)]
pub struct CurateAdjFactorsRunReport {
pub bars_files_read: usize,
pub bars_rows_loaded: usize,
pub bars_listings_indexed: usize,
pub splits_docs_framed: u64,
pub splits_bytes_read: u64,
pub splits_decode: BsonQmActionDecodeStats,
pub dividends_docs_framed: u64,
pub dividends_bytes_read: u64,
pub dividends_decode: BsonQmActionDecodeStats,
pub dividends_with_prev_close: usize,
pub dividends_without_prev_close: usize,
pub curate_stats: CurateAdjFactorsStats,
pub write_stats: AdjFactorsWriteStats,
pub elapsed_secs: f64,
}
/// Stage-timed run output used internally by `bench-curate-adj-cmd`.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CurateAdjFactorsTimedRun {
pub report: CurateAdjFactorsRunReport,
pub bars_load_elapsed_secs: f64,
pub decode_elapsed_secs: f64,
pub curate_elapsed_secs: f64,
pub write_elapsed_secs: f64,
pub checksum: u64,
}
/// Typed errors returned by [`run_curate_adj_factors`].
///
/// Every variant's `Display` output is a single line naming the offending path (and 1-based line
/// number for TSV parse errors).
#[derive(Debug)]
pub enum RunCurateAdjError {
InvalidOutDir {
path: PathBuf,
detail: String,
},
InvalidBars1dDir {
path: PathBuf,
detail: String,
},
OpenInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
ReadInput {
label: &'static str,
path: PathBuf,
source: io::Error,
},
TsvParse {
path: PathBuf,
line: usize,
detail: String,
},
ProviderMapping {
path: PathBuf,
source: ProviderMappingError,
},
BarsParquetSchemaMismatch {
path: PathBuf,
},
BarsParquetRead {
path: PathBuf,
source: ParquetError,
},
BarsParquetIntegrity {
path: PathBuf,
detail: String,
},
BsonStream {
label: &'static str,
path: PathBuf,
source: BsonStreamError,
},
CurateWrite {
out_dir: PathBuf,
input_path: Option<PathBuf>,
source: CurateAdjWriteError,
},
}
impl fmt::Display for RunCurateAdjError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidOutDir { path, detail } => {
write!(f, "invalid --out '{}': {detail}", path.display())
}
Self::InvalidBars1dDir { path, detail } => {
write!(f, "invalid --bars-1d '{}': {detail}", path.display())
}
Self::OpenInput {
label,
path,
source,
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
Self::ReadInput {
label,
path,
source,
} => write!(f, "failed to read {label} '{}': {source}", path.display()),
Self::TsvParse { path, line, detail } => {
write!(f, "{}:{line}: {detail}", path.display())
}
Self::ProviderMapping { path, source } => {
write!(f, "invalid provider_mapping '{}': {source}", path.display())
}
Self::BarsParquetSchemaMismatch { path } => {
write!(f, "bars_1d Parquet schema mismatch at '{}'", path.display())
}
Self::BarsParquetRead { path, source } => {
write!(
f,
"failed reading bars_1d Parquet '{}': {source}",
path.display()
)
}
Self::BarsParquetIntegrity { path, detail } => {
write!(
f,
"bars_1d Parquet integrity error at '{}': {detail}",
path.display()
)
}
Self::BsonStream {
label,
path,
source,
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
Self::CurateWrite {
out_dir,
input_path,
source,
} => match input_path {
Some(path) => write!(
f,
"curate failed for '{}' (out '{}'): {source}",
path.display(),
out_dir.display()
),
None => write!(f, "curate/write to '{}' failed: {source}", out_dir.display()),
},
}
}
}
impl Error for RunCurateAdjError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
Self::ProviderMapping { source, .. } => Some(source),
Self::BarsParquetRead { source, .. } => Some(source),
Self::BsonStream { source, .. } => Some(source),
Self::CurateWrite { source, .. } => Some(source),
Self::InvalidOutDir { .. }
| Self::InvalidBars1dDir { .. }
| Self::TsvParse { .. }
| Self::BarsParquetSchemaMismatch { .. }
| Self::BarsParquetIntegrity { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy)]
struct BarCloseEntry {
close: f64,
session_date: i32,
currency_id: u16,
}
const _: () = assert!(std::mem::size_of::<BarCloseEntry>() == 16);
#[derive(Default)]
struct CurrencyInterner {
to_id: HashMap<String, u16>,
strings: Vec<String>,
}
impl CurrencyInterner {
fn intern(&mut self, value: &str, path: &Path) -> Result<u16, RunCurateAdjError> {
if let Some(&id) = self.to_id.get(value) {
return Ok(id);
}
let next_id = u16::try_from(self.strings.len()).map_err(|_| {
RunCurateAdjError::BarsParquetIntegrity {
path: path.to_path_buf(),
detail: "more than 65536 distinct currencies in bars_1d".to_string(),
}
})?;
self.strings.push(value.to_owned());
self.to_id.insert(value.to_owned(), next_id);
Ok(next_id)
}
#[inline]
fn get(&self, id: u16) -> &str {
self.strings[usize::from(id)].as_str()
}
}
struct PrevCloseIndex {
by_listing: HashMap<i32, Vec<BarCloseEntry>>,
currencies: CurrencyInterner,
files_read: usize,
rows_loaded: usize,
}
impl PrevCloseIndex {
/// Returns `(close, currency)` of the last `bars_1d` session strictly before `ex_date`
/// (`session_date < ex_date`) for `listing_id`, or `None` if no earlier bar exists.
#[inline]
fn lookup(&self, listing_id: i32, ex_date: i32) -> Option<(f64, &str)> {
let entries = self.by_listing.get(&listing_id)?;
let idx = entries.partition_point(|e| e.session_date < ex_date);
if idx == 0 {
return None;
}
let entry = entries[idx - 1];
Some((entry.close, self.currencies.get(entry.currency_id)))
}
}
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateAdjError> {
if out_dir.exists() && !out_dir.is_dir() {
return Err(RunCurateAdjError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
Ok(())
}
fn parse_year_partition_name(name: &str) -> Option<i32> {
let suffix = name.strip_prefix("year=")?;
if suffix.len() != 4 || !suffix.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
suffix.parse::<i32>().ok()
}
fn collect_year_partitions(dir: &Path) -> Result<Vec<(i32, PathBuf)>, RunCurateAdjError> {
let read_dir = fs::read_dir(dir).map_err(|source| RunCurateAdjError::ReadInput {
label: "bars-1d",
path: dir.to_path_buf(),
source,
})?;
let mut partitions = Vec::new();
for entry_res in read_dir {
let entry = entry_res.map_err(|source| RunCurateAdjError::ReadInput {
label: "bars-1d",
path: dir.to_path_buf(),
source,
})?;
let file_name = entry.file_name();
let Some(name_str) = file_name.to_str() else {
continue;
};
if let Some(year) = parse_year_partition_name(name_str) {
partitions.push((year, entry.path()));
}
}
partitions.sort_unstable_by_key(|(year, _)| *year);
Ok(partitions)
}
fn discover_bars_1d_part_files(bars_1d_dir: &Path) -> Result<Vec<PathBuf>, RunCurateAdjError> {
if !bars_1d_dir.exists() {
return Err(RunCurateAdjError::InvalidBars1dDir {
path: bars_1d_dir.to_path_buf(),
detail: "directory does not exist".to_string(),
});
}
if !bars_1d_dir.is_dir() {
return Err(RunCurateAdjError::InvalidBars1dDir {
path: bars_1d_dir.to_path_buf(),
detail: "path is not a directory".to_string(),
});
}
let mut partitions = collect_year_partitions(bars_1d_dir)?;
if partitions.is_empty() {
let nested = bars_1d_dir.join("bars_1d");
if nested.is_dir() {
partitions = collect_year_partitions(&nested)?;
}
}
if partitions.is_empty() {
return Err(RunCurateAdjError::InvalidBars1dDir {
path: bars_1d_dir.to_path_buf(),
detail: "no year=YYYY partitions found (expected year=YYYY/part.parquet or bars_1d/year=YYYY/part.parquet)".to_string(),
});
}
let mut files = Vec::with_capacity(partitions.len());
for (_year, part_dir) in partitions {
if !part_dir.is_dir() {
return Err(RunCurateAdjError::InvalidBars1dDir {
path: part_dir,
detail: "year partition entry is not a directory".to_string(),
});
}
let part_file = part_dir.join("part.parquet");
if !part_file.is_file() {
return Err(RunCurateAdjError::InvalidBars1dDir {
path: part_file,
detail: "missing part.parquet in year partition".to_string(),
});
}
files.push(part_file);
}
Ok(files)
}
fn load_prev_close_index(bars_1d_dir: &Path) -> Result<PrevCloseIndex, RunCurateAdjError> {
let part_files = discover_bars_1d_part_files(bars_1d_dir)?;
let expected_schema =
bars_1d_parquet_schema().map_err(|source| RunCurateAdjError::BarsParquetRead {
path: bars_1d_dir.to_path_buf(),
source,
})?;
let mut by_listing: HashMap<i32, Vec<BarCloseEntry>> = HashMap::new();
let mut currencies = CurrencyInterner::default();
let mut rows_loaded: usize = 0;
let mut batch_listing_ids: Vec<i32> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
let mut batch_session_dates: Vec<i32> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
let mut batch_closes: Vec<f64> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
let mut batch_currencies: Vec<ByteArray> = Vec::with_capacity(BARS_READ_BATCH_ROWS);
for part_path in &part_files {
let file = File::open(part_path).map_err(|source| RunCurateAdjError::OpenInput {
label: "bars-1d",
path: part_path.clone(),
source,
})?;
let reader =
SerializedFileReader::new(file).map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})?;
if reader.metadata().file_metadata().schema_descr().root_schema()
!= expected_schema.as_ref()
{
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
path: part_path.clone(),
});
}
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| {
RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
}
})?;
let num_rows = usize::try_from(file_meta.row_group(rg_idx).num_rows()).map_err(|_| {
RunCurateAdjError::BarsParquetIntegrity {
path: part_path.clone(),
detail: "negative or overflowing row-group row count".to_string(),
}
})?;
let mut listing_col = match rg_reader
.get_column_reader(COL_BARS_LISTING_ID)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})? {
ColumnReader::Int32ColumnReader(r) => r,
_ => {
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
path: part_path.clone(),
});
}
};
let mut date_col = match rg_reader
.get_column_reader(COL_BARS_SESSION_DATE)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})? {
ColumnReader::Int32ColumnReader(r) => r,
_ => {
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
path: part_path.clone(),
});
}
};
let mut close_col = match rg_reader
.get_column_reader(COL_BARS_CLOSE)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})? {
ColumnReader::DoubleColumnReader(r) => r,
_ => {
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
path: part_path.clone(),
});
}
};
let mut curr_col = match rg_reader
.get_column_reader(COL_BARS_CURRENCY)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})? {
ColumnReader::ByteArrayColumnReader(r) => r,
_ => {
return Err(RunCurateAdjError::BarsParquetSchemaMismatch {
path: part_path.clone(),
});
}
};
let mut remaining = num_rows;
while remaining > 0 {
let batch = remaining.min(BARS_READ_BATCH_ROWS);
batch_listing_ids.clear();
batch_session_dates.clear();
batch_closes.clear();
batch_currencies.clear();
let (n_lid, _, _) = listing_col
.read_records(batch, None, None, &mut batch_listing_ids)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})?;
let (n_date, _, _) = date_col
.read_records(batch, None, None, &mut batch_session_dates)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})?;
let (n_close, _, _) = close_col
.read_records(batch, None, None, &mut batch_closes)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})?;
let (n_curr, _, _) = curr_col
.read_records(batch, None, None, &mut batch_currencies)
.map_err(|source| RunCurateAdjError::BarsParquetRead {
path: part_path.clone(),
source,
})?;
if n_lid != batch
|| n_date != batch
|| n_close != batch
|| n_curr != batch
|| batch_listing_ids.len() != batch
|| batch_session_dates.len() != batch
|| batch_closes.len() != batch
|| batch_currencies.len() != batch
{
return Err(RunCurateAdjError::BarsParquetIntegrity {
path: part_path.clone(),
detail: format!(
"column batch length mismatch: expected {batch}, got ({n_lid}, {n_date}, {n_close}, {n_curr})"
),
});
}
for i in 0..batch {
let curr_str =
std::str::from_utf8(batch_currencies[i].data()).map_err(|_| {
RunCurateAdjError::BarsParquetIntegrity {
path: part_path.clone(),
detail: "non-UTF8 currency value in bars_1d Parquet".to_string(),
}
})?;
let currency_id = currencies.intern(curr_str, part_path)?;
by_listing
.entry(batch_listing_ids[i])
.or_default()
.push(BarCloseEntry {
close: batch_closes[i],
session_date: batch_session_dates[i],
currency_id,
});
}
rows_loaded += batch;
remaining -= batch;
}
}
}
for (&listing_id, entries) in &mut by_listing {
entries.sort_unstable_by_key(|e| e.session_date);
for pair in entries.windows(2) {
if pair[0].session_date == pair[1].session_date {
return Err(RunCurateAdjError::BarsParquetIntegrity {
path: bars_1d_dir.to_path_buf(),
detail: format!(
"duplicate (listing_id={listing_id}, session_date={}) across bars_1d partitions",
pair[0].session_date
),
});
}
}
}
Ok(PrevCloseIndex {
by_listing,
currencies,
files_read: part_files.len(),
rows_loaded,
})
}
fn load_provider_mapping_table(path: &Path) -> Result<ProviderMappingTable, RunCurateAdjError> {
let mapping_rows = load_provider_mapping_tsv(path).map_err(|err| match err {
RunCurateBarsError::OpenInput {
label,
path,
source,
} => RunCurateAdjError::OpenInput {
label,
path,
source,
},
RunCurateBarsError::ReadInput {
label,
path,
source,
} => RunCurateAdjError::ReadInput {
label,
path,
source,
},
RunCurateBarsError::TsvParse { path, line, detail } => {
RunCurateAdjError::TsvParse { path, line, detail }
}
RunCurateBarsError::ProviderMapping { path, source } => {
RunCurateAdjError::ProviderMapping { path, source }
}
other => RunCurateAdjError::TsvParse {
path: path.to_path_buf(),
line: 0,
detail: other.to_string(),
},
})?;
ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateAdjError::ProviderMapping {
path: path.to_path_buf(),
source,
}
})
}
struct DecodedAdjInputs {
mapping: ProviderMappingTable,
splits: Vec<(Arc<str>, SplitEvent)>,
dividends: Vec<(Arc<str>, DividendEvent)>,
splits_docs_framed: u64,
splits_bytes_read: u64,
splits_decode: BsonQmActionDecodeStats,
dividends_docs_framed: u64,
dividends_bytes_read: u64,
dividends_decode: BsonQmActionDecodeStats,
dividends_with_prev_close: usize,
dividends_without_prev_close: usize,
}
#[inline]
fn intern_qm_key(keys: &mut HashSet<Arc<str>>, raw: &str) -> Arc<str> {
if let Some(existing) = keys.get(raw) {
return Arc::clone(existing);
}
let arc: Arc<str> = Arc::from(raw);
keys.insert(Arc::clone(&arc));
arc
}
fn decode_mapping_and_bson_inputs(
args: &CurateAdjFactorsArgs,
prev_close_index: &PrevCloseIndex,
) -> Result<DecodedAdjInputs, RunCurateAdjError> {
decode_mapping_and_bson_from_openers(
&args.provider_mapping,
&args.qm_splits,
|| {
File::open(&args.qm_splits).map_err(|source| RunCurateAdjError::OpenInput {
label: "qm-splits",
path: args.qm_splits.clone(),
source,
})
},
&args.qm_dividends,
|| {
File::open(&args.qm_dividends).map_err(|source| RunCurateAdjError::OpenInput {
label: "qm-dividends",
path: args.qm_dividends.clone(),
source,
})
},
prev_close_index,
)
}
fn decode_mapping_and_bson_from_openers<RS, FS, RD, FD>(
provider_mapping_path: &Path,
qm_splits_path: &Path,
open_splits: FS,
qm_dividends_path: &Path,
open_dividends: FD,
prev_close_index: &PrevCloseIndex,
) -> Result<DecodedAdjInputs, RunCurateAdjError>
where
RS: io::Read,
FS: FnOnce() -> Result<RS, RunCurateAdjError>,
RD: io::Read,
FD: FnOnce() -> Result<RD, RunCurateAdjError>,
{
let mapping = load_provider_mapping_table(provider_mapping_path)?;
let mut qm_keys: HashSet<Arc<str>> = HashSet::new();
// Stream `qmSplits`.
let splits_stream = open_splits()?;
let mut splits_reader =
RawBsonChunkReader::with_options(splits_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateAdjError::BsonStream {
label: "qm-splits",
path: qm_splits_path.to_path_buf(),
source,
},
)?;
let mut splits: Vec<(Arc<str>, SplitEvent)> = Vec::new();
let splits_decode = decode_qm_split_chunks(
&mut splits_reader,
|split| {
let key = intern_qm_key(&mut qm_keys, split.qm_search_code);
splits.push((key, split.to_split_event()));
},
|_offset, _err| {},
)
.map_err(|source| RunCurateAdjError::BsonStream {
label: "qm-splits",
path: qm_splits_path.to_path_buf(),
source,
})?;
let splits_docs_framed = splits_reader.docs_framed();
let splits_bytes_read = splits_reader.bytes_read();
// Stream `qmDividends` and attach strict pre-ex-date `prev_close` from `bars_1d`.
let dividends_stream = open_dividends()?;
let mut dividends_reader =
RawBsonChunkReader::with_options(dividends_stream, BsonStreamOptions::default()).map_err(
|source| RunCurateAdjError::BsonStream {
label: "qm-dividends",
path: qm_dividends_path.to_path_buf(),
source,
},
)?;
let mut dividends: Vec<(Arc<str>, DividendEvent)> = Vec::new();
let mut dividends_with_prev_close: usize = 0;
let mut dividends_without_prev_close: usize = 0;
let dividends_decode = decode_qm_dividend_chunks(
&mut dividends_reader,
|div| {
let key = intern_qm_key(&mut qm_keys, div.qm_search_code);
let (prev_close, prev_close_currency) =
match mapping.resolve("qm", div.qm_search_code, div.ex_date) {
Some(listing_id) => match prev_close_index.lookup(listing_id, div.ex_date) {
Some((close, curr)) => {
dividends_with_prev_close += 1;
(Some(close), Some(curr.to_owned()))
}
None => {
dividends_without_prev_close += 1;
(None, None)
}
},
None => (None, None),
};
dividends.push((key, div.to_dividend_event(prev_close, prev_close_currency)));
},
|_offset, _err| {},
)
.map_err(|source| RunCurateAdjError::BsonStream {
label: "qm-dividends",
path: qm_dividends_path.to_path_buf(),
source,
})?;
let dividends_docs_framed = dividends_reader.docs_framed();
let dividends_bytes_read = dividends_reader.bytes_read();
Ok(DecodedAdjInputs {
mapping,
splits,
dividends,
splits_docs_framed,
splits_bytes_read,
splits_decode,
dividends_docs_framed,
dividends_bytes_read,
dividends_decode,
dividends_with_prev_close,
dividends_without_prev_close,
})
}
fn map_curate_write_error_paths(
out_dir: &Path,
qm_splits_path: &Path,
qm_dividends_path: &Path,
source: CurateAdjWriteError,
) -> RunCurateAdjError {
let input_path = match &source {
CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeySplit { .. }) => {
Some(qm_splits_path.to_path_buf())
}
CurateAdjWriteError::Curate(CurateAdjError::ConflictingCrossKeyDividend { .. }) => {
Some(qm_dividends_path.to_path_buf())
}
_ => None,
};
RunCurateAdjError::CurateWrite {
out_dir: out_dir.to_path_buf(),
input_path,
source,
}
}
/// Runs the end-to-end `curate-adj-factors` file-to-Parquet pipeline via
/// [`curate_and_write_adj_factors`].
///
/// Any input, schema, mapping, or curation error returns before touching `args.out_dir`,
/// leaving any pre-existing `<out_dir>/adj_factors/part.parquet` byte-identical.
pub fn run_curate_adj_factors(
args: &CurateAdjFactorsArgs,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
run_curate_adj_factors_fenced(args, None)
}
/// Runs the end-to-end `curate-adj-factors` file-to-Parquet pipeline with an optional
/// [`AdjPointInTimeFence`] (publishing a verified `point_in_time_fenced` snapshot when `Some`).
pub fn run_curate_adj_factors_fenced(
args: &CurateAdjFactorsArgs,
fence: Option<AdjPointInTimeFence>,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
let start = Instant::now();
validate_out_dir(&args.out_dir)?;
let prev_close_index = load_prev_close_index(&args.bars_1d_dir)?;
let bars_files_read = prev_close_index.files_read;
let bars_rows_loaded = prev_close_index.rows_loaded;
let bars_listings_indexed = prev_close_index.by_listing.len();
let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?;
drop(prev_close_index);
finish_curate_adj_factors(
decoded,
&args.out_dir,
&args.qm_splits,
&args.qm_dividends,
fence,
bars_files_read,
bars_rows_loaded,
bars_listings_indexed,
start,
)
}
/// Runs `curate-adj-factors` from arbitrary raw-BSON [`io::Read`] streams.
#[allow(clippy::too_many_arguments)]
pub fn run_curate_adj_factors_with_readers<RS: io::Read, RD: io::Read>(
provider_mapping_path: &Path,
bars_1d_dir: &Path,
qm_splits_input: (&Path, RS),
qm_dividends_input: (&Path, RD),
out_dir: &Path,
fence: Option<AdjPointInTimeFence>,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
let start = Instant::now();
validate_out_dir(out_dir)?;
let prev_close_index = load_prev_close_index(bars_1d_dir)?;
let bars_files_read = prev_close_index.files_read;
let bars_rows_loaded = prev_close_index.rows_loaded;
let bars_listings_indexed = prev_close_index.by_listing.len();
let (qm_splits_path, splits_stream) = qm_splits_input;
let (qm_dividends_path, dividends_stream) = qm_dividends_input;
let decoded = decode_mapping_and_bson_from_openers(
provider_mapping_path,
qm_splits_path,
|| Ok(splits_stream),
qm_dividends_path,
|| Ok(dividends_stream),
&prev_close_index,
)?;
drop(prev_close_index);
finish_curate_adj_factors(
decoded,
out_dir,
qm_splits_path,
qm_dividends_path,
fence,
bars_files_read,
bars_rows_loaded,
bars_listings_indexed,
start,
)
}
#[allow(clippy::too_many_arguments)]
fn finish_curate_adj_factors(
decoded: DecodedAdjInputs,
out_dir: &Path,
qm_splits_path: &Path,
qm_dividends_path: &Path,
fence: Option<AdjPointInTimeFence>,
bars_files_read: usize,
bars_rows_loaded: usize,
bars_listings_indexed: usize,
start: Instant,
) -> Result<CurateAdjFactorsRunReport, RunCurateAdjError> {
let write_report = match fence {
Some(f) => curate_and_write_adj_factors_as_of(
out_dir,
&decoded.mapping,
"qm",
decoded.splits,
decoded.dividends,
f,
AdjFactorsWriteOptions::default(),
),
None => curate_and_write_adj_factors(
out_dir,
&decoded.mapping,
"qm",
decoded.splits,
decoded.dividends,
AdjFactorsWriteOptions::default(),
),
}
.map_err(|source| map_curate_write_error_paths(out_dir, qm_splits_path, qm_dividends_path, source))?;
Ok(CurateAdjFactorsRunReport {
bars_files_read,
bars_rows_loaded,
bars_listings_indexed,
splits_docs_framed: decoded.splits_docs_framed,
splits_bytes_read: decoded.splits_bytes_read,
splits_decode: decoded.splits_decode,
dividends_docs_framed: decoded.dividends_docs_framed,
dividends_bytes_read: decoded.dividends_bytes_read,
dividends_decode: decoded.dividends_decode,
dividends_with_prev_close: decoded.dividends_with_prev_close,
dividends_without_prev_close: decoded.dividends_without_prev_close,
curate_stats: write_report.curate_stats,
write_stats: write_report.write_stats,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
fn compute_rows_checksum(rows: &[AdjFactorsParquetRow]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
let mix = |mut h: u64, v: u64| -> u64 {
h ^= v;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
h
};
for row in rows {
hash = mix(hash, row.listing_id as u64);
hash = mix(hash, row.ex_date as u64);
hash = mix(hash, row.split_factor.to_bits());
hash = mix(hash, row.div_cash.to_bits());
match row.div_currency.as_deref() {
Some(c) => {
hash = mix(hash, 1);
for &b in c.as_bytes() {
hash = mix(hash, u64::from(b));
}
}
None => {
hash = mix(hash, 0);
}
}
hash = mix(hash, row.cum_split_factor.to_bits());
hash = mix(hash, row.cum_total_factor.to_bits());
hash = mix(hash, row.known_at_micros as u64);
}
hash
}
/// Stage-timed variant of [`run_curate_adj_factors`] used internally by `bench-curate-adj-cmd`.
///
/// Times `bars_load`, `decode` (mapping + BSON streams + `prev_close` attach), `curate`, and
/// `write` (`write_adj_factors_snapshot_parquet`, identical footer-verified snapshot as
/// [`curate_and_write_adj_factors`]) separately.
pub(crate) fn run_curate_adj_factors_timed(
args: &CurateAdjFactorsArgs,
) -> Result<CurateAdjFactorsTimedRun, RunCurateAdjError> {
let total_start = Instant::now();
validate_out_dir(&args.out_dir)?;
let bars_start = Instant::now();
let prev_close_index = load_prev_close_index(&args.bars_1d_dir)?;
let bars_load_elapsed_secs = bars_start.elapsed().as_secs_f64();
let bars_files_read = prev_close_index.files_read;
let bars_rows_loaded = prev_close_index.rows_loaded;
let bars_listings_indexed = prev_close_index.by_listing.len();
let decode_start = Instant::now();
let decoded = decode_mapping_and_bson_inputs(args, &prev_close_index)?;
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
drop(prev_close_index);
let curate_start = Instant::now();
let curated = curate_adj_factors(
&decoded.mapping,
"qm",
decoded.splits,
decoded.dividends,
)
.map_err(|source| {
map_curate_write_error_paths(
&args.out_dir,
&args.qm_splits,
&args.qm_dividends,
CurateAdjWriteError::Curate(source),
)
})?;
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
let checksum = compute_rows_checksum(&curated.rows);
let write_start = Instant::now();
let write_stats = write_adj_factors_snapshot_parquet(
&args.out_dir,
&curated.rows,
curated.snapshot_kind,
AdjFactorsWriteOptions::default(),
)
.map_err(|source| {
map_curate_write_error_paths(
&args.out_dir,
&args.qm_splits,
&args.qm_dividends,
CurateAdjWriteError::Parquet(source),
)
})?;
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
let report = CurateAdjFactorsRunReport {
bars_files_read,
bars_rows_loaded,
bars_listings_indexed,
splits_docs_framed: decoded.splits_docs_framed,
splits_bytes_read: decoded.splits_bytes_read,
splits_decode: decoded.splits_decode,
dividends_docs_framed: decoded.dividends_docs_framed,
dividends_bytes_read: decoded.dividends_bytes_read,
dividends_decode: decoded.dividends_decode,
dividends_with_prev_close: decoded.dividends_with_prev_close,
dividends_without_prev_close: decoded.dividends_without_prev_close,
curate_stats: curated.stats,
write_stats,
elapsed_secs: total_start.elapsed().as_secs_f64(),
};
Ok(CurateAdjFactorsTimedRun {
report,
bars_load_elapsed_secs,
decode_elapsed_secs,
curate_elapsed_secs,
write_elapsed_secs,
checksum,
})
}
/// Formats [`CurateAdjFactorsRunReport`] into a deterministic machine-readable `key=value` summary.
///
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
pub fn format_curate_adj_report(report: &CurateAdjFactorsRunReport) -> String {
format!(
"curate-etl curate-adj-factors\n\
\x20 bars_1d: files_read={} rows_loaded={} listings_indexed={}\n\
\x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
\x20 dividends_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
\x20 prev_close: with_prev_close={} without_prev_close={} unmapped={}\n\
\x20 builder: splits_in={} dividends_in={} rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}\n\
\x20 curate: splits_in={} dividends_in={} rows_out={} listings_out={} splits_unmapped={} divs_unmapped={} splits_fenced={} divs_fenced={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}\n\
\x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\
\x20 timing: elapsed_secs={:.6}",
report.bars_files_read,
report.bars_rows_loaded,
report.bars_listings_indexed,
report.splits_docs_framed,
report.splits_bytes_read,
report.splits_decode.docs_in,
report.splits_decode.decoded,
report.splits_decode.split_noop_ratio_one,
report.splits_decode.rejected_total(),
report.splits_decode.rejected_missing_field,
report.splits_decode.rejected_empty_field,
report.splits_decode.rejected_wrong_type,
report.splits_decode.rejected_malformed_date,
report.splits_decode.rejected_invalid_number,
report.splits_decode.rejected_corrupt_document,
report.dividends_docs_framed,
report.dividends_bytes_read,
report.dividends_decode.docs_in,
report.dividends_decode.decoded,
report.dividends_decode.rejected_total(),
report.dividends_decode.rejected_missing_field,
report.dividends_decode.rejected_empty_field,
report.dividends_decode.rejected_wrong_type,
report.dividends_decode.rejected_malformed_date,
report.dividends_decode.rejected_invalid_number,
report.dividends_decode.rejected_corrupt_document,
report.dividends_with_prev_close,
report.dividends_without_prev_close,
report.curate_stats.dividends_dropped_unmapped,
report.curate_stats.builder.split_events_in,
report.curate_stats.builder.dividend_events_in,
report.curate_stats.builder.rows_out,
report.curate_stats.builder.keys_out,
report.curate_stats.builder.split_noops_dropped,
report.curate_stats.builder.dividend_zero_cash_dropped,
report.curate_stats.builder.dividends_missing_prev_close,
report.curate_stats.builder.dividends_currency_mismatch,
report.curate_stats.builder.dividends_not_below_prev_close,
report.curate_stats.splits_in,
report.curate_stats.dividends_in,
report.curate_stats.rows_out,
report.curate_stats.listings_out,
report.curate_stats.splits_dropped_unmapped,
report.curate_stats.dividends_dropped_unmapped,
report.curate_stats.splits_dropped_fenced,
report.curate_stats.dividends_dropped_fenced,
report.curate_stats.splits_collision_collapsed,
report.curate_stats.dividends_collision_collapsed,
report.curate_stats.listing_collision_collapsed,
report.write_stats.rows_written,
report.write_stats.files_written,
report.write_stats.row_groups_written,
report.write_stats.bytes_written,
report.elapsed_secs,
)
}
#[cfg(test)]
#[path = "run_curate_adj_tests.rs"]
mod tests;