1395 lines
52 KiB
Rust
1395 lines
52 KiB
Rust
//! File-to-file `curate-bars-1d` command runner (`M1.2z`).
|
|
//!
|
|
//! Streams concatenated raw BSON `eodPrices` and `qmSplits` dump files alongside
|
|
//! `provider_mapping` and `listing_currencies` TSV files into an atomically published
|
|
//! `<out_dir>/bars_1d/year=YYYY/part.parquet` dataset via [`curate_and_write_bars_1d`].
|
|
//!
|
|
//! # TSV Formats (strict, headerless, `\t`-separated)
|
|
//! - `provider_mapping`:
|
|
//! `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
|
//! (`source` and `source_id` are preserved verbatim — never trimmed).
|
|
//! - `listing_currencies`:
|
|
//! `listing_id \t currency`
|
|
//! (unique positive `listing_id` per row; non-blank currency code).
|
|
//! - Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line.
|
|
//!
|
|
//! # Missing-Currency Behavior
|
|
//! Delegated unchanged to [`curate_bars_1d`]: any mapped `listing_id` absent from
|
|
//! `listing_currencies` (or mapping to a blank string) is dropped and counted in
|
|
//! [`CurateBars1dStats::dropped_missing_currency`] rather than failing the run.
|
|
|
|
use std::borrow::Cow;
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::error::Error;
|
|
use std::fmt;
|
|
use std::fs::File;
|
|
use std::io::{self, BufRead, BufReader};
|
|
use std::mem::size_of;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::Instant;
|
|
|
|
use crate::bars::{EodDailyBar, QmRawVolume, VolumeMismatchSample};
|
|
use crate::bson_eod_prices::{parse_ymd_strict_days, BsonEodDecodeStats};
|
|
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
|
use crate::bson_qm_prices::BsonQmPriceDecodeStats;
|
|
use crate::bson_stream::{
|
|
decode_eod_price_chunks, decode_qm_price_chunks, decode_qm_split_chunks, BsonStreamError,
|
|
RawBsonChunkReader,
|
|
};
|
|
use crate::curate_bars::{
|
|
curate_and_write_bars_1d, curate_bars_1d, CurateBars1dStats, CurateBarsWriteError,
|
|
};
|
|
use crate::parquet_bars::{
|
|
default_parallel_threads, write_bars_1d_dataset, Bars1dWriteOptions, Bars1dWriteStats,
|
|
ParquetBarsError,
|
|
};
|
|
use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable};
|
|
use crate::shorts::epoch_days_to_ymd;
|
|
use crate::split::{SplitError, SplitEvent, SplitTable};
|
|
|
|
/// Default relative volume tolerance passed to `curate_bars_1d` (matches `bench-curate-bars`).
|
|
pub const DEFAULT_CURATE_BARS_REL_TOLERANCE: f64 = 0.01;
|
|
|
|
/// Default Parquet writer thread count for `curate-bars-1d` (`std::thread::available_parallelism()`,
|
|
/// falling back to `1`).
|
|
pub fn default_curate_bars_threads() -> usize {
|
|
default_parallel_threads()
|
|
}
|
|
|
|
/// Parsed arguments for the `curate-bars-1d` CLI command.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct CurateBars1dArgs {
|
|
pub eod_prices: PathBuf,
|
|
pub qm_splits: PathBuf,
|
|
pub qm_prices: Option<PathBuf>,
|
|
pub provider_mapping: PathBuf,
|
|
pub listing_currencies: PathBuf,
|
|
pub out_dir: PathBuf,
|
|
pub rel_tolerance: f64,
|
|
pub threads: usize,
|
|
}
|
|
|
|
/// Accounting counters for re-keying `qmSplits` (`qmSearchCode` -> `listing_id` -> `eodSearchCode`).
|
|
///
|
|
/// Conservation invariant (paired with `splits_decode: BsonQmActionDecodeStats`):
|
|
/// `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_decode.rejected_total()`.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct SplitRekeyStats {
|
|
/// Total `qmSplits` documents framed and fed into the decoder (`== splits_decode.docs_in`).
|
|
pub splits_in: usize,
|
|
/// Decoded `qmSplits` rows with `ratio == 1.0` dropped as no-ops before re-keying.
|
|
pub splits_noop_dropped: usize,
|
|
/// Non-no-op decoded splits whose `("qm", qm_search_code, ex_date)` had no mapping.
|
|
pub splits_unmapped_qm: usize,
|
|
/// Mapped splits whose `listing_id` had no `"eod"` `source_id` partner in `provider_mapping`.
|
|
pub splits_no_eod_partner: usize,
|
|
/// Cross-key QM alias split documents on the same `(listing_id, ex_date)` with bitwise
|
|
/// identical ratio collapsed before fanning out to `"eod"` partners.
|
|
pub splits_collision_collapsed: usize,
|
|
/// Non-no-op splits attached to at least one `"eod"` `source_id` after cross-key compaction.
|
|
pub splits_applied: usize,
|
|
/// Total `(eod_source_id, SplitEvent)` pairs pushed into `SplitTable` (may exceed
|
|
/// `splits_applied` when a listing has multiple `"eod"` `source_id`s).
|
|
pub split_events_attached: usize,
|
|
}
|
|
|
|
/// Accounting counters for date-aware re-keying of `qmPrices`
|
|
/// (`qmSearchCode` -> `listing_id` -> `eodSearchCode`).
|
|
///
|
|
/// Conservation invariants (paired with `qm_prices_decode: BsonQmPriceDecodeStats` and
|
|
/// `curate_stats.builder: Bars1dStats`):
|
|
/// - `qm_in == qm_attached + qm_unmapped_qm + qm_no_eod_partner + qm_prices_decode.rejected_total()`
|
|
/// - `qm_volumes_attached == curate_stats.builder.qm_rows_in`
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct QmVolumeRekeyStats {
|
|
/// Total `qmPrices` documents framed and fed into the decoder (`== qm_prices_decode.docs_in`).
|
|
pub qm_in: usize,
|
|
/// Decoded `qmPrices` rows whose `("qm", qm_search_code, session_date)` had no mapping.
|
|
pub qm_unmapped_qm: usize,
|
|
/// Mapped `qmPrices` rows whose `listing_id` had no `"eod"` mapping covering `session_date`.
|
|
pub qm_no_eod_partner: usize,
|
|
/// Decoded `qmPrices` rows attached to at least one date-covering `"eod"` `source_id`.
|
|
pub qm_attached: usize,
|
|
/// Total `QmRawVolume<Arc<str>>` observations pushed into `build_bars_1d` (`== builder.qm_rows_in`).
|
|
pub qm_volumes_attached: usize,
|
|
}
|
|
|
|
/// Full run report produced by [`run_curate_bars_1d`].
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct CurateBars1dRunReport {
|
|
pub eod_docs_framed: u64,
|
|
pub eod_bytes_read: u64,
|
|
pub eod_decode: BsonEodDecodeStats,
|
|
pub splits_docs_framed: u64,
|
|
pub splits_bytes_read: u64,
|
|
pub splits_decode: BsonQmActionDecodeStats,
|
|
pub split_rekey: SplitRekeyStats,
|
|
pub qm_prices_present: bool,
|
|
pub qm_prices_docs_framed: u64,
|
|
pub qm_prices_bytes_read: u64,
|
|
pub qm_prices_decode: BsonQmPriceDecodeStats,
|
|
pub qm_rekey: QmVolumeRekeyStats,
|
|
pub buffered_qm_bytes: usize,
|
|
pub bars_unmapped_source_dropped: usize,
|
|
pub buffered_bars: usize,
|
|
/// Approximate heap bytes occupied by the buffered `Vec<EodDailyBar<Arc<str>>>` capacity plus
|
|
/// the interned `"eod"` `Arc<str>` key allocations.
|
|
pub buffered_bar_bytes: usize,
|
|
pub curate_stats: CurateBars1dStats,
|
|
pub write_stats: Bars1dWriteStats,
|
|
pub mismatch_samples: Vec<VolumeMismatchSample<Arc<str>>>,
|
|
pub threads: usize,
|
|
pub elapsed_secs: f64,
|
|
}
|
|
|
|
/// Stage-timed run output used internally by `bench-curate-bars-cmd`.
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub(crate) struct CurateBars1dTimedRun {
|
|
pub report: CurateBars1dRunReport,
|
|
pub decode_elapsed_secs: f64,
|
|
pub qm_decode_rekey_elapsed_secs: f64,
|
|
pub curate_elapsed_secs: f64,
|
|
pub write_elapsed_secs: f64,
|
|
}
|
|
|
|
/// Stage-timed run output comparing sequential (`threads=1`) vs parallel (`threads=par_threads`)
|
|
/// Parquet writes on the same curated rows for `bench-curate-bars-cmd`.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub(crate) struct CurateBars1dTimedCompareRun {
|
|
pub report: CurateBars1dRunReport,
|
|
pub decode_elapsed_secs: f64,
|
|
pub qm_decode_rekey_elapsed_secs: f64,
|
|
pub curate_elapsed_secs: f64,
|
|
pub write_seq_elapsed_secs: f64,
|
|
pub write_par_elapsed_secs: f64,
|
|
pub write_stats_seq: Bars1dWriteStats,
|
|
}
|
|
|
|
/// Typed errors returned by [`run_curate_bars_1d`] and its TSV loaders.
|
|
///
|
|
/// 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 RunCurateBarsError {
|
|
InvalidOutDir {
|
|
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,
|
|
},
|
|
BsonStream {
|
|
label: &'static str,
|
|
path: PathBuf,
|
|
source: BsonStreamError,
|
|
},
|
|
SplitTable {
|
|
path: PathBuf,
|
|
source: SplitError,
|
|
},
|
|
ConflictingCrossKeySplit {
|
|
path: PathBuf,
|
|
listing_id: i32,
|
|
ex_date: i32,
|
|
first_key: String,
|
|
first_ratio: f64,
|
|
second_key: String,
|
|
second_ratio: f64,
|
|
},
|
|
CurateWrite {
|
|
out_dir: PathBuf,
|
|
source: CurateBarsWriteError,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for RunCurateBarsError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::InvalidOutDir { path, detail } => {
|
|
write!(f, "invalid --out '{}': {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::BsonStream {
|
|
label,
|
|
path,
|
|
source,
|
|
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
|
Self::SplitTable { path, source } => {
|
|
write!(f, "invalid split table from '{}': {source}", path.display())
|
|
}
|
|
Self::ConflictingCrossKeySplit {
|
|
path,
|
|
listing_id,
|
|
ex_date,
|
|
first_key,
|
|
first_ratio,
|
|
second_key,
|
|
second_ratio,
|
|
} => write!(
|
|
f,
|
|
"conflicting cross-key split in '{}': listing_id={listing_id} ex_date={ex_date} '{first_key}' ({first_ratio}) vs '{second_key}' ({second_ratio})",
|
|
path.display()
|
|
),
|
|
Self::CurateWrite { out_dir, source } => {
|
|
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Error for RunCurateBarsError {
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
match self {
|
|
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
|
|
Self::ProviderMapping { source, .. } => Some(source),
|
|
Self::BsonStream { source, .. } => Some(source),
|
|
Self::SplitTable { source, .. } => Some(source),
|
|
Self::CurateWrite { source, .. } => Some(source),
|
|
Self::InvalidOutDir { .. }
|
|
| Self::TsvParse { .. }
|
|
| Self::ConflictingCrossKeySplit { .. } => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Parses a strictly positive ASCII base-10 `i32` (no leading/trailing whitespace or sign).
|
|
pub(crate) fn parse_strict_positive_i32(raw: &str) -> Option<i32> {
|
|
if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
|
|
return None;
|
|
}
|
|
let val = raw.parse::<i32>().ok()?;
|
|
if val > 0 {
|
|
Some(val)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// Streams a strict headerless TSV file line by line, enforcing `\n`/`\r\n` endings, valid UTF-8,
|
|
/// and at most one trailing blank line.
|
|
pub(crate) fn read_tsv_lines<F>(
|
|
path: &Path,
|
|
label: &'static str,
|
|
mut on_line: F,
|
|
) -> Result<(), RunCurateBarsError>
|
|
where
|
|
F: FnMut(usize, &str) -> Result<(), String>,
|
|
{
|
|
let file = File::open(path).map_err(|source| RunCurateBarsError::OpenInput {
|
|
label,
|
|
path: path.to_path_buf(),
|
|
source,
|
|
})?;
|
|
let mut reader = BufReader::new(file);
|
|
let mut raw_buf: Vec<u8> = Vec::with_capacity(256);
|
|
let mut line_no: usize = 0;
|
|
let mut pending_blank_line: Option<usize> = None;
|
|
|
|
loop {
|
|
raw_buf.clear();
|
|
let bytes_read =
|
|
reader
|
|
.read_until(b'\n', &mut raw_buf)
|
|
.map_err(|source| RunCurateBarsError::ReadInput {
|
|
label,
|
|
path: path.to_path_buf(),
|
|
source,
|
|
})?;
|
|
if bytes_read == 0 {
|
|
break;
|
|
}
|
|
line_no += 1;
|
|
|
|
let mut slice = raw_buf.as_slice();
|
|
if slice.ends_with(b"\n") {
|
|
slice = &slice[..slice.len() - 1];
|
|
if slice.ends_with(b"\r") {
|
|
slice = &slice[..slice.len() - 1];
|
|
}
|
|
}
|
|
if slice.contains(&b'\r') {
|
|
return Err(RunCurateBarsError::TsvParse {
|
|
path: path.to_path_buf(),
|
|
line: line_no,
|
|
detail: "unexpected carriage return inside TSV line".to_string(),
|
|
});
|
|
}
|
|
|
|
let text = std::str::from_utf8(slice).map_err(|_| RunCurateBarsError::TsvParse {
|
|
path: path.to_path_buf(),
|
|
line: line_no,
|
|
detail: "invalid UTF-8 in TSV line".to_string(),
|
|
})?;
|
|
|
|
if text.is_empty() {
|
|
if pending_blank_line.is_some() {
|
|
return Err(RunCurateBarsError::TsvParse {
|
|
path: path.to_path_buf(),
|
|
line: line_no,
|
|
detail: "multiple trailing blank lines are not allowed".to_string(),
|
|
});
|
|
}
|
|
pending_blank_line = Some(line_no);
|
|
continue;
|
|
}
|
|
|
|
if let Some(blank_line) = pending_blank_line.take() {
|
|
return Err(RunCurateBarsError::TsvParse {
|
|
path: path.to_path_buf(),
|
|
line: blank_line,
|
|
detail: "blank line is only allowed as a single trailing line".to_string(),
|
|
});
|
|
}
|
|
|
|
on_line(line_no, text).map_err(|detail| RunCurateBarsError::TsvParse {
|
|
path: path.to_path_buf(),
|
|
line: line_no,
|
|
detail,
|
|
})?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Loads `provider_mapping.tsv` into raw [`ProviderMappingRow`] records.
|
|
///
|
|
/// Format (no header, 5 `\t`-separated columns):
|
|
/// `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
|
///
|
|
/// `source` and `source_id` are preserved verbatim (never trimmed).
|
|
pub fn load_provider_mapping_tsv(
|
|
path: &Path,
|
|
) -> Result<Vec<ProviderMappingRow>, RunCurateBarsError> {
|
|
let mut rows = Vec::new();
|
|
read_tsv_lines(path, "provider-mapping", |_line_no, line| {
|
|
let mut fields = line.split('\t');
|
|
let source = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 5 tab-separated columns".to_string())?;
|
|
let source_id = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 5 tab-separated columns (got 1)".to_string())?;
|
|
let valid_from_str = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 5 tab-separated columns (got 2)".to_string())?;
|
|
let valid_to_str = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 5 tab-separated columns (got 3)".to_string())?;
|
|
let listing_id_str = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 5 tab-separated columns (got 4)".to_string())?;
|
|
if fields.next().is_some() {
|
|
return Err("expected 5 tab-separated columns (got more than 5)".to_string());
|
|
}
|
|
|
|
if source.trim().is_empty() {
|
|
return Err("source column must not be empty or blank".to_string());
|
|
}
|
|
if source_id.trim().is_empty() {
|
|
return Err("source_id column must not be empty or blank".to_string());
|
|
}
|
|
|
|
let valid_from = parse_ymd_strict_days(valid_from_str).ok_or_else(|| {
|
|
format!("invalid valid_from date '{valid_from_str}' (expected YYYY-MM-DD)")
|
|
})?;
|
|
let valid_to = if valid_to_str.is_empty() {
|
|
None
|
|
} else {
|
|
Some(parse_ymd_strict_days(valid_to_str).ok_or_else(|| {
|
|
format!("invalid valid_to date '{valid_to_str}' (expected YYYY-MM-DD or empty)")
|
|
})?)
|
|
};
|
|
let listing_id = parse_strict_positive_i32(listing_id_str).ok_or_else(|| {
|
|
format!("invalid listing_id '{listing_id_str}' (expected positive integer)")
|
|
})?;
|
|
|
|
rows.push(ProviderMappingRow {
|
|
source: source.to_owned(),
|
|
source_id: source_id.to_owned(),
|
|
valid_from,
|
|
valid_to,
|
|
listing_id,
|
|
});
|
|
Ok(())
|
|
})?;
|
|
Ok(rows)
|
|
}
|
|
|
|
/// Loads `listing_currencies.tsv` into a `listing_id -> currency` map.
|
|
///
|
|
/// Format (no header, 2 `\t`-separated columns):
|
|
/// `listing_id \t currency`
|
|
pub fn load_listing_currencies_tsv(
|
|
path: &Path,
|
|
) -> Result<HashMap<i32, Cow<'static, str>>, RunCurateBarsError> {
|
|
let mut currencies: HashMap<i32, Cow<'static, str>> = HashMap::new();
|
|
read_tsv_lines(path, "listing-currencies", |_line_no, line| {
|
|
let mut fields = line.split('\t');
|
|
let listing_id_str = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 2 tab-separated columns".to_string())?;
|
|
let currency_str = fields
|
|
.next()
|
|
.ok_or_else(|| "expected 2 tab-separated columns (got 1)".to_string())?;
|
|
if fields.next().is_some() {
|
|
return Err("expected 2 tab-separated columns (got more than 2)".to_string());
|
|
}
|
|
|
|
let listing_id = parse_strict_positive_i32(listing_id_str).ok_or_else(|| {
|
|
format!("invalid listing_id '{listing_id_str}' (expected positive integer)")
|
|
})?;
|
|
if currency_str.trim().is_empty() {
|
|
return Err("currency column must not be empty or blank".to_string());
|
|
}
|
|
|
|
let currency: Cow<'static, str> = match currency_str {
|
|
"USD" => Cow::Borrowed("USD"),
|
|
"CAD" => Cow::Borrowed("CAD"),
|
|
other => Cow::Owned(other.to_owned()),
|
|
};
|
|
|
|
if currencies.insert(listing_id, currency).is_some() {
|
|
return Err(format!(
|
|
"duplicate listing_id {listing_id} in listing_currencies"
|
|
));
|
|
}
|
|
Ok(())
|
|
})?;
|
|
Ok(currencies)
|
|
}
|
|
|
|
struct LoadedCurateBarsInputs {
|
|
mapping: ProviderMappingTable,
|
|
currencies: HashMap<i32, Cow<'static, str>>,
|
|
splits: SplitTable<Arc<str>>,
|
|
bars: Vec<EodDailyBar<Arc<str>>>,
|
|
qm_volumes: Vec<QmRawVolume<Arc<str>>>,
|
|
eod_docs_framed: u64,
|
|
eod_bytes_read: u64,
|
|
eod_decode: BsonEodDecodeStats,
|
|
splits_docs_framed: u64,
|
|
splits_bytes_read: u64,
|
|
splits_decode: BsonQmActionDecodeStats,
|
|
split_rekey: SplitRekeyStats,
|
|
qm_prices_present: bool,
|
|
qm_prices_docs_framed: u64,
|
|
qm_prices_bytes_read: u64,
|
|
qm_prices_decode: BsonQmPriceDecodeStats,
|
|
qm_rekey: QmVolumeRekeyStats,
|
|
buffered_qm_bytes: usize,
|
|
qm_decode_rekey_elapsed_secs: f64,
|
|
bars_unmapped_source_dropped: usize,
|
|
buffered_bars: usize,
|
|
buffered_bar_bytes: usize,
|
|
}
|
|
|
|
struct EodListingRange {
|
|
valid_from: i32,
|
|
valid_to: Option<i32>,
|
|
key: Arc<str>,
|
|
}
|
|
|
|
#[inline]
|
|
fn valid_to_sort_key(valid_to: Option<i32>) -> (u8, i32) {
|
|
match valid_to {
|
|
Some(to) => (0, to),
|
|
None => (1, i32::MAX),
|
|
}
|
|
}
|
|
|
|
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> {
|
|
if out_dir.exists() && !out_dir.is_dir() {
|
|
return Err(RunCurateBarsError::InvalidOutDir {
|
|
path: out_dir.to_path_buf(),
|
|
detail: "path exists and is not a directory".to_string(),
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
struct MappedQmSplit {
|
|
listing_id: i32,
|
|
ex_date: i32,
|
|
qm_key: String,
|
|
ratio: f64,
|
|
}
|
|
|
|
/// Applies the `curate_adj` cross-key split policy by `(listing_id, ex_date)` before fanning out
|
|
/// to `"eod"` partners:
|
|
/// - Single-QM-key groups pass through unchanged (preserving `SplitTable` same-day multiplication).
|
|
/// - Multi-QM-key groups with bitwise-identical ratios collapse to one event (`collapsed += n - 1`).
|
|
/// - Multi-QM-key groups with conflicting ratios fail closed with `ConflictingCrossKeySplit`.
|
|
fn compact_mapped_qm_splits(
|
|
path: &Path,
|
|
mut mapped: Vec<MappedQmSplit>,
|
|
) -> Result<(Vec<(i32, SplitEvent)>, usize), RunCurateBarsError> {
|
|
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.qm_key.cmp(&b.qm_key))
|
|
.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<MappedQmSplit> = 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].qm_key.as_str();
|
|
let last_key = group[group_len - 1].qm_key.as_str();
|
|
if first_key == last_key {
|
|
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 {
|
|
let (lhs, rhs) = if let Some(other) = group[1..]
|
|
.iter()
|
|
.find(|e| e.qm_key.as_str() != 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.qm_key.as_str() != first_key)
|
|
.expect("distinct source key exists");
|
|
(bad, other_key)
|
|
};
|
|
return Err(RunCurateBarsError::ConflictingCrossKeySplit {
|
|
path: path.to_path_buf(),
|
|
listing_id,
|
|
ex_date,
|
|
first_key: lhs.qm_key.clone(),
|
|
first_ratio: lhs.ratio,
|
|
second_key: rhs.qm_key.clone(),
|
|
second_ratio: rhs.ratio,
|
|
});
|
|
}
|
|
}
|
|
|
|
Ok((out, collapsed_total))
|
|
}
|
|
|
|
fn load_and_decode_inputs(
|
|
args: &CurateBars1dArgs,
|
|
) -> Result<LoadedCurateBarsInputs, RunCurateBarsError> {
|
|
validate_out_dir(&args.out_dir)?;
|
|
|
|
let qm_prices_path = args.qm_prices.clone();
|
|
load_and_decode_from_openers(
|
|
&args.provider_mapping,
|
|
&args.listing_currencies,
|
|
&args.qm_splits,
|
|
|| {
|
|
File::open(&args.qm_splits).map_err(|source| RunCurateBarsError::OpenInput {
|
|
label: "qm-splits",
|
|
path: args.qm_splits.clone(),
|
|
source,
|
|
})
|
|
},
|
|
&args.eod_prices,
|
|
|| {
|
|
File::open(&args.eod_prices).map_err(|source| RunCurateBarsError::OpenInput {
|
|
label: "eod-prices",
|
|
path: args.eod_prices.clone(),
|
|
source,
|
|
})
|
|
},
|
|
qm_prices_path.as_deref(),
|
|
|| match &qm_prices_path {
|
|
Some(path) => Ok(Some(File::open(path).map_err(|source| {
|
|
RunCurateBarsError::OpenInput {
|
|
label: "qm-prices",
|
|
path: path.clone(),
|
|
source,
|
|
}
|
|
})?)),
|
|
None => Ok(None),
|
|
},
|
|
)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn load_and_decode_from_openers<RS, FS, RE, FE, RQ, FQ>(
|
|
provider_mapping_path: &Path,
|
|
listing_currencies_path: &Path,
|
|
qm_splits_path: &Path,
|
|
open_splits: FS,
|
|
eod_prices_path: &Path,
|
|
open_eod: FE,
|
|
qm_prices_path: Option<&Path>,
|
|
open_qm: FQ,
|
|
) -> Result<LoadedCurateBarsInputs, RunCurateBarsError>
|
|
where
|
|
RS: io::Read,
|
|
FS: FnOnce() -> Result<RS, RunCurateBarsError>,
|
|
RE: io::Read,
|
|
FE: FnOnce() -> Result<RE, RunCurateBarsError>,
|
|
RQ: io::Read,
|
|
FQ: FnOnce() -> Result<Option<RQ>, RunCurateBarsError>,
|
|
{
|
|
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)?;
|
|
let currencies = load_listing_currencies_tsv(listing_currencies_path)?;
|
|
|
|
// Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
|
// When `--qm-prices` is provided, also build a date-aware reverse index
|
|
// `listing_id -> [(valid_from, valid_to, Arc<str>)]` so reused EOD tickers never receive
|
|
// cross-check observations outside their mapping range.
|
|
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
|
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
|
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
|
|
let track_eod_ranges = qm_prices_path.is_some();
|
|
for row in &mapping_rows {
|
|
if row.source == "eod" {
|
|
let key = match eod_keys.get(row.source_id.as_str()) {
|
|
Some(existing) => Arc::clone(existing),
|
|
None => {
|
|
let arc: Arc<str> = Arc::from(row.source_id.as_str());
|
|
eod_keys.insert(Arc::clone(&arc));
|
|
arc
|
|
}
|
|
};
|
|
if track_eod_ranges {
|
|
eod_ranges_by_listing
|
|
.entry(row.listing_id)
|
|
.or_default()
|
|
.push(EodListingRange {
|
|
valid_from: row.valid_from,
|
|
valid_to: row.valid_to,
|
|
key: Arc::clone(&key),
|
|
});
|
|
}
|
|
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
|
}
|
|
}
|
|
for partners in eod_by_listing.values_mut() {
|
|
partners.sort_unstable();
|
|
partners.dedup();
|
|
}
|
|
for ranges in eod_ranges_by_listing.values_mut() {
|
|
ranges.sort_unstable_by(|a, b| {
|
|
a.valid_from
|
|
.cmp(&b.valid_from)
|
|
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
|
|
.then_with(|| a.key.cmp(&b.key))
|
|
});
|
|
}
|
|
|
|
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
|
RunCurateBarsError::ProviderMapping {
|
|
path: provider_mapping_path.to_path_buf(),
|
|
source,
|
|
}
|
|
})?;
|
|
|
|
// Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`.
|
|
let splits_stream = open_splits()?;
|
|
let mut splits_reader = RawBsonChunkReader::new(splits_stream);
|
|
let mut split_rekey = SplitRekeyStats::default();
|
|
let mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
|
|
let splits_decode = decode_qm_split_chunks(
|
|
&mut splits_reader,
|
|
|split| {
|
|
if split.ratio == 1.0 {
|
|
split_rekey.splits_noop_dropped += 1;
|
|
return;
|
|
}
|
|
let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date)
|
|
else {
|
|
split_rekey.splits_unmapped_qm += 1;
|
|
return;
|
|
};
|
|
let has_eod_partner = eod_by_listing
|
|
.get(&listing_id)
|
|
.is_some_and(|partners| !partners.is_empty());
|
|
if !has_eod_partner {
|
|
split_rekey.splits_no_eod_partner += 1;
|
|
return;
|
|
}
|
|
mapped_splits.push(MappedQmSplit {
|
|
listing_id,
|
|
ex_date: split.ex_date,
|
|
qm_key: split.qm_search_code.to_owned(),
|
|
ratio: split.ratio,
|
|
});
|
|
},
|
|
|_offset, _err| {},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::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();
|
|
split_rekey.splits_in = splits_decode.docs_in;
|
|
|
|
// Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys.
|
|
let (compacted_splits, splits_collision_collapsed) =
|
|
compact_mapped_qm_splits(qm_splits_path, mapped_splits)?;
|
|
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
|
|
|
|
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
|
|
for (listing_id, event) in compacted_splits {
|
|
let partners = &eod_by_listing[&listing_id];
|
|
split_rekey.splits_applied += 1;
|
|
for eod_key in partners {
|
|
split_events.push((Arc::clone(eod_key), event));
|
|
}
|
|
split_rekey.split_events_attached += partners.len();
|
|
}
|
|
|
|
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
|
RunCurateBarsError::SplitTable {
|
|
path: qm_splits_path.to_path_buf(),
|
|
source,
|
|
}
|
|
})?;
|
|
|
|
// Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys.
|
|
let eod_stream = open_eod()?;
|
|
let mut eod_reader = RawBsonChunkReader::new(eod_stream);
|
|
let mut bars: Vec<EodDailyBar<Arc<str>>> = Vec::new();
|
|
let mut bars_unmapped_source_dropped: usize = 0;
|
|
let eod_decode = decode_eod_price_chunks(
|
|
&mut eod_reader,
|
|
|raw_bar| {
|
|
if let Some(key) = eod_keys.get(raw_bar.eod_search_code) {
|
|
bars.push(raw_bar.into_eod_daily_bar(|_, _| Arc::clone(key)));
|
|
} else {
|
|
bars_unmapped_source_dropped += 1;
|
|
}
|
|
},
|
|
|_offset, _err| {},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::BsonStream {
|
|
label: "eod-prices",
|
|
path: eod_prices_path.to_path_buf(),
|
|
source,
|
|
})?;
|
|
let eod_docs_framed = eod_reader.docs_framed();
|
|
let eod_bytes_read = eod_reader.bytes_read();
|
|
let buffered_bars = bars.len();
|
|
let interned_key_bytes: usize = eod_keys
|
|
.iter()
|
|
.map(|k| 2 * size_of::<usize>() + k.len())
|
|
.sum();
|
|
let buffered_bar_bytes =
|
|
bars.capacity() * size_of::<EodDailyBar<Arc<str>>>() + interned_key_bytes;
|
|
|
|
// Optionally stream `qmPrices` and date-aware re-key into interned `"eod"` keys.
|
|
let mut qm_volumes: Vec<QmRawVolume<Arc<str>>> = Vec::new();
|
|
let mut qm_prices_present = false;
|
|
let mut qm_prices_docs_framed = 0u64;
|
|
let mut qm_prices_bytes_read = 0u64;
|
|
let mut qm_prices_decode = BsonQmPriceDecodeStats::default();
|
|
let mut qm_rekey = QmVolumeRekeyStats::default();
|
|
let mut qm_decode_rekey_elapsed_secs = 0.0f64;
|
|
|
|
if let Some(qm_prices_path) = qm_prices_path {
|
|
if let Some(qm_stream) = open_qm()? {
|
|
qm_prices_present = true;
|
|
let qm_start = Instant::now();
|
|
let mut qm_reader = RawBsonChunkReader::new(qm_stream);
|
|
qm_prices_decode = decode_qm_price_chunks(
|
|
&mut qm_reader,
|
|
|raw_price| {
|
|
let Some(listing_id) =
|
|
mapping.resolve("qm", raw_price.qm_search_code, raw_price.session_date)
|
|
else {
|
|
qm_rekey.qm_unmapped_qm += 1;
|
|
return;
|
|
};
|
|
let mut matched_eod = 0usize;
|
|
if let Some(ranges) = eod_ranges_by_listing.get(&listing_id) {
|
|
for range in ranges {
|
|
if raw_price.session_date >= range.valid_from
|
|
&& range
|
|
.valid_to
|
|
.is_none_or(|to| raw_price.session_date <= to)
|
|
{
|
|
qm_volumes.push(QmRawVolume {
|
|
key: Arc::clone(&range.key),
|
|
session_date: raw_price.session_date,
|
|
share_volume: raw_price.share_volume,
|
|
});
|
|
matched_eod += 1;
|
|
}
|
|
}
|
|
}
|
|
if matched_eod == 0 {
|
|
qm_rekey.qm_no_eod_partner += 1;
|
|
} else {
|
|
qm_rekey.qm_attached += 1;
|
|
qm_rekey.qm_volumes_attached += matched_eod;
|
|
}
|
|
},
|
|
|_offset, _err| {},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::BsonStream {
|
|
label: "qm-prices",
|
|
path: qm_prices_path.to_path_buf(),
|
|
source,
|
|
})?;
|
|
qm_prices_docs_framed = qm_reader.docs_framed();
|
|
qm_prices_bytes_read = qm_reader.bytes_read();
|
|
qm_rekey.qm_in = qm_prices_decode.docs_in;
|
|
qm_decode_rekey_elapsed_secs = qm_start.elapsed().as_secs_f64();
|
|
}
|
|
}
|
|
let buffered_qm_bytes = qm_volumes.capacity() * size_of::<QmRawVolume<Arc<str>>>();
|
|
|
|
Ok(LoadedCurateBarsInputs {
|
|
mapping,
|
|
currencies,
|
|
splits,
|
|
bars,
|
|
qm_volumes,
|
|
eod_docs_framed,
|
|
eod_bytes_read,
|
|
eod_decode,
|
|
splits_docs_framed,
|
|
splits_bytes_read,
|
|
splits_decode,
|
|
split_rekey,
|
|
qm_prices_present,
|
|
qm_prices_docs_framed,
|
|
qm_prices_bytes_read,
|
|
qm_prices_decode,
|
|
qm_rekey,
|
|
buffered_qm_bytes,
|
|
qm_decode_rekey_elapsed_secs,
|
|
bars_unmapped_source_dropped,
|
|
buffered_bars,
|
|
buffered_bar_bytes,
|
|
})
|
|
}
|
|
|
|
/// Runs the end-to-end `curate-bars-1d` file-to-Parquet pipeline via [`curate_and_write_bars_1d`].
|
|
pub fn run_curate_bars_1d(
|
|
args: &CurateBars1dArgs,
|
|
) -> Result<CurateBars1dRunReport, RunCurateBarsError> {
|
|
if args.threads == 0 {
|
|
return Err(RunCurateBarsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads),
|
|
});
|
|
}
|
|
let start = Instant::now();
|
|
let loaded = load_and_decode_inputs(args)?;
|
|
finish_curate_bars_1d(loaded, &args.out_dir, args.rel_tolerance, args.threads, start)
|
|
}
|
|
|
|
/// Runs `curate-bars-1d` from arbitrary raw-BSON [`io::Read`] streams (such as
|
|
/// [`crate::RawBsonCursorReader`] backed by read-only MongoDB cursors).
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn run_curate_bars_1d_with_readers<RS: io::Read, RE: io::Read, RQ: io::Read>(
|
|
provider_mapping_path: &Path,
|
|
listing_currencies_path: &Path,
|
|
qm_splits_input: (&Path, RS),
|
|
eod_prices_input: (&Path, RE),
|
|
qm_prices_input: Option<(PathBuf, RQ)>,
|
|
out_dir: &Path,
|
|
rel_tolerance: f64,
|
|
threads: usize,
|
|
) -> Result<CurateBars1dRunReport, RunCurateBarsError> {
|
|
if threads == 0 {
|
|
return Err(RunCurateBarsError::CurateWrite {
|
|
out_dir: out_dir.to_path_buf(),
|
|
source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads),
|
|
});
|
|
}
|
|
let start = Instant::now();
|
|
validate_out_dir(out_dir)?;
|
|
let (qm_splits_path, splits_stream) = qm_splits_input;
|
|
let (eod_prices_path, eod_stream) = eod_prices_input;
|
|
let (qm_prices_path, qm_stream) = match qm_prices_input {
|
|
Some((p, r)) => (Some(p), Some(r)),
|
|
None => (None, None),
|
|
};
|
|
let loaded = load_and_decode_from_openers(
|
|
provider_mapping_path,
|
|
listing_currencies_path,
|
|
qm_splits_path,
|
|
|| Ok(splits_stream),
|
|
eod_prices_path,
|
|
|| Ok(eod_stream),
|
|
qm_prices_path.as_deref(),
|
|
|| Ok(qm_stream),
|
|
)?;
|
|
finish_curate_bars_1d(loaded, out_dir, rel_tolerance, threads, start)
|
|
}
|
|
|
|
fn finish_curate_bars_1d(
|
|
loaded: LoadedCurateBarsInputs,
|
|
out_dir: &Path,
|
|
rel_tolerance: f64,
|
|
threads: usize,
|
|
start: Instant,
|
|
) -> Result<CurateBars1dRunReport, RunCurateBarsError> {
|
|
let write_report = curate_and_write_bars_1d(
|
|
out_dir,
|
|
loaded.bars,
|
|
&loaded.splits,
|
|
loaded.qm_volumes,
|
|
rel_tolerance,
|
|
&loaded.mapping,
|
|
"eod",
|
|
&loaded.currencies,
|
|
Bars1dWriteOptions {
|
|
threads,
|
|
..Bars1dWriteOptions::default()
|
|
},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::CurateWrite {
|
|
out_dir: out_dir.to_path_buf(),
|
|
source,
|
|
})?;
|
|
|
|
Ok(CurateBars1dRunReport {
|
|
eod_docs_framed: loaded.eod_docs_framed,
|
|
eod_bytes_read: loaded.eod_bytes_read,
|
|
eod_decode: loaded.eod_decode,
|
|
splits_docs_framed: loaded.splits_docs_framed,
|
|
splits_bytes_read: loaded.splits_bytes_read,
|
|
splits_decode: loaded.splits_decode,
|
|
split_rekey: loaded.split_rekey,
|
|
qm_prices_present: loaded.qm_prices_present,
|
|
qm_prices_docs_framed: loaded.qm_prices_docs_framed,
|
|
qm_prices_bytes_read: loaded.qm_prices_bytes_read,
|
|
qm_prices_decode: loaded.qm_prices_decode,
|
|
qm_rekey: loaded.qm_rekey,
|
|
buffered_qm_bytes: loaded.buffered_qm_bytes,
|
|
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
|
buffered_bars: loaded.buffered_bars,
|
|
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
|
curate_stats: write_report.curate_stats,
|
|
write_stats: write_report.write_stats,
|
|
mismatch_samples: write_report.mismatch_samples,
|
|
threads,
|
|
elapsed_secs: start.elapsed().as_secs_f64(),
|
|
})
|
|
}
|
|
|
|
/// Stage-timed variant of [`run_curate_bars_1d`] sharing [`load_and_decode_inputs`] and calling
|
|
/// [`curate_bars_1d`] + [`write_bars_1d_dataset`] separately.
|
|
#[allow(dead_code)]
|
|
pub(crate) fn run_curate_bars_1d_timed(
|
|
args: &CurateBars1dArgs,
|
|
) -> Result<CurateBars1dTimedRun, RunCurateBarsError> {
|
|
if args.threads == 0 {
|
|
return Err(RunCurateBarsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads),
|
|
});
|
|
}
|
|
let total_start = Instant::now();
|
|
|
|
let decode_start = Instant::now();
|
|
let loaded = load_and_decode_inputs(args)?;
|
|
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
|
|
|
|
let curate_start = Instant::now();
|
|
let curated = curate_bars_1d(
|
|
loaded.bars,
|
|
&loaded.splits,
|
|
loaded.qm_volumes,
|
|
args.rel_tolerance,
|
|
&loaded.mapping,
|
|
"eod",
|
|
&loaded.currencies,
|
|
)
|
|
.map_err(|source| RunCurateBarsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateBarsWriteError::Curate(source),
|
|
})?;
|
|
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
|
|
|
let write_start = Instant::now();
|
|
let write_stats = write_bars_1d_dataset(
|
|
&args.out_dir,
|
|
curated.rows,
|
|
Bars1dWriteOptions {
|
|
threads: args.threads,
|
|
..Bars1dWriteOptions::default()
|
|
},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::CurateWrite {
|
|
out_dir: args.out_dir.clone(),
|
|
source: CurateBarsWriteError::Parquet(source),
|
|
})?;
|
|
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
|
|
|
|
let report = CurateBars1dRunReport {
|
|
eod_docs_framed: loaded.eod_docs_framed,
|
|
eod_bytes_read: loaded.eod_bytes_read,
|
|
eod_decode: loaded.eod_decode,
|
|
splits_docs_framed: loaded.splits_docs_framed,
|
|
splits_bytes_read: loaded.splits_bytes_read,
|
|
splits_decode: loaded.splits_decode,
|
|
split_rekey: loaded.split_rekey,
|
|
qm_prices_present: loaded.qm_prices_present,
|
|
qm_prices_docs_framed: loaded.qm_prices_docs_framed,
|
|
qm_prices_bytes_read: loaded.qm_prices_bytes_read,
|
|
qm_prices_decode: loaded.qm_prices_decode,
|
|
qm_rekey: loaded.qm_rekey,
|
|
buffered_qm_bytes: loaded.buffered_qm_bytes,
|
|
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
|
buffered_bars: loaded.buffered_bars,
|
|
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
|
curate_stats: curated.stats,
|
|
write_stats,
|
|
mismatch_samples: curated.mismatch_samples,
|
|
threads: args.threads,
|
|
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
|
};
|
|
|
|
Ok(CurateBars1dTimedRun {
|
|
report,
|
|
decode_elapsed_secs,
|
|
qm_decode_rekey_elapsed_secs: loaded.qm_decode_rekey_elapsed_secs,
|
|
curate_elapsed_secs,
|
|
write_elapsed_secs,
|
|
})
|
|
}
|
|
|
|
/// Stage-timed variant for `bench-curate-bars-cmd`: decodes and curates once, then times
|
|
/// `write_bars_1d_dataset` on the exact same curated rows at `threads = 1` (into `seq_out_dir`)
|
|
/// and `threads = par_threads` (into `par_out_dir`).
|
|
pub(crate) fn run_curate_bars_1d_timed_compare(
|
|
args: &CurateBars1dArgs,
|
|
seq_out_dir: &Path,
|
|
par_out_dir: &Path,
|
|
par_threads: usize,
|
|
) -> Result<CurateBars1dTimedCompareRun, RunCurateBarsError> {
|
|
if par_threads == 0 {
|
|
return Err(RunCurateBarsError::CurateWrite {
|
|
out_dir: par_out_dir.to_path_buf(),
|
|
source: CurateBarsWriteError::Parquet(ParquetBarsError::InvalidThreads),
|
|
});
|
|
}
|
|
validate_out_dir(seq_out_dir)?;
|
|
validate_out_dir(par_out_dir)?;
|
|
let total_start = Instant::now();
|
|
|
|
let decode_start = Instant::now();
|
|
let loaded = load_and_decode_inputs(args)?;
|
|
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
|
|
|
|
let curate_start = Instant::now();
|
|
let curated = curate_bars_1d(
|
|
loaded.bars,
|
|
&loaded.splits,
|
|
loaded.qm_volumes,
|
|
args.rel_tolerance,
|
|
&loaded.mapping,
|
|
"eod",
|
|
&loaded.currencies,
|
|
)
|
|
.map_err(|source| RunCurateBarsError::CurateWrite {
|
|
out_dir: par_out_dir.to_path_buf(),
|
|
source: CurateBarsWriteError::Curate(source),
|
|
})?;
|
|
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
|
|
|
let write_seq_start = Instant::now();
|
|
let write_stats_seq = write_bars_1d_dataset(
|
|
seq_out_dir,
|
|
&curated.rows,
|
|
Bars1dWriteOptions {
|
|
threads: 1,
|
|
..Bars1dWriteOptions::default()
|
|
},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::CurateWrite {
|
|
out_dir: seq_out_dir.to_path_buf(),
|
|
source: CurateBarsWriteError::Parquet(source),
|
|
})?;
|
|
let write_seq_elapsed_secs = write_seq_start.elapsed().as_secs_f64();
|
|
|
|
let write_par_start = Instant::now();
|
|
let write_stats_par = write_bars_1d_dataset(
|
|
par_out_dir,
|
|
&curated.rows,
|
|
Bars1dWriteOptions {
|
|
threads: par_threads,
|
|
..Bars1dWriteOptions::default()
|
|
},
|
|
)
|
|
.map_err(|source| RunCurateBarsError::CurateWrite {
|
|
out_dir: par_out_dir.to_path_buf(),
|
|
source: CurateBarsWriteError::Parquet(source),
|
|
})?;
|
|
let write_par_elapsed_secs = write_par_start.elapsed().as_secs_f64();
|
|
|
|
assert_eq!(
|
|
write_stats_seq, write_stats_par,
|
|
"sequential and parallel write_bars_1d_dataset stats must match identically"
|
|
);
|
|
|
|
let report = CurateBars1dRunReport {
|
|
eod_docs_framed: loaded.eod_docs_framed,
|
|
eod_bytes_read: loaded.eod_bytes_read,
|
|
eod_decode: loaded.eod_decode,
|
|
splits_docs_framed: loaded.splits_docs_framed,
|
|
splits_bytes_read: loaded.splits_bytes_read,
|
|
splits_decode: loaded.splits_decode,
|
|
split_rekey: loaded.split_rekey,
|
|
qm_prices_present: loaded.qm_prices_present,
|
|
qm_prices_docs_framed: loaded.qm_prices_docs_framed,
|
|
qm_prices_bytes_read: loaded.qm_prices_bytes_read,
|
|
qm_prices_decode: loaded.qm_prices_decode,
|
|
qm_rekey: loaded.qm_rekey,
|
|
buffered_qm_bytes: loaded.buffered_qm_bytes,
|
|
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
|
buffered_bars: loaded.buffered_bars,
|
|
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
|
curate_stats: curated.stats,
|
|
write_stats: write_stats_par,
|
|
mismatch_samples: curated.mismatch_samples,
|
|
threads: par_threads,
|
|
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
|
};
|
|
|
|
Ok(CurateBars1dTimedCompareRun {
|
|
report,
|
|
decode_elapsed_secs,
|
|
qm_decode_rekey_elapsed_secs: loaded.qm_decode_rekey_elapsed_secs,
|
|
curate_elapsed_secs,
|
|
write_seq_elapsed_secs,
|
|
write_par_elapsed_secs,
|
|
write_stats_seq,
|
|
})
|
|
}
|
|
|
|
/// Formats [`CurateBars1dRunReport`] into a deterministic machine-readable `key=value` summary.
|
|
///
|
|
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
|
pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
|
use std::fmt::Write as _;
|
|
|
|
let years = if report.write_stats.rows_by_year.is_empty() {
|
|
"none".to_string()
|
|
} else {
|
|
report
|
|
.write_stats
|
|
.rows_by_year
|
|
.iter()
|
|
.map(|(year, count)| format!("{year:04}={count}"))
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
};
|
|
|
|
let mut out = format!(
|
|
"curate-etl curate-bars-1d\n\
|
|
\x20 eod_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\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 splits: splits_in={} splits_applied={} splits_collision_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\
|
|
\x20 filter: bars_unmapped_source_dropped={} buffered_bars={} buffered_bar_bytes={}\n\
|
|
\x20 builder: bars_in={} rows_out={} keys_out={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} dup_collapsed={} dup_conflict_dropped={}\n\
|
|
\x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} dropped_missing_currency={} dropped_ts_out_of_range={} listing_collision_collapsed={} listing_collision_dropped={}\n\
|
|
\x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\
|
|
\x20 years: {years}\n",
|
|
report.eod_docs_framed,
|
|
report.eod_bytes_read,
|
|
report.eod_decode.docs_in,
|
|
report.eod_decode.decoded,
|
|
report.eod_decode.rejected_total(),
|
|
report.eod_decode.rejected_missing_field,
|
|
report.eod_decode.rejected_empty_field,
|
|
report.eod_decode.rejected_wrong_type,
|
|
report.eod_decode.rejected_malformed_date,
|
|
report.eod_decode.rejected_invalid_number,
|
|
report.eod_decode.rejected_corrupt_document,
|
|
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.split_rekey.splits_in,
|
|
report.split_rekey.splits_applied,
|
|
report.split_rekey.splits_collision_collapsed,
|
|
report.split_rekey.splits_unmapped_qm,
|
|
report.split_rekey.splits_no_eod_partner,
|
|
report.split_rekey.splits_noop_dropped,
|
|
report.split_rekey.split_events_attached,
|
|
report.bars_unmapped_source_dropped,
|
|
report.buffered_bars,
|
|
report.buffered_bar_bytes,
|
|
report.curate_stats.builder.bars_in,
|
|
report.curate_stats.builder.rows_out,
|
|
report.curate_stats.builder.keys_out,
|
|
report.curate_stats.builder.dropped_invalid_ohlc,
|
|
report.curate_stats.builder.dropped_inconsistent_ohlc,
|
|
report.curate_stats.builder.dropped_invalid_volume,
|
|
report.curate_stats.builder.duplicate_collapsed,
|
|
report.curate_stats.builder.duplicate_conflict_dropped,
|
|
report.curate_stats.rows_in,
|
|
report.curate_stats.rows_out,
|
|
report.curate_stats.listings_out,
|
|
report.curate_stats.dropped_unmapped,
|
|
report.curate_stats.dropped_missing_currency,
|
|
report.curate_stats.dropped_ts_out_of_range,
|
|
report.curate_stats.listing_collision_collapsed,
|
|
report.curate_stats.listing_collision_dropped,
|
|
report.write_stats.rows_written,
|
|
report.write_stats.files_written,
|
|
report.write_stats.row_groups_written,
|
|
report.write_stats.bytes_written,
|
|
);
|
|
|
|
if report.qm_prices_present {
|
|
let b = &report.curate_stats.builder;
|
|
let _ = writeln!(
|
|
out,
|
|
" qm_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} corrupt={})",
|
|
report.qm_prices_docs_framed,
|
|
report.qm_prices_bytes_read,
|
|
report.qm_prices_decode.docs_in,
|
|
report.qm_prices_decode.decoded,
|
|
report.qm_prices_decode.rejected_total(),
|
|
report.qm_prices_decode.rejected_missing_field,
|
|
report.qm_prices_decode.rejected_empty_field,
|
|
report.qm_prices_decode.rejected_wrong_type,
|
|
report.qm_prices_decode.rejected_malformed_date,
|
|
report.qm_prices_decode.rejected_corrupt_document,
|
|
);
|
|
let _ = writeln!(
|
|
out,
|
|
" qm_rekey: qm_in={} qm_attached={} qm_unmapped_qm={} qm_no_eod_partner={} qm_volumes_attached={} buffered_qm_bytes={}",
|
|
report.qm_rekey.qm_in,
|
|
report.qm_rekey.qm_attached,
|
|
report.qm_rekey.qm_unmapped_qm,
|
|
report.qm_rekey.qm_no_eod_partner,
|
|
report.qm_rekey.qm_volumes_attached,
|
|
report.buffered_qm_bytes,
|
|
);
|
|
let _ = writeln!(
|
|
out,
|
|
" qm_check: qm_rows_in={} qm_unique_partners={} qm_invalid_vol={} qm_dup_collapsed={} qm_dup_conflict={} volume_checked={} volume_within_tolerance={} volume_mismatched={} volume_unchecked={} max_rel_diff={:.6} mismatch_samples={}",
|
|
b.qm_rows_in,
|
|
b.qm_unique_partners,
|
|
b.qm_invalid_volume_dropped,
|
|
b.qm_duplicate_collapsed,
|
|
b.qm_duplicate_conflict_dropped,
|
|
b.volume_checked,
|
|
b.volume_within_tolerance,
|
|
b.volume_mismatched,
|
|
b.volume_unchecked,
|
|
b.max_rel_diff,
|
|
report.mismatch_samples.len(),
|
|
);
|
|
for sample in &report.mismatch_samples {
|
|
let (y, m, d) = epoch_days_to_ymd(sample.session_date);
|
|
let _ = writeln!(
|
|
out,
|
|
" qm_mismatch: key={} session_date={y:04}-{m:02}-{d:02} volume={:.6} share_volume={:.6} rel={:.6}",
|
|
sample.key, sample.volume, sample.share_volume, sample.rel,
|
|
);
|
|
}
|
|
} else {
|
|
out.push_str(" qm_check: qm_prices=absent\n");
|
|
}
|
|
|
|
let _ = writeln!(out, " config: threads={}", report.threads);
|
|
let _ = write!(out, " timing: elapsed_secs={:.6}", report.elapsed_secs);
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "run_curate_bars_tests.rs"]
|
|
mod tests;
|