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

300 lines
11 KiB
Rust

//! Pure, in-memory `posts` curation stage joining [`crate::posts::build_posts`],
//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::parquet_posts`], and
//! [`crate::parquet_events::write_events_dataset`] into contract [`EventsParquetRow`]s.
//!
//! # Contract & Point-in-Time Rules
//! - Calls [`build_posts`] unchanged on source keys so global `spiel_id` deduplication,
//! `bot == "1"` newswire vs. retail splitting, and the `edited` text `known_at` guard run
//! before `provider_mapping` resolution.
//! - **Eastern local posting date (`posted_at`, not UTC date or `known_at`):** resolves each
//! post's `(mapping_source, key, et_date)` to a permanent `listing_id: i32` where `et_date` is
//! the `America/Toronto` (Eastern) local calendar date of `posted_at` via
//! [`crate::session_close::utc_micros_to_et_local`]. Late edits never shift a post onto a
//! different listing, while text availability remains guarded by `known_at`.
//! - Timestamps outside the range supported by `utc_micros_to_et_local` (`1976-01-01..=2030-12-31`
//! Eastern) are dropped and counted in [`CuratePostsStats::dropped_unsupported_date`] before
//! checking mapping coverage, without aborting or panicking.
//! - Rows with no covering `provider_mapping` range are dropped into
//! [`CuratePostsStats::dropped_unmapped`]. Because `build_posts` sorts by
//! `(key, known_at, spiel_id)` rather than `posted_at`, per-key lookups rely on
//! [`ProviderMappingCursor::resolve`]'s binary-search fallback whenever `et_date` steps
//! backward.
//! - Converts each mapped [`PostRow<i32>`] via [`EventsParquetRow::from`] (reusing
//! [`crate::parquet_posts`] labels and payload encoding verbatim), frees builder vectors 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)`,
//! and collapses exact 7-field duplicates into [`CuratePostsStats::listing_duplicate_collapsed`]
//! as a defensive writer-key uniqueness guard.
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::path::Path;
use crate::parquet_events::{
write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
ParquetEventsError,
};
use crate::parquet_posts::{POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL};
use crate::posts::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats};
use crate::provider_mapping::{ProviderMappingCursor, ProviderMappingTable};
use crate::session_close::utc_micros_to_et_local;
/// Accounting summary produced alongside [`CuratePostsOutput::rows`].
///
/// Conservation invariants:
/// - `rows_in == builder.newswire + builder.retail`
/// - `rows_in == rows_out + dropped_unmapped + dropped_unsupported_date + listing_duplicate_collapsed`
/// - `rows_out == newswire_out + retail_out`
/// - `builder` independently satisfies all [`PostsStats`] conservation invariants.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CuratePostsStats {
pub builder: PostsStats,
pub rows_in: usize,
pub rows_out: usize,
pub newswire_out: usize,
pub retail_out: usize,
pub listings_out: usize,
pub dropped_unmapped: usize,
pub dropped_unsupported_date: usize,
pub listing_duplicate_collapsed: usize,
}
/// Output of [`curate_posts`]: contract Parquet rows strictly ascending in the 7-field writer
/// sort key and full stage + builder stats.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CuratePostsOutput {
pub rows: Vec<EventsParquetRow>,
pub stats: CuratePostsStats,
}
/// Typed caller errors returned by [`curate_posts`].
///
/// Unmapped rows and posts outside the supported Eastern calendar range are dropped and counted
/// in [`CuratePostsStats`] rather than aborting the stage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CuratePostsError {
/// Error propagated from [`build_posts`] (e.g., [`PostsError::TimestampOverflow`]).
Posts(PostsError),
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
EmptyMappingSource,
}
impl fmt::Display for CuratePostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Posts(err) => write!(f, "{err}"),
Self::EmptyMappingSource => {
write!(f, "mapping_source must not be empty or blank")
}
}
}
}
impl Error for CuratePostsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Posts(err) => Some(err),
Self::EmptyMappingSource => None,
}
}
}
impl From<PostsError> for CuratePostsError {
fn from(err: PostsError) -> Self {
Self::Posts(err)
}
}
/// Combined stats returned by [`curate_and_write_posts`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CuratePostsWriteReport {
pub curate_stats: CuratePostsStats,
pub write_stats: EventsWriteStats,
}
/// Typed error returned by [`curate_and_write_posts`].
#[derive(Debug)]
pub enum CuratePostsWriteError {
Curate(CuratePostsError),
Parquet(ParquetEventsError),
}
impl fmt::Display for CuratePostsWriteError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Curate(err) => write!(f, "posts curation failed: {err}"),
Self::Parquet(err) => write!(f, "posts Parquet write failed: {err}"),
}
}
}
impl Error for CuratePostsWriteError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Curate(err) => Some(err),
Self::Parquet(err) => Some(err),
}
}
}
impl From<CuratePostsError> for CuratePostsWriteError {
fn from(err: CuratePostsError) -> Self {
Self::Curate(err)
}
}
impl From<ParquetEventsError> for CuratePostsWriteError {
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()))
}
fn resolve_and_finalize<K>(
build: PostsBuild<K>,
mapping_source: &str,
mapping: &ProviderMappingTable,
) -> CuratePostsOutput
where
K: Ord + Clone + AsRef<str>,
{
let rows_in = build.newswire.len() + build.retail.len();
let mut stats = CuratePostsStats {
builder: build.stats,
rows_in,
..CuratePostsStats::default()
};
let mut rows: Vec<EventsParquetRow> = Vec::with_capacity(rows_in);
for stream in [build.newswire, build.retail] {
let mut current_key: Option<K> = None;
let mut current_cursor: Option<ProviderMappingCursor<'_>> = None;
for row in stream {
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 Ok(et_local) = utc_micros_to_et_local(row.posted_at) else {
stats.dropped_unsupported_date += 1;
continue;
};
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(et_local.session_date) else {
stats.dropped_unmapped += 1;
continue;
};
let mapped_row = PostRow {
key: listing_id,
spiel_id: row.spiel_id,
posted_at: row.posted_at,
known_at: row.known_at,
is_bot: row.is_bot,
is_edited: row.is_edited,
user_id: row.user_id,
text: row.text,
source: row.source,
};
rows.push(EventsParquetRow::from(mapped_row));
}
}
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.subtype.as_str() {
POST_SUBTYPE_NEWSWIRE => stats.newswire_out += 1,
POST_SUBTYPE_RETAIL => stats.retail_out += 1,
other => unreachable!("unexpected post subtype from parquet_posts: {other:?}"),
}
}
stats.rows_out = rows.len();
CuratePostsOutput { rows, stats }
}
/// Pure `posts` curation stage: builds point-in-time `ceoPosts` newswire and retail streams on
/// source keys via [`build_posts`], resolves `(mapping_source, key, et_date) -> listing_id` on
/// each post's `America/Toronto` (Eastern) local posting date via `provider_mapping`, and emits
/// contract [`EventsParquetRow`]s strictly ascending in the 7-field writer key.
///
/// Mapping lookup always uses the Eastern local calendar date of `posted_at` (never UTC date and
/// never `known_at`). Posts outside the supported Eastern calendar range are dropped into
/// `dropped_unsupported_date`; unmapped posts are dropped into `dropped_unmapped`.
pub fn curate_posts<K, I>(
posts: I,
mapping_source: &str,
mapping: &ProviderMappingTable,
) -> Result<CuratePostsOutput, CuratePostsError>
where
K: Ord + Clone + AsRef<str>,
I: IntoIterator<Item = CeoPost<K>>,
{
if mapping_source.trim().is_empty() {
return Err(CuratePostsError::EmptyMappingSource);
}
let built = build_posts(posts)?;
Ok(resolve_and_finalize(built, mapping_source, mapping))
}
/// Thin end-to-end wrapper running [`curate_posts`] and publishing the resulting contract rows
/// via [`write_events_dataset`] to `<out_dir>/events/year=YYYY/part.parquet`.
///
/// Any [`CuratePostsError`] returns before [`write_events_dataset`] is invoked, leaving
/// `out_dir` untouched.
pub fn curate_and_write_posts<P, K, I>(
out_dir: P,
posts: I,
mapping_source: &str,
mapping: &ProviderMappingTable,
options: EventsWriteOptions,
) -> Result<CuratePostsWriteReport, CuratePostsWriteError>
where
P: AsRef<Path>,
K: Ord + Clone + AsRef<str>,
I: IntoIterator<Item = CeoPost<K>>,
{
let curated = curate_posts(posts, mapping_source, mapping)?;
let write_stats = write_events_dataset(out_dir, &curated.rows, options)?;
Ok(CuratePostsWriteReport {
curate_stats: curated.stats,
write_stats,
})
}
#[cfg(test)]
#[path = "curate_posts_tests.rs"]
mod tests;