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

692 lines
24 KiB
Rust

//! File-to-file `curate-posts` runner (`M2.2i`).
//!
//! Streams a concatenated raw BSON `ceoPosts` dump file alongside `provider_mapping.tsv` into an
//! atomically published `<out_dir>/events/year=YYYY/part.parquet` dataset via
//! [`curate_and_write_posts`].
//!
//! # Dedicated Output Directory & Clobber Guard
//! `write_events_dataset` replaces whole `<out_dir>/events/year=YYYY/part.parquet` files, and
//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `<out_dir>/events`
//! directory. To prevent silently clobbering another stage's partitions, this runner **requires a
//! dedicated output directory** and fails closed with [`RunCuratePostsError::EventsDatasetExists`]
//! before any write whenever `<out_dir>/events` already contains any `year=*` entry. Combining
//! filings, earnings, and posts into one `events` dataset is a separate follow-up.
//!
//! # Contract & Point-in-Time Rules
//! - Field names are supplied via [`CuratePostsArgs`] (validated via
//! [`CeoPostsFieldNames::validate`] before reading inputs).
//! - Numeric timestamp unit ([`CeoPostsTimestampUnit`]) has **no default** and must be chosen
//! explicitly by the caller because the live MongoDB `ceoPosts` numeric unit (`Seconds` vs.
//! `Millis`) is unverified in the repository. BSON `DateTime` values are always epoch
//! milliseconds regardless of unit.
//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from
//! [`crate::run_curate_bars::load_provider_mapping_tsv`].
//! - All decoded [`CeoPost`] rows are passed directly to [`curate_and_write_posts`] (which splits
//! `bot == "1"` newswire vs. retail, enforces the `edited` text `known_at` guard, resolves
//! `provider_mapping` on the Eastern local posting date of `posted_at`, and drops unmapped or
//! unsupported-date rows into stats).
//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON chunk buffer
//! (`peak_chunk_bytes`); decoded posts and their text accumulate in memory before
//! [`curate_and_write_posts`] runs, as [`crate::curate_posts::curate_posts`] requires.
//! - **Empty / all-unmapped behavior:** returns `Ok` with `rows_written == 0` and
//! `files_written == 0` without creating `<out_dir>/events`.
//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `<out_dir>/events/year=*` entries,
//! invalid field names, blank `mapping_source`, unreadable inputs, malformed/overlapping
//! `provider_mapping.tsv`, truncated/corrupt BSON framing or element bytes, and curation
//! timestamp overflow errors return a typed [`RunCuratePostsError`] before touching `out_dir`.
//!
//! # Counter Conservation Invariants
//! Every successful [`CuratePostsRunReport`] satisfies:
//! - `docs_framed as usize == decode.docs_in == decode.rows_out + decode.skipped_total()`
//! - `decode.rows_out == curate_stats.builder.input`
//! - `curate_stats.builder.input == curate_stats.builder.newswire + curate_stats.builder.retail + curate_stats.builder.duplicates_dropped + curate_stats.builder.rejected_invalid`
//! - `curate_stats.rows_in == curate_stats.builder.newswire + curate_stats.builder.retail == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.dropped_unsupported_date + curate_stats.listing_duplicate_collapsed`
//! - `write_stats.rows_written == curate_stats.rows_out`
use std::collections::HashSet;
use std::error::Error;
use std::fmt::{self, Write as _};
use std::fs::{self, File};
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use crate::bson_ceo_posts::{
BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit,
};
use crate::bson_stream::{
decode_ceo_posts_chunks, BsonCeoPostsStreamError, BsonStreamError, BsonStreamOptions,
RawBsonChunkReader,
};
use crate::curate_posts::{curate_and_write_posts, CuratePostsStats, CuratePostsWriteError};
use crate::parquet_events::{EventsWriteOptions, EventsWriteStats};
use crate::posts::CeoPost;
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
/// Default `mapping_source` passed to `provider_mapping` lookups for `ceoPosts`.
pub const DEFAULT_MAPPING_SOURCE: &str = "ceo";
/// Arguments for [`run_curate_posts`].
///
/// `timestamp_unit` intentionally has no default: callers must explicitly choose
/// [`CeoPostsTimestampUnit::Seconds`] or [`CeoPostsTimestampUnit::Millis`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CuratePostsArgs {
pub ceo_posts: PathBuf,
pub provider_mapping: PathBuf,
pub out_dir: PathBuf,
pub timestamp_unit: CeoPostsTimestampUnit,
pub key_field: String,
pub spiel_id_field: String,
pub timestamp_field: String,
pub edited_field: String,
pub bot_field: String,
pub user_id_field: String,
pub text_field: String,
pub mapping_source: String,
}
impl CuratePostsArgs {
/// Borrows the configured BSON field names as [`CeoPostsFieldNames`].
#[inline]
pub fn field_names(&self) -> CeoPostsFieldNames<'_> {
CeoPostsFieldNames {
key: self.key_field.as_str(),
spiel_id: self.spiel_id_field.as_str(),
timestamp: self.timestamp_field.as_str(),
edited: self.edited_field.as_str(),
bot: self.bot_field.as_str(),
user_id: self.user_id_field.as_str(),
text: self.text_field.as_str(),
}
}
}
/// Full run report produced by [`run_curate_posts`] and [`run_curate_posts_with_reader`].
#[derive(Debug, Clone, PartialEq)]
pub struct CuratePostsRunReport {
pub docs_framed: u64,
pub bytes_read: u64,
pub peak_chunk_bytes: usize,
pub decode: BsonCeoPostsDecodeStats,
pub curate_stats: CuratePostsStats,
pub write_stats: EventsWriteStats,
pub elapsed_secs: f64,
}
/// Typed errors returned by [`run_curate_posts`] and [`run_curate_posts_with_reader`].
///
/// 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 RunCuratePostsError {
InvalidOutDir {
path: PathBuf,
detail: String,
},
InspectOutDir {
path: PathBuf,
source: io::Error,
},
EventsDatasetExists {
path: PathBuf,
},
InvalidFieldNames {
source: BsonCeoPostsError,
},
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: BsonCeoPostsError,
},
CurateWrite {
out_dir: PathBuf,
source: CuratePostsWriteError,
},
}
struct SingleLineWriter<'a, 'b> {
f: &'a mut fmt::Formatter<'b>,
}
impl fmt::Write for SingleLineWriter<'_, '_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let mut rest = s;
while let Some(idx) = rest.find(['\n', '\r']) {
let (head, tail) = rest.split_at(idx);
if !head.is_empty() {
self.f.write_str(head)?;
}
let mut chars = tail.chars();
match chars.next() {
Some('\n') => self.f.write_str("\\n")?,
Some('\r') => self.f.write_str("\\r")?,
_ => unreachable!(),
}
rest = chars.as_str();
}
if !rest.is_empty() {
self.f.write_str(rest)?;
}
Ok(())
}
}
impl fmt::Display for RunCuratePostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut w = SingleLineWriter { f };
match self {
Self::InvalidOutDir { path, detail } => {
write!(w, "invalid --out '{}': {detail}", path.display())
}
Self::InspectOutDir { path, source } => {
write!(
w,
"failed to inspect output path '{}': {source}",
path.display()
)
}
Self::EventsDatasetExists { path } => write!(
w,
"refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts",
path.display()
),
Self::InvalidFieldNames { source } => write!(w, "{source}"),
Self::EmptyMappingSource => {
write!(w, "invalid --mapping-source: must not be empty or blank")
}
Self::OpenInput {
label,
path,
source,
} => write!(w, "failed to open {label} '{}': {source}", path.display()),
Self::ReadInput {
label,
path,
source,
} => write!(w, "failed to read {label} '{}': {source}", path.display()),
Self::TsvParse { path, line, detail } => {
write!(w, "{}:{line}: {detail}", path.display())
}
Self::ProviderMapping { path, source } => {
write!(w, "invalid provider_mapping '{}': {source}", path.display())
}
Self::BsonStream { path, source } => {
write!(w, "failed reading ceo-posts '{}': {source}", path.display())
}
Self::CorruptBson {
path,
offset,
source,
} => write!(
w,
"corrupt ceo-posts BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CurateWrite { out_dir, source } => {
write!(w, "curate/write to '{}' failed: {source}", out_dir.display())
}
}
}
}
impl Error for RunCuratePostsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::InspectOutDir { source, .. } => Some(source),
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::EventsDatasetExists { .. }
| Self::EmptyMappingSource
| Self::TsvParse { .. } => None,
}
}
}
fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePostsError> {
if out_dir.as_os_str().is_empty() {
return Err(RunCuratePostsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "output directory path must not be empty".to_string(),
});
}
// Reject `..` after a missing path component: `fs::metadata` reports `NotFound` for the
// unresolved path, but `create_dir_all` would create the missing component and then traverse
// `..` into an existing directory, bypassing the events clobber guard.
let mut prefix = PathBuf::new();
let mut saw_missing = false;
for component in out_dir.components() {
match component {
Component::ParentDir => {
if saw_missing {
return Err(RunCuratePostsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "output path must not contain '..' after a missing component"
.to_string(),
});
}
prefix.push(component);
}
Component::CurDir => {
if !saw_missing {
prefix.push(component);
}
}
Component::RootDir | Component::Prefix(_) => {
prefix.push(component);
}
Component::Normal(_) => {
prefix.push(component);
if !saw_missing {
match fs::metadata(&prefix) {
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {
saw_missing = true;
}
Err(source) => {
return Err(RunCuratePostsError::InspectOutDir {
path: prefix,
source,
});
}
}
}
}
}
}
match fs::metadata(out_dir) {
Ok(meta) if !meta.is_dir() => {
return Err(RunCuratePostsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "path exists and is not a directory".to_string(),
});
}
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(source) => {
return Err(RunCuratePostsError::InspectOutDir {
path: out_dir.to_path_buf(),
source,
});
}
}
let events_dir = out_dir.join("events");
match fs::metadata(&events_dir) {
Ok(meta) if !meta.is_dir() => {
return Err(RunCuratePostsError::InvalidOutDir {
path: events_dir,
detail: "events output path exists and is not a directory".to_string(),
});
}
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(source) => {
return Err(RunCuratePostsError::InspectOutDir {
path: events_dir,
source,
});
}
}
let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir {
path: events_dir.clone(),
source,
})?;
let mut existing_year_entry: Option<PathBuf> = None;
for entry_res in entries {
let entry = entry_res.map_err(|source| RunCuratePostsError::InspectOutDir {
path: events_dir.clone(),
source,
})?;
let name = entry.file_name();
if name.to_string_lossy().starts_with("year=") {
let candidate = entry.path();
if existing_year_entry
.as_ref()
.is_none_or(|current| candidate < *current)
{
existing_year_entry = Some(candidate);
}
}
}
if let Some(path) = existing_year_entry {
return Err(RunCuratePostsError::EventsDatasetExists { path });
}
Ok(())
}
fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCuratePostsError {
match err {
RunCurateBarsError::OpenInput {
label,
path,
source,
} => RunCuratePostsError::OpenInput {
label,
path,
source,
},
RunCurateBarsError::ReadInput {
label,
path,
source,
} => RunCuratePostsError::ReadInput {
label,
path,
source,
},
RunCurateBarsError::TsvParse { path, line, detail } => {
RunCuratePostsError::TsvParse { path, line, detail }
}
RunCurateBarsError::ProviderMapping { path, source } => {
RunCuratePostsError::ProviderMapping { path, source }
}
other => RunCuratePostsError::TsvParse {
path: path.to_path_buf(),
line: 0,
detail: other.to_string(),
},
}
}
fn bson_error_offset(err: &BsonCeoPostsError) -> u64 {
match err {
BsonCeoPostsError::TruncatedDocument { offset, .. }
| BsonCeoPostsError::CorruptDocumentLength { offset, .. }
| BsonCeoPostsError::CorruptBson { offset, .. } => *offset,
BsonCeoPostsError::InvalidFieldNames { .. } => 0,
}
}
struct DecodedPostsInputs {
mapping: ProviderMappingTable,
posts: Vec<CeoPost<Arc<str>>>,
docs_framed: u64,
bytes_read: u64,
peak_chunk_bytes: usize,
decode: BsonCeoPostsDecodeStats,
}
fn decode_inputs_from_opener<R, F>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoPostsFieldNames<'_>,
timestamp_unit: CeoPostsTimestampUnit,
ceo_posts_path: &Path,
open_posts: F,
) -> Result<DecodedPostsInputs, RunCuratePostsError>
where
R: io::Read,
F: FnOnce() -> Result<R, RunCuratePostsError>,
{
fields
.validate()
.map_err(|source| RunCuratePostsError::InvalidFieldNames { source })?;
if mapping_source.trim().is_empty() {
return Err(RunCuratePostsError::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| {
RunCuratePostsError::ProviderMapping {
path: provider_mapping_path.to_path_buf(),
source,
}
})?;
let stream = open_posts()?;
let mut reader = RawBsonChunkReader::with_options(stream, BsonStreamOptions::default())
.map_err(|source| RunCuratePostsError::BsonStream {
path: ceo_posts_path.to_path_buf(),
source,
})?;
let mut key_interner: HashSet<Arc<str>> = HashSet::new();
let mut posts: Vec<CeoPost<Arc<str>>> = Vec::new();
let decode = decode_ceo_posts_chunks(&mut reader, fields, timestamp_unit, |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
};
posts.push(CeoPost {
key,
spiel_id: raw.spiel_id,
timestamp_ms: raw.timestamp_ms,
edited_ms: raw.edited_ms,
bot: raw.bot,
user_id: raw.user_id,
text: raw.text,
});
})
.map_err(|err| match err {
BsonCeoPostsStreamError::Stream(source) => RunCuratePostsError::BsonStream {
path: ceo_posts_path.to_path_buf(),
source,
},
BsonCeoPostsStreamError::Decode(source) => match &source {
BsonCeoPostsError::InvalidFieldNames { .. } => {
RunCuratePostsError::InvalidFieldNames { source }
}
_ => {
let offset = bson_error_offset(&source);
RunCuratePostsError::CorruptBson {
path: ceo_posts_path.to_path_buf(),
offset,
source,
}
}
},
})?;
Ok(DecodedPostsInputs {
mapping,
posts,
docs_framed: reader.docs_framed(),
bytes_read: reader.bytes_read(),
peak_chunk_bytes: reader.buffer_capacity(),
decode,
})
}
fn run_curate_posts_from_opener<R, F>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoPostsFieldNames<'_>,
timestamp_unit: CeoPostsTimestampUnit,
ceo_posts_path: &Path,
open_posts: F,
out_dir: &Path,
) -> Result<CuratePostsRunReport, RunCuratePostsError>
where
R: io::Read,
F: FnOnce() -> Result<R, RunCuratePostsError>,
{
let start = Instant::now();
validate_out_dir_and_events_guard(out_dir)?;
let decoded = decode_inputs_from_opener(
provider_mapping_path,
mapping_source,
fields,
timestamp_unit,
ceo_posts_path,
open_posts,
)?;
// Re-check output directory and clobber guard immediately before curating/writing.
validate_out_dir_and_events_guard(out_dir)?;
let write_report = curate_and_write_posts(
out_dir,
decoded.posts,
mapping_source,
&decoded.mapping,
EventsWriteOptions::default(),
)
.map_err(|source| RunCuratePostsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source,
})?;
Ok(CuratePostsRunReport {
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(),
})
}
/// Runs the end-to-end `curate-posts` file-to-Parquet pipeline via [`curate_and_write_posts`].
///
/// Any validation, clobber-guard, I/O, TSV, mapping, BSON framing/corruption, or curation error
/// returns before touching `args.out_dir`.
pub fn run_curate_posts(
args: &CuratePostsArgs,
) -> Result<CuratePostsRunReport, RunCuratePostsError> {
run_curate_posts_from_opener(
&args.provider_mapping,
&args.mapping_source,
&args.field_names(),
args.timestamp_unit,
&args.ceo_posts,
|| {
File::open(&args.ceo_posts).map_err(|source| RunCuratePostsError::OpenInput {
label: "ceo-posts",
path: args.ceo_posts.clone(),
source,
})
},
&args.out_dir,
)
}
/// Runs `curate-posts` from an arbitrary raw-BSON [`io::Read`] stream.
pub fn run_curate_posts_with_reader<R: io::Read>(
provider_mapping_path: &Path,
mapping_source: &str,
fields: &CeoPostsFieldNames<'_>,
timestamp_unit: CeoPostsTimestampUnit,
ceo_posts_input: (&Path, R),
out_dir: &Path,
) -> Result<CuratePostsRunReport, RunCuratePostsError> {
let (ceo_path, stream) = ceo_posts_input;
run_curate_posts_from_opener(
provider_mapping_path,
mapping_source,
fields,
timestamp_unit,
ceo_path,
|| Ok(stream),
out_dir,
)
}
/// Formats [`CuratePostsRunReport`] into a deterministic machine-readable `key=value` summary.
///
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
pub fn format_curate_posts_report(report: &CuratePostsRunReport) -> 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-posts\n\
\x20 ceo_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_spiel_id={} wrong_spiel_id_type={} empty_spiel_id={} missing_ts={} wrong_ts_type={} invalid_ts={} ts_oor={} invalid_edited={} wrong_text_type={}) emitted=(edited_zero_or_false={} nulled_bot={} nulled_user_id={} empty_text={})\n\
\x20 builder: input={} newswire={} retail={} edited={} edited_before_posted={} dup_dropped={} rejected_invalid={}\n\
\x20 curate: rows_in={} rows_out={} newswire_out={} retail_out={} listings_out={} dropped_unmapped={} dropped_unsupported_date={} listing_dup_collapsed={}\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_spiel_id,
d.skipped_wrong_spiel_id_type,
d.skipped_empty_spiel_id,
d.skipped_missing_timestamp,
d.skipped_wrong_timestamp_type,
d.skipped_invalid_timestamp,
d.skipped_timestamp_out_of_range,
d.skipped_invalid_edited,
d.skipped_wrong_text_type,
d.edited_zero_or_false,
d.nulled_wrong_type_bot,
d.nulled_wrong_type_user_id,
d.empty_text,
b.input,
b.newswire,
b.retail,
b.edited,
b.edited_before_posted,
b.duplicates_dropped,
b.rejected_invalid,
c.rows_in,
c.rows_out,
c.newswire_out,
c.retail_out,
c.listings_out,
c.dropped_unmapped,
c.dropped_unsupported_date,
c.listing_duplicate_collapsed,
w.files_written,
w.row_groups_written,
w.rows_written,
w.bytes_written,
report.elapsed_secs,
)
}
#[cfg(test)]
#[path = "run_curate_posts_tests.rs"]
mod tests;