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

315 lines
11 KiB
Rust

//! Pure, in-memory `shorts` curation stage joining [`crate::shorts::build_shorts`],
//! [`crate::provider_mapping::ProviderMappingTable`], and
//! [`crate::parquet_shorts::write_shorts_dataset`] into contract [`ShortsParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - Calls [`build_shorts`] unchanged to validate `shares_short`, sanitize non-finite optional
//! fields, deduplicate same-`(key, report_date)` reports, apply the locked `+4` Canadian TSX
//! business-day CIRO lag, and stamp `known_at_utc_micros = 17:00:00 America/Toronto` plus
//! `source = SHORTS_SOURCE_CEO` (`"ceo_shorts"`).
//! - Resolves each output row's `(mapping_source, key, report_date)` to a permanent
//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`]
//! (one cursor per contiguous `key` run, since `build_shorts` emits rows sorted by
//! `(key, report_date)`).
//! - **Point-in-time mapping boundary (`report_date`, not `known_at_date`):** `provider_mapping`
//! is resolved strictly on `report_date` (the reporting period the short position describes),
//! not on `known_at_date` (when CIRO disseminates the report `+4` business days later). A ticker
//! that changes listing or delists between `report_date` and `known_at_date` still belongs to
//! the listing that was active on `report_date`.
//! - Carries `source` through unchanged from `build_shorts` (`SHORTS_SOURCE_CEO` = `"ceo_shorts"`)
//! as `Cow::Borrowed`.
//! - Re-sorts mapped rows in place by `(listing_id, report_date)` and compacts cross-`key`
//! collisions on the same `(listing_id, report_date)`: bitwise-identical
//! `(known_at_micros, shares_short, net_change, pct_float)` collapses to one row
//! (`listing_collision_collapsed`), while any conflict drops the entire group
//! (`listing_collision_dropped`), mirroring `build_shorts`'s duplicate policy.
use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::parquet_shorts::{
write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions,
ShortsWriteStats,
};
use crate::provider_mapping::ProviderMappingTable;
use crate::shorts::{build_shorts, CeoShortReport, ShortsError, ShortsStats};
/// Accounting summary produced alongside [`CurateShortsOutput::rows`].
///
/// Conservation invariants:
/// - `rows_in == builder.rows_out`
/// - `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped`
/// - `builder` independently satisfies all [`ShortsStats`] conservation invariants.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CurateShortsStats {
pub builder: ShortsStats,
pub rows_in: usize,
pub rows_out: usize,
pub listings_out: usize,
pub dropped_unmapped: usize,
pub listing_collision_collapsed: usize,
pub listing_collision_dropped: usize,
}
/// Output of [`curate_shorts`]: contract Parquet rows sorted and unique by
/// `(listing_id, report_date)` and full stage + builder stats.
#[derive(Debug, Clone, PartialEq)]
pub struct CurateShortsOutput {
pub rows: Vec<ShortsParquetRow>,
pub stats: CurateShortsStats,
}
/// Typed caller errors returned by [`curate_shorts`].
///
/// Bad single rows (unmapped dates and cross-`key` collisions) are dropped and counted in
/// [`CurateShortsStats`] rather than aborting the stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CurateShortsError {
/// Error propagated from [`build_shorts`] (e.g., `report_date` outside `2008..=2030`).
Shorts(ShortsError),
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
EmptyMappingSource,
}
impl fmt::Display for CurateShortsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Shorts(err) => write!(f, "{err}"),
Self::EmptyMappingSource => {
write!(f, "mapping_source must not be empty or blank")
}
}
}
}
impl Error for CurateShortsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Shorts(err) => Some(err),
Self::EmptyMappingSource => None,
}
}
}
impl From<ShortsError> for CurateShortsError {
fn from(err: ShortsError) -> Self {
Self::Shorts(err)
}
}
/// Combined stats returned by [`curate_and_write_shorts`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurateShortsWriteReport {
pub curate_stats: CurateShortsStats,
pub write_stats: ShortsWriteStats,
}
/// Typed error returned by [`curate_and_write_shorts`].
#[derive(Debug)]
pub enum CurateShortsWriteError {
Curate(CurateShortsError),
Parquet(ParquetShortsError),
}
impl fmt::Display for CurateShortsWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "shorts curation failed: {err}"),
Self::Parquet(err) => write!(f, "shorts Parquet write failed: {err}"),
}
}
}
impl Error for CurateShortsWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateShortsError> for CurateShortsWriteError {
fn from(err: CurateShortsError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetShortsError> for CurateShortsWriteError {
fn from(err: ParquetShortsError) -> Self {
Self::Parquet(err)
}
}
#[inline]
fn parquet_row_values_bit_eq(a: &ShortsParquetRow, b: &ShortsParquetRow) -> bool {
a.known_at_micros == b.known_at_micros
&& a.shares_short.to_bits() == b.shares_short.to_bits()
&& a.net_change.map(f64::to_bits) == b.net_change.map(f64::to_bits)
&& a.pct_float.map(f64::to_bits) == b.pct_float.map(f64::to_bits)
}
/// Pure `shorts` curation stage: validates, deduplicates, and point-in-time lags source-keyed
/// `ceoShorts` reports via [`build_shorts`], resolves `(mapping_source, key, report_date) ->
/// listing_id` through `provider_mapping`, and emits contract [`ShortsParquetRow`]s sorted and
/// unique by `(listing_id, report_date)`.
///
/// Mapping lookup uses `report_date` (the reporting period the short position describes), not
/// `known_at_date`. Rows with no covering mapping range are dropped into `dropped_unmapped`.
///
/// After re-sorting in place by `(listing_id, report_date)`, cross-`key` collisions on the same
/// `(listing_id, report_date)` collapse to one row when `known_at_micros`, `shares_short`,
/// `net_change`, and `pct_float` are bitwise identical (`listing_collision_collapsed += g - 1`)
/// and drop the entire group when any of those fields differ (`listing_collision_dropped += g`).
pub fn curate_shorts<K, I>(
reports: I,
mapping_source: &str,
mapping: &ProviderMappingTable,
) -> Result<CurateShortsOutput, CurateShortsError>
where
K: Ord + Clone + AsRef<str>,
I: IntoIterator<Item = CeoShortReport<K>>,
{
if mapping_source.trim().is_empty() {
return Err(CurateShortsError::EmptyMappingSource);
}
let built = build_shorts(reports)?;
let mut stats = CurateShortsStats {
builder: built.stats,
rows_in: built.rows.len(),
..CurateShortsStats::default()
};
let mut rows: Vec<ShortsParquetRow> = Vec::with_capacity(built.rows.len());
let total_built = built.rows.len();
let mut idx = 0usize;
while idx < total_built {
let run_start = idx;
let run_key = &built.rows[run_start].key;
idx += 1;
while idx < total_built && built.rows[idx].key == *run_key {
idx += 1;
}
let run_end = idx;
let mut cursor = mapping.cursor_for(mapping_source, run_key.as_ref());
if cursor.ranges().is_empty() {
stats.dropped_unmapped += run_end - run_start;
continue;
}
for row in &built.rows[run_start..run_end] {
let Some(listing_id) = cursor.resolve(row.report_date) else {
stats.dropped_unmapped += 1;
continue;
};
rows.push(ShortsParquetRow {
listing_id,
report_date: row.report_date,
known_at_micros: row.known_at_utc_micros,
shares_short: row.shares_short,
net_change: row.net_change,
pct_float: row.pct_float,
source: Cow::Borrowed(row.source),
});
}
}
// Free builder rows before sorting/compacting mapped contract rows to cut peak RAM.
drop(built.rows);
rows.sort_unstable_by(|a, b| {
a.listing_id
.cmp(&b.listing_id)
.then_with(|| a.report_date.cmp(&b.report_date))
});
let mut write_idx = 0usize;
let mut read_idx = 0usize;
let total_mapped = rows.len();
let mut last_listing_id: Option<i32> = None;
while read_idx < total_mapped {
let listing_id = rows[read_idx].listing_id;
let report_date = rows[read_idx].report_date;
let mut group_end = read_idx + 1;
while group_end < total_mapped
&& rows[group_end].listing_id == listing_id
&& rows[group_end].report_date == report_date
{
group_end += 1;
}
let group_len = group_end - read_idx;
if group_len == 1 {
if write_idx != read_idx {
rows.swap(write_idx, read_idx);
}
if last_listing_id != Some(listing_id) {
stats.listings_out += 1;
last_listing_id = Some(listing_id);
}
write_idx += 1;
} else {
let first = &rows[read_idx];
let all_identical = rows[read_idx + 1..group_end]
.iter()
.all(|other| parquet_row_values_bit_eq(first, other));
if all_identical {
stats.listing_collision_collapsed += group_len - 1;
if write_idx != read_idx {
rows.swap(write_idx, read_idx);
}
if last_listing_id != Some(listing_id) {
stats.listings_out += 1;
last_listing_id = Some(listing_id);
}
write_idx += 1;
} else {
stats.listing_collision_dropped += group_len;
}
}
read_idx = group_end;
}
rows.truncate(write_idx);
stats.rows_out = rows.len();
Ok(CurateShortsOutput { rows, stats })
}
/// Thin end-to-end wrapper running [`curate_shorts`] and publishing the resulting contract rows
/// via [`write_shorts_dataset`] to `<out_dir>/shorts/part.parquet`.
///
/// Any [`CurateShortsError`] returns before [`write_shorts_dataset`] is invoked, leaving
/// `out_dir` untouched.
pub fn curate_and_write_shorts<P, K, I>(
out_dir: P,
reports: I,
mapping_source: &str,
mapping: &ProviderMappingTable,
options: ShortsWriteOptions,
) -> Result<CurateShortsWriteReport, CurateShortsWriteError>
where
P: AsRef<Path>,
K: Ord + Clone + AsRef<str>,
I: IntoIterator<Item = CeoShortReport<K>>,
{
let curated = curate_shorts(reports, mapping_source, mapping)?;
let write_stats = write_shorts_dataset(out_dir, &curated.rows, options)?;
Ok(CurateShortsWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_shorts_tests.rs"]
mod tests;