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

589 lines
21 KiB
Rust

//! File-to-file `curate-shorts` command runner (`M1.2ad`).
//!
//! Streams a concatenated raw BSON `ceoShorts` dump file alongside `provider_mapping.tsv` into an
//! atomically published `<out_dir>/shorts/part.parquet` dataset via [`curate_and_write_shorts`].
//!
//! # Contract & Point-in-Time Rules
//! - Field names are supplied explicitly via [`CurateShortsArgs`] (validated via
//! [`CeoShortsFieldNames::validate`] before touching disk) because live MongoDB `ceoShorts`
//! value field names are unverified in the repository.
//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from
//! [`crate::run_curate_bars::load_provider_mapping_tsv`].
//! - All decoded [`CeoShortReport`] rows are passed directly to [`curate_and_write_shorts`] (which
//! resolves `provider_mapping` strictly on `report_date`, not `known_at_date`, stamps
//! `known_at = report_date + 4` Canadian TSX business days at `17:00 America/Toronto`, and
//! counts unmapped keys in [`CurateShortsStats::dropped_unmapped`]).
//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_shorts`] /
//! [`write_shorts_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0`
//! without creating `<out_dir>/shorts` or modifying any pre-existing `part.parquet`.
//! - **Fail-closed safety:** invalid `--out`, invalid field names, empty `--mapping-source`,
//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON
//! framing or element bytes, and out-of-range `report_date` errors return a typed
//! [`RunCurateShortsError`] before touching `args.out_dir`.
//!
//! # Counter Conservation Invariants
//! Every successful [`CurateShortsRunReport`] satisfies:
//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()`
//! - `decode.rows_out == curate_stats.builder.rows_in`
//! - `curate_stats.builder.rows_in == curate_stats.builder.rows_out + curate_stats.builder.dropped_invalid_shares_short + curate_stats.builder.duplicate_collapsed + curate_stats.builder.duplicate_conflict_dropped`
//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped`
//! - `write_stats.rows_written == curate_stats.rows_out`
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use crate::bson_ceo_shorts::{
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
};
use crate::bson_stream::{
decode_ceo_shorts_chunks, BsonCeoShortsStreamError, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader,
};
use crate::curate_shorts::{
curate_and_write_shorts, curate_shorts, CurateShortsStats, CurateShortsWriteError,
};
use crate::parquet_shorts::{
write_shorts_dataset, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats,
};
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
use crate::shorts::CeoShortReport;
/// Default `--mapping-source` passed to `provider_mapping` lookups for `ceoShorts`.
pub const DEFAULT_MAPPING_SOURCE: &str = "ceo";
/// Parsed arguments for the `curate-shorts` CLI command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateShortsArgs {
pub ceo_shorts: PathBuf,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub key_field: String,
pub report_date_field: String,
pub shares_short_field: String,
pub net_change_field: Option<String>,
pub pct_float_field: Option<String>,
pub mapping_source: String,
}
impl CurateShortsArgs {
/// Borrows the configured BSON field names as [`CeoShortsFieldNames`].
#[inline]
pub fn field_names(&self) -> CeoShortsFieldNames<'_> {
CeoShortsFieldNames {
key: self.key_field.as_str(),
report_date: self.report_date_field.as_str(),
shares_short: self.shares_short_field.as_str(),
net_change: self.net_change_field.as_deref(),
pct_float: self.pct_float_field.as_deref(),
}
}
}
/// Full run report produced by [`run_curate_shorts`].
#[derive(Debug, Clone, PartialEq)]
pub struct CurateShortsRunReport {
pub docs_framed: u64,
pub bytes_read: u64,
pub peak_chunk_bytes: usize,
pub decode: BsonCeoShortsDecodeStats,
pub curate_stats: CurateShortsStats,
pub write_stats: ShortsWriteStats,
pub elapsed_secs: f64,
}
/// Stage-timed run output used internally by `bench-curate-shorts-command`.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CurateShortsTimedRun {
pub report: CurateShortsRunReport,
pub decode_elapsed_secs: f64,
pub curate_elapsed_secs: f64,
pub write_elapsed_secs: f64,
pub checksum: u64,
}
/// Typed errors returned by [`run_curate_shorts`].
///
/// Every variant's `Display` output is a single line naming the offending path (and line number or
/// byte offset where applicable).
#[derive(Debug)]
pub enum RunCurateShortsError {
InvalidOutDir {
path: PathBuf,
detail: String,
},
InvalidFieldNames {
source: BsonCeoShortsError,
},
EmptyMappingSource,
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 {
path: PathBuf,
source: BsonStreamError,
},
CorruptBson {
path: PathBuf,
offset: u64,
source: BsonCeoShortsError,
},
CurateWrite {
out_dir: PathBuf,
source: CurateShortsWriteError,
},
}
impl fmt::Display for RunCurateShortsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidOutDir { path, detail } => {
write!(f, "invalid --out '{}': {detail}", path.display())
}
Self::InvalidFieldNames { source } => write!(f, "{source}"),
Self::EmptyMappingSource => {
write!(f, "invalid --mapping-source: must not be empty or blank")
}
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 { path, source } => {
write!(f, "failed reading ceo-shorts '{}': {source}", path.display())
}
Self::CorruptBson {
path,
offset,
source,
} => write!(
f,
"corrupt ceo-shorts BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CurateWrite { out_dir, source } => {
write!(f, "curate/write to '{}' failed: {source}", out_dir.display())
}
}
}
}
impl Error for RunCurateShortsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::InvalidFieldNames { source } => Some(source),
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
Self::ProviderMapping { source, .. } => Some(source),
Self::BsonStream { source, .. } => Some(source),
Self::CorruptBson { source, .. } => Some(source),
Self::CurateWrite { source, .. } => Some(source),
Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None,
}
}
}
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateShortsError> {
if out_dir.exists() && !out_dir.is_dir() {
return Err(RunCurateShortsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
Ok(())
}
fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateShortsError {
match err {
RunCurateBarsError::OpenInput {
label,
path,
source,
} => RunCurateShortsError::OpenInput {
label,
path,
source,
},
RunCurateBarsError::ReadInput {
label,
path,
source,
} => RunCurateShortsError::ReadInput {
label,
path,
source,
},
RunCurateBarsError::TsvParse { path, line, detail } => {
RunCurateShortsError::TsvParse { path, line, detail }
}
RunCurateBarsError::ProviderMapping { path, source } => {
RunCurateShortsError::ProviderMapping { path, source }
}
other => RunCurateShortsError::TsvParse {
path: path.to_path_buf(),
line: 0,
detail: other.to_string(),
},
}
}
fn bson_error_offset(err: &BsonCeoShortsError) -> u64 {
match err {
BsonCeoShortsError::TruncatedDocument { offset, .. }
| BsonCeoShortsError::CorruptDocumentLength { offset, .. }
| BsonCeoShortsError::CorruptBson { offset, .. } => *offset,
BsonCeoShortsError::InvalidFieldNames { .. } => 0,
}
}
struct DecodedShortsInputs {
mapping: ProviderMappingTable,
reports: Vec<CeoShortReport<Arc<str>>>,
docs_framed: u64,
bytes_read: u64,
peak_chunk_bytes: usize,
decode: BsonCeoShortsDecodeStats,
}
fn decode_all_inputs(args: &CurateShortsArgs) -> Result<DecodedShortsInputs, RunCurateShortsError> {
decode_inputs_from_opener(
&args.provider_mapping,
&args.mapping_source,
&args.field_names(),
&args.ceo_shorts,
|| {
File::open(&args.ceo_shorts).map_err(|source| RunCurateShortsError::OpenInput {
label: "ceo-shorts",
path: args.ceo_shorts.clone(),
source,
})
},
)
}
fn decode_inputs_from_opener<R, F>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoShortsFieldNames<'_>,
ceo_shorts_path: &Path,
open_shorts: F,
) -> Result<DecodedShortsInputs, RunCurateShortsError>
where
R: io::Read,
F: FnOnce() -> Result<R, RunCurateShortsError>,
{
fields
.validate()
.map_err(|source| RunCurateShortsError::InvalidFieldNames { source })?;
if mapping_source.trim().is_empty() {
return Err(RunCurateShortsError::EmptyMappingSource);
}
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)
.map_err(|err| map_tsv_error(provider_mapping_path, err))?;
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
RunCurateShortsError::ProviderMapping {
path: provider_mapping_path.to_path_buf(),
source,
}
})?;
let stream = open_shorts()?;
let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default())
.map_err(|source| RunCurateShortsError::BsonStream {
path: ceo_shorts_path.to_path_buf(),
source,
})?;
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
let mut reports: Vec<CeoShortReport<Arc<str>>> = Vec::new();
let decode = decode_ceo_shorts_chunks(&mut reader, fields, |raw| {
let key = if let Some(existing) = key_interner.get(raw.key) {
Arc::clone(existing)
} else {
let arc: Arc<str> = Arc::from(raw.key);
key_interner.insert(Arc::clone(&arc));
arc
};
reports.push(CeoShortReport {
key,
report_date: raw.report_date,
shares_short: raw.shares_short,
net_change: raw.net_change,
pct_float: raw.pct_float,
});
})
.map_err(|err| match err {
BsonCeoShortsStreamError::Stream(source) => RunCurateShortsError::BsonStream {
path: ceo_shorts_path.to_path_buf(),
source,
},
BsonCeoShortsStreamError::Decode(source) => match &source {
BsonCeoShortsError::InvalidFieldNames { .. } => {
RunCurateShortsError::InvalidFieldNames { source }
}
_ => {
let offset = bson_error_offset(&source);
RunCurateShortsError::CorruptBson {
path: ceo_shorts_path.to_path_buf(),
offset,
source,
}
}
},
})?;
Ok(DecodedShortsInputs {
mapping,
reports,
docs_framed: reader.docs_framed(),
bytes_read: reader.bytes_read(),
peak_chunk_bytes: reader.buffer_capacity(),
decode,
})
}
/// Runs the end-to-end `curate-shorts` file-to-Parquet pipeline via [`curate_and_write_shorts`].
///
/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before
/// touching `args.out_dir`, leaving any pre-existing `<out_dir>/shorts/part.parquet`
/// byte-identical.
pub fn run_curate_shorts(
args: &CurateShortsArgs,
) -> Result<CurateShortsRunReport, RunCurateShortsError> {
let start = Instant::now();
validate_out_dir(&args.out_dir)?;
let decoded = decode_all_inputs(args)?;
finish_curate_shorts(decoded, &args.mapping_source, &args.out_dir, start)
}
/// Runs `curate-shorts` from an arbitrary raw-BSON [`io::Read`] stream.
pub fn run_curate_shorts_with_reader<R: io::Read>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoShortsFieldNames<'_>,
ceo_shorts_input: (&Path, R),
out_dir: &Path,
) -> Result<CurateShortsRunReport, RunCurateShortsError> {
let start = Instant::now();
validate_out_dir(out_dir)?;
let (ceo_path, stream) = ceo_shorts_input;
let decoded = decode_inputs_from_opener(
provider_mapping_path,
mapping_source,
fields,
ceo_path,
|| Ok(stream),
)?;
finish_curate_shorts(decoded, mapping_source, out_dir, start)
}
fn finish_curate_shorts(
decoded: DecodedShortsInputs,
mapping_source: &str,
out_dir: &Path,
start: Instant,
) -> Result<CurateShortsRunReport, RunCurateShortsError> {
let write_report = curate_and_write_shorts(
out_dir,
decoded.reports,
mapping_source,
&decoded.mapping,
ShortsWriteOptions::default(),
)
.map_err(|source| RunCurateShortsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source,
})?;
Ok(CurateShortsRunReport {
docs_framed: decoded.docs_framed,
bytes_read: decoded.bytes_read,
peak_chunk_bytes: decoded.peak_chunk_bytes,
decode: decoded.decode,
curate_stats: write_report.curate_stats,
write_stats: write_report.write_stats,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}
fn compute_rows_checksum(rows: &[ShortsParquetRow]) -> 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
};
let mix_str = |mut h: u64, s: &str| -> u64 {
h = mix(h, s.len() as u64);
for &b in s.as_bytes() {
h = mix(h, u64::from(b));
}
h
};
for row in rows {
hash = mix(hash, row.listing_id as u64);
hash = mix(hash, row.report_date as u64);
hash = mix(hash, row.known_at_micros as u64);
hash = mix(hash, row.shares_short.to_bits());
hash = match row.net_change {
Some(v) => mix(mix(hash, 1), v.to_bits()),
None => mix(hash, 0),
};
hash = match row.pct_float {
Some(v) => mix(mix(hash, 1), v.to_bits()),
None => mix(hash, 0),
};
hash = mix_str(hash, row.source.as_ref());
}
hash
}
/// Stage-timed variant of [`run_curate_shorts`] used internally by `bench-curate-shorts-command`.
///
/// Separately times `decode` (TSV load + BSON stream), `curate` (`curate_shorts`), and `write`
/// (`write_shorts_dataset`), and computes a deterministic FNV-1a checksum over all 7 columns of the
/// curated rows.
pub(crate) fn run_curate_shorts_timed(
args: &CurateShortsArgs,
) -> Result<CurateShortsTimedRun, RunCurateShortsError> {
let total_start = Instant::now();
validate_out_dir(&args.out_dir)?;
let decode_start = Instant::now();
let decoded = decode_all_inputs(args)?;
let decode_elapsed_secs = decode_start.elapsed().as_secs_f64();
let curate_start = Instant::now();
let curated = curate_shorts(decoded.reports, &args.mapping_source, &decoded.mapping).map_err(
|source| RunCurateShortsError::CurateWrite {
out_dir: args.out_dir.clone(),
source: CurateShortsWriteError::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_shorts_dataset(&args.out_dir, &curated.rows, ShortsWriteOptions::default()).map_err(
|source| RunCurateShortsError::CurateWrite {
out_dir: args.out_dir.clone(),
source: CurateShortsWriteError::Parquet(source),
},
)?;
let write_elapsed_secs = write_start.elapsed().as_secs_f64();
let report = CurateShortsRunReport {
docs_framed: decoded.docs_framed,
bytes_read: decoded.bytes_read,
peak_chunk_bytes: decoded.peak_chunk_bytes,
decode: decoded.decode,
curate_stats: curated.stats,
write_stats,
elapsed_secs: total_start.elapsed().as_secs_f64(),
};
Ok(CurateShortsTimedRun {
report,
decode_elapsed_secs,
curate_elapsed_secs,
write_elapsed_secs,
checksum,
})
}
/// Formats [`CurateShortsRunReport`] into a deterministic machine-readable `key=value` summary.
///
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
pub fn format_curate_shorts_report(report: &CurateShortsRunReport) -> String {
let d = &report.decode;
let b = &report.curate_stats.builder;
let c = &report.curate_stats;
let w = &report.write_stats;
format!(
"curate-etl curate-shorts\n\
\x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_date={} wrong_date_type={} invalid_date={} date_oor={} missing_shares={} wrong_shares_type={}) nulled_wrong_type=(net_change={} pct_float={})\n\
\x20 builder: rows_in={} rows_out={} keys_out={} invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict={}\n\
\x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} coll_collapsed={} coll_dropped={}\n\
\x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\
\x20 timing: elapsed_secs={:.6}",
report.docs_framed,
report.bytes_read,
report.peak_chunk_bytes,
d.docs_in,
d.rows_out,
d.skipped_total(),
d.skipped_missing_key,
d.skipped_wrong_key_type,
d.skipped_empty_key,
d.skipped_missing_report_date,
d.skipped_wrong_report_date_type,
d.skipped_invalid_report_date,
d.skipped_report_date_out_of_range,
d.skipped_missing_shares_short,
d.skipped_wrong_shares_short_type,
d.nulled_wrong_type_net_change,
d.nulled_wrong_type_pct_float,
b.rows_in,
b.rows_out,
b.keys_out,
b.dropped_invalid_shares_short,
b.nulled_invalid_net_change,
b.nulled_invalid_pct_float,
b.duplicate_collapsed,
b.duplicate_conflict_dropped,
c.rows_in,
c.rows_out,
c.listings_out,
c.dropped_unmapped,
c.listing_collision_collapsed,
c.listing_collision_dropped,
w.files_written,
w.row_groups_written,
w.rows_written,
w.bytes_written,
report.elapsed_secs,
)
}
#[cfg(test)]
#[path = "run_curate_shorts_tests.rs"]
mod tests;