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

261 lines
9.5 KiB
Rust

//! Pure, in-memory `posts` builder for `ceoPosts` (`bot == "1"` newswire vs. retail split,
//! `edited` text point-in-time `known_at` guard, and deterministic global `spielId` deduplication).
//!
//! Aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row):
//! - Separates `bot == "1"` newswire posts (e.g. `@thenewswire`) from retail posts so wire
//! releases are never pooled with crowd chat.
//! - Computes text availability as `known_at = COALESCE(edited, timestamp)` in UTC microseconds,
//! clamped so `known_at >= posted_at` always holds.
//! - **Point-in-time rule:** any text-based feature or sentiment model MUST join on `known_at`,
//! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version
//! history, so the builder retains one supplied version per `spiel_id` and cannot recover
//! earlier pre-edit text.
use std::error::Error;
use std::fmt;
/// Canonical provenance label written to [`PostRow::source`].
pub const POSTS_SOURCE_CEO: &str = "ceo_posts";
/// Typed errors returned by [`build_posts`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PostsError {
/// Converting a millisecond timestamp (`timestamp_ms` or `edited_ms`) to UTC microseconds
/// overflowed `i64`.
TimestampOverflow {
spiel_id: String,
field: &'static str,
timestamp_ms: i64,
},
}
impl fmt::Display for PostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TimestampOverflow {
spiel_id,
field,
timestamp_ms,
} => write!(
f,
"timestamp overflow converting {field}={timestamp_ms} ms to UTC microseconds for spiel_id '{spiel_id}'"
),
}
}
}
impl Error for PostsError {}
/// A single already-decoded `ceoPosts` input row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CeoPost<K = String> {
/// Channel / `ceoId` (or resolved listing key).
pub key: K,
/// Provider post identifier (`spielId`, MongoDB upsert key).
pub spiel_id: String,
/// Provider post creation time in epoch milliseconds (`timestamp`).
pub timestamp_ms: i64,
/// Optional provider last-edit time in epoch milliseconds (`edited`).
pub edited_ms: Option<i64>,
/// Raw provider bot flag (`bot`; only `"1"` after trim classifies as newswire).
pub bot: Option<String>,
/// Optional provider author identifier (`userId`).
pub user_id: Option<String>,
/// Post text (`spiel`).
pub text: String,
}
/// A single curated `ceoPosts` output row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostRow<K = String> {
pub key: K,
pub spiel_id: String,
/// Post creation timestamp in UTC microseconds (`timestamp_ms * 1_000`).
pub posted_at: i64,
/// Point-in-time text availability timestamp in UTC microseconds (`max(posted_at, edited_at)`).
/// Downstream text features MUST join on `known_at`, never `posted_at`.
pub known_at: i64,
pub is_bot: bool,
pub is_edited: bool,
pub user_id: Option<String>,
pub text: String,
pub source: &'static str,
}
/// Summary accounting counters produced alongside [`PostsBuild::newswire`] and
/// [`PostsBuild::retail`].
///
/// Conservation invariant:
/// `input == newswire + retail + duplicates_dropped + rejected_invalid`
///
/// Accounting note: `edited` and `edited_before_posted` are counted on valid input rows before
/// `spiel_id` deduplication (so they include valid duplicates and exclude `rejected_invalid`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PostsStats {
pub input: usize,
pub newswire: usize,
pub retail: usize,
pub edited: usize,
pub edited_before_posted: usize,
pub duplicates_dropped: usize,
pub rejected_invalid: usize,
}
/// Output of [`build_posts`]: disjoint, deterministically sorted `newswire` and `retail` streams
/// plus exact accounting stats.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PostsBuild<K = String> {
pub newswire: Vec<PostRow<K>>,
pub retail: Vec<PostRow<K>>,
pub stats: PostsStats,
}
/// Builds disjoint, deterministically sorted `newswire` and `retail` post streams from raw
/// `ceoPosts` inputs.
///
/// Rules:
/// - Rejects (counts in [`PostsStats::rejected_invalid`] without aborting) rows with an empty
/// `spiel_id` or `timestamp_ms <= 0` before timestamp conversion.
/// - Classifies `is_bot` as `true` iff `bot` is `"1"` after trimming whitespace; all other values
/// (`None`, `"0"`, `""`, etc.) route to `retail`.
/// - Sets `is_edited = edited_ms.is_some()`, counts valid edited rows in [`PostsStats::edited`],
/// and guards against look-ahead / clock-skew edits earlier than posting (`edited_ms <
/// timestamp_ms`) by clamping `known_at` to `posted_at` and incrementing
/// [`PostsStats::edited_before_posted`]. Both edit counters are recorded on valid rows prior to
/// deduplication.
/// - Converts `timestamp_ms` and the selected `known_at` millisecond value to UTC microseconds via
/// `checked_mul(1_000)`, returning [`PostsError::TimestampOverflow`] on overflow.
/// - Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail` (keeping
/// one supplied version per `spiel_id`; earlier pre-edit versions cannot be recovered). Within a
/// `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties
/// deterministically by the maximum lexicographic tuple
/// `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero
/// dependence on input order. All other `group_len - 1` rows are counted in
/// [`PostsStats::duplicates_dropped`].
/// - Sorts both `newswire` and `retail` strictly ascending by `(key, known_at, spiel_id)`.
/// - Any permutation of `rows` produces identical `newswire`, `retail`, and `stats`.
pub fn build_posts<K, I>(rows: I) -> Result<PostsBuild<K>, PostsError>
where
K: Ord + Clone,
I: IntoIterator<Item = CeoPost<K>>,
{
let iter = rows.into_iter();
let (lower, _) = iter.size_hint();
let mut stats = PostsStats::default();
let mut normalized: Vec<PostRow<K>> = Vec::with_capacity(lower);
for row in iter {
stats.input += 1;
if row.spiel_id.is_empty() || row.timestamp_ms <= 0 {
stats.rejected_invalid += 1;
continue;
}
let is_bot = row.bot.as_deref().map(str::trim) == Some("1");
let is_edited = row.edited_ms.is_some();
let known_at_ms = match row.edited_ms {
Some(edited_ms) => {
stats.edited += 1;
if edited_ms < row.timestamp_ms {
stats.edited_before_posted += 1;
row.timestamp_ms
} else {
edited_ms
}
}
None => row.timestamp_ms,
};
let posted_at =
row.timestamp_ms
.checked_mul(1_000)
.ok_or_else(|| PostsError::TimestampOverflow {
spiel_id: row.spiel_id.clone(),
field: "timestamp_ms",
timestamp_ms: row.timestamp_ms,
})?;
let known_at = if known_at_ms == row.timestamp_ms {
posted_at
} else {
known_at_ms
.checked_mul(1_000)
.ok_or_else(|| PostsError::TimestampOverflow {
spiel_id: row.spiel_id.clone(),
field: "edited_ms",
timestamp_ms: known_at_ms,
})?
};
normalized.push(PostRow {
key: row.key,
spiel_id: row.spiel_id,
posted_at,
known_at,
is_bot,
is_edited,
user_id: row.user_id,
text: row.text,
source: POSTS_SOURCE_CEO,
});
}
normalized.sort_unstable_by(|a, b| {
a.spiel_id
.cmp(&b.spiel_id)
.then_with(|| b.known_at.cmp(&a.known_at))
.then_with(|| b.posted_at.cmp(&a.posted_at))
.then_with(|| b.is_edited.cmp(&a.is_edited))
.then_with(|| b.is_bot.cmp(&a.is_bot))
.then_with(|| b.key.cmp(&a.key))
.then_with(|| b.user_id.cmp(&a.user_id))
.then_with(|| b.text.cmp(&a.text))
});
let mut newswire: Vec<PostRow<K>> = Vec::new();
let mut retail: Vec<PostRow<K>> = Vec::new();
let mut last_kept_in_newswire: Option<bool> = None;
for row in normalized {
let is_dup = match last_kept_in_newswire {
Some(true) => newswire
.last()
.is_some_and(|prev| prev.spiel_id == row.spiel_id),
Some(false) => retail
.last()
.is_some_and(|prev| prev.spiel_id == row.spiel_id),
None => false,
};
if is_dup {
stats.duplicates_dropped += 1;
continue;
}
if row.is_bot {
newswire.push(row);
last_kept_in_newswire = Some(true);
} else {
retail.push(row);
last_kept_in_newswire = Some(false);
}
}
let output_order = |a: &PostRow<K>, b: &PostRow<K>| {
a.key
.cmp(&b.key)
.then_with(|| a.known_at.cmp(&b.known_at))
.then_with(|| a.spiel_id.cmp(&b.spiel_id))
};
newswire.sort_unstable_by(output_order);
retail.sort_unstable_by(output_order);
stats.newswire = newswire.len();
stats.retail = retail.len();
Ok(PostsBuild {
newswire,
retail,
stats,
})
}