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

273 lines
10 KiB
Rust

//! Pure, in-memory `events` curation stage joining [`crate::events::build_events`],
//! [`crate::provider_mapping::ProviderMappingTable`], and
//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - Calls the [`crate::events::build_events`] pipeline unchanged on source keys so same-day
//! earnings↔filing linking (`8-K` / `News release`), form classification, timestamp parsing,
//! conservative `16:05 ET` fallback, and per-key deduplication run before `provider_mapping`
//! resolution.
//! - **Exact Eastern local `event_date` mechanism:** Internally uses the crate-private
//! [`crate::events::build_events_with_dates`] helper (zero overhead on public `build_events`,
//! unchanged `EventsParquetRow` schema) to carry each row's already-parsed Eastern local
//! calendar date (`ParsedFilingTime::et_date` for filings; `QmEarning::report_date` for
//! earnings) alongside the row. This guarantees exact Eastern-date `provider_mapping` lookup
//! across all supported years—including pre-2008 historical filings and late-evening EST/EDT
//! filings whose UTC date has already rolled over to the next day—never using UTC date or
//! `known_at` date.
//! - Resolves each row's `(mapping_source, key, event_date)` to a permanent `listing_id: i32` via
//! [`ProviderMappingTable::cursor_for`] / [`ProviderMappingCursor::resolve`] (opening one cursor
//! per contiguous `key` run, since `build_events_with_dates` emits rows sorted by `key` then
//! `ts_micros`). Rows with no covering mapping range are dropped into `dropped_unmapped`.
//! - Moves `subtype` and `payload_json` without cloning, keeps `known_at_source` and `kind` as
//! `Cow::Borrowed`, and frees builder rows before re-sorting in place by the exact 7-field
//! writer key `(listing_id, ts_micros, kind, subtype, payload_json, known_at_micros,
//! known_at_source)`.
//! - Cross-`key` rows mapping to the same `listing_id` that are equal on all seven fields collapse
//! to one row (`listing_duplicate_collapsed`); rows differing in any single field are all kept
//! (events are not unique per `(listing_id, ts)`).
use std::borrow::Cow;
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::events::{
build_events_with_dates, EventRowWithDate, EventsStats, QmEarning, QmFiling,
EVENT_KIND_EARNINGS, EVENT_KIND_FILING,
};
use crate::parquet_events::{
write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
ParquetEventsError,
};
use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable};
/// Accounting summary produced alongside [`CurateEventsOutput::rows`].
///
/// Conservation invariants:
/// - `rows_in == builder.rows_out`
/// - `rows_in == rows_out + dropped_unmapped + listing_duplicate_collapsed`
/// - `rows_out == filings_out + earnings_out`
/// - `builder` independently satisfies all [`EventsStats`] conservation invariants.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CurateEventsStats {
pub builder: EventsStats,
pub rows_in: usize,
pub rows_out: usize,
pub listings_out: usize,
pub filings_out: usize,
pub earnings_out: usize,
pub dropped_unmapped: usize,
pub listing_duplicate_collapsed: usize,
}
/// Output of [`curate_events`]: contract Parquet rows strictly ascending in the 7-field writer
/// sort key and full stage + builder stats.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateEventsOutput {
pub rows: Vec<EventsParquetRow>,
pub stats: CurateEventsStats,
}
/// Typed caller errors returned by [`curate_events`].
///
/// Bad or unmapped single rows are skipped/dropped and counted in [`CurateEventsStats`] rather
/// than aborting the stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CurateEventsError {
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
EmptyMappingSource,
}
impl fmt::Display for CurateEventsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::EmptyMappingSource => {
write!(f, "mapping_source must not be empty or blank")
}
}
}
}
impl Error for CurateEventsError {}
/// Combined stats returned by [`curate_and_write_events`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateEventsWriteReport {
pub curate_stats: CurateEventsStats,
pub write_stats: EventsWriteStats,
}
/// Typed error returned by [`curate_and_write_events`].
#[derive(Debug)]
pub enum CurateEventsWriteError {
Curate(CurateEventsError),
Parquet(ParquetEventsError),
}
impl fmt::Display for CurateEventsWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "events curation failed: {err}"),
Self::Parquet(err) => write!(f, "events Parquet write failed: {err}"),
}
}
}
impl Error for CurateEventsWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CurateEventsError> for CurateEventsWriteError {
fn from(err: CurateEventsError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetEventsError> for CurateEventsWriteError {
fn from(err: ParquetEventsError) -> Self {
Self::Parquet(err)
}
}
#[inline]
fn compare_event_rows(a: &EventsParquetRow, b: &EventsParquetRow) -> Ordering {
a.listing_id
.cmp(&b.listing_id)
.then_with(|| a.ts_micros.cmp(&b.ts_micros))
.then_with(|| a.kind.as_ref().cmp(b.kind.as_ref()))
.then_with(|| a.subtype.cmp(&b.subtype))
.then_with(|| a.payload_json.cmp(&b.payload_json))
.then_with(|| a.known_at_micros.cmp(&b.known_at_micros))
.then_with(|| a.known_at_source.as_ref().cmp(b.known_at_source.as_ref()))
}
/// Pure `events` curation stage: builds point-in-time `qmFilings` + `qmEarnings` rows on source
/// keys, resolves `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern
/// local calendar date via `provider_mapping`, and emits contract [`EventsParquetRow`]s strictly
/// ascending in the 7-field writer key.
///
/// `event_date` is the filing's `timefiled` Eastern local calendar date for filings and
/// `report_date` for earnings—never the UTC date and never the `known_at` date. Rows with no
/// covering mapping range are dropped into `dropped_unmapped`. Cross-`key` rows that map to the
/// same `listing_id` and match on all seven fields collapse to one row
/// (`listing_duplicate_collapsed`); rows differing in any field are all kept.
pub fn curate_events<K, IF, IE>(
filings: IF,
earnings: IE,
mapping_source: &str,
mapping: &ProviderMappingTable,
) -> Result<CurateEventsOutput, CurateEventsError>
where
K: Ord + Clone + AsRef<str>,
IF: IntoIterator<Item = QmFiling<K>>,
IE: IntoIterator<Item = QmEarning<K>>,
{
if mapping_source.trim().is_empty() {
return Err(CurateEventsError::EmptyMappingSource);
}
let (built_rows, builder_stats) = build_events_with_dates(filings, earnings);
let mut stats = CurateEventsStats {
builder: builder_stats,
rows_in: built_rows.len(),
..CurateEventsStats::default()
};
let mut rows: Vec<EventsParquetRow> = Vec::with_capacity(built_rows.len());
let mut current_key: Option<K> = None;
let mut current_cursor: Option<ProviderMappingCursor<'_>> = None;
for EventRowWithDate { row, event_date } in built_rows {
if current_key.as_ref() != Some(&row.key) {
current_cursor = Some(mapping.cursor_for(mapping_source, row.key.as_ref()));
current_key = Some(row.key);
}
let cursor = current_cursor
.as_mut()
.expect("cursor initialized for current key run");
if cursor.ranges().is_empty() {
stats.dropped_unmapped += 1;
continue;
}
let Some(listing_id) = cursor.resolve(event_date) else {
stats.dropped_unmapped += 1;
continue;
};
rows.push(EventsParquetRow {
listing_id,
ts_micros: row.ts_micros,
known_at_micros: row.known_at_micros,
known_at_source: Cow::Borrowed(row.known_at_source),
kind: Cow::Borrowed(row.kind),
subtype: row.subtype,
payload_json: row.payload_json,
});
}
// `built_rows` has been consumed by value; drop key state before re-sorting.
drop(current_key);
rows.sort_unstable_by(compare_event_rows);
let mapped_len = rows.len();
rows.dedup();
stats.listing_duplicate_collapsed = mapped_len - rows.len();
let mut last_listing_id: Option<i32> = None;
for row in &rows {
if last_listing_id != Some(row.listing_id) {
stats.listings_out += 1;
last_listing_id = Some(row.listing_id);
}
match row.kind.as_ref() {
EVENT_KIND_FILING => stats.filings_out += 1,
EVENT_KIND_EARNINGS => stats.earnings_out += 1,
other => unreachable!("unexpected event kind from build_events: {other:?}"),
}
}
stats.rows_out = rows.len();
Ok(CurateEventsOutput { rows, stats })
}
/// Thin end-to-end wrapper running [`curate_events`] and publishing the resulting contract rows
/// via [`write_events_dataset`] to `<out_dir>/events/year=YYYY/part.parquet`.
///
/// Any [`CurateEventsError`] returns before [`write_events_dataset`] is invoked, leaving
/// `out_dir` untouched.
pub fn curate_and_write_events<P, K, IF, IE>(
out_dir: P,
filings: IF,
earnings: IE,
mapping_source: &str,
mapping: &ProviderMappingTable,
options: EventsWriteOptions,
) -> Result<CurateEventsWriteReport, CurateEventsWriteError>
where
P: AsRef<Path>,
K: Ord + Clone + AsRef<str>,
IF: IntoIterator<Item = QmFiling<K>>,
IE: IntoIterator<Item = QmEarning<K>>,
{
let curated = curate_events(filings, earnings, mapping_source, mapping)?;
let write_stats = write_events_dataset(out_dir, &curated.rows, options)?;
Ok(CurateEventsWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_events_tests.rs"]
mod tests;