T-164: M2.2i — tools/curate-etl: file-to-file ceoPosts runner (decode_ceo_posts_chunks in bson_stream.rs + run_curate_posts.rs: raw BSON dump + provider_mapping.tsv → curate_and_write_posts → events Zstd Parquet) with tests (no new crates, no CLI/bench changes, no live Mongo)

This commit is contained in:
Studio 2026-12-02 10:34:50 -05:00
parent b061299b44
commit d999ebe595
6 changed files with 2023 additions and 8 deletions

View file

@ -142,7 +142,16 @@ Rules:
4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties 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. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`.
5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`.
Deferred out of `src/posts.rs`: `curate-posts` CLI subcommand, benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, and `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`).
Deferred out of `src/posts.rs`: `curate-posts` CLI subcommand, benchmark, live `ceoPosts` verification (including live `edited` BSON type verification), and co-publishing with `curate-events` output (offline raw-BSON decoding lives in `src/bson_ceo_posts.rs`, chunked streaming in `src/bson_stream.rs`, `events` Parquet row mapping in `src/parquet_posts.rs`, `provider_mapping` listing resolution + Parquet writing in `src/curate_posts.rs`, and the file-to-file runner in `src/run_curate_posts.rs`).
### `run_curate_posts` File-to-File Runner (`M2.2i`)
`run_curate_posts` / `run_curate_posts_with_reader` (`src/run_curate_posts.rs`) connects a concatenated raw BSON `ceoPosts` dump file and a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) through `decode_ceo_posts_chunks` (`src/bson_stream.rs`) and `curate_and_write_posts` into `<out_dir>/events/year=YYYY/part.parquet` (Zstd Parquet):
- **Explicit timestamp unit (no default):** `CuratePostsArgs::timestamp_unit` requires callers to pass `CeoPostsTimestampUnit::Seconds` or `CeoPostsTimestampUnit::Millis` explicitly (the live MongoDB numeric unit is unverified in the repo; BSON `DateTime` values are always epoch milliseconds).
- **Dedicated output directory & clobber guard:** Because `write_events_dataset` replaces whole `events/year=YYYY/part.parquet` files and `run_curate_events` (filings + earnings) writes to the same `<out_dir>/events` path, `run_curate_posts` requires a dedicated `--out` 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 a single `events` dataset is a separate follow-up.
- **Zero-row & fail-closed behavior:** Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/events`. Validation, clobber checks, TSV loading, full BSON decoding, and curation complete before `out_dir` is touched.
- **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 `curate_posts` requires).
## `events` Builder (`M1.2g`)

View file

@ -21,6 +21,10 @@ use std::error::Error;
use std::fmt;
use std::io;
use crate::bson_ceo_posts::{
decode_ceo_posts_buffer, BsonCeoPostsDecodeStats, BsonCeoPostsError, CeoPostsFieldNames,
CeoPostsTimestampUnit,
};
use crate::bson_ceo_shorts::{
decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames,
};
@ -50,6 +54,7 @@ use crate::bson_te_market_data::{
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
};
use crate::fx::FxDailyBar;
use crate::posts::CeoPost;
use crate::shorts::CeoShortReport;
/// Default chunk buffer capacity: 8 MiB.
@ -973,6 +978,112 @@ where
decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error)
}
/// Terminal error returned by [`decode_ceo_posts_chunks`] and [`decode_ceo_posts_stream`].
#[derive(Debug)]
pub enum BsonCeoPostsStreamError {
Stream(BsonStreamError),
Decode(BsonCeoPostsError),
}
impl fmt::Display for BsonCeoPostsStreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stream(err) => write!(f, "{err}"),
Self::Decode(err) => write!(f, "{err}"),
}
}
}
impl Error for BsonCeoPostsStreamError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Stream(err) => Some(err),
Self::Decode(err) => Some(err),
}
}
}
impl From<BsonStreamError> for BsonCeoPostsStreamError {
fn from(err: BsonStreamError) -> Self {
Self::Stream(err)
}
}
impl From<BsonCeoPostsError> for BsonCeoPostsStreamError {
fn from(err: BsonCeoPostsError) -> Self {
Self::Decode(err)
}
}
#[inline]
fn rebase_ceo_posts_error(base: u64, err: BsonCeoPostsError) -> BsonCeoPostsError {
match err {
BsonCeoPostsError::TruncatedDocument {
offset,
remaining,
declared_len,
} => BsonCeoPostsError::TruncatedDocument {
offset: base.saturating_add(offset),
remaining,
declared_len,
},
BsonCeoPostsError::CorruptDocumentLength {
offset,
declared_len,
} => BsonCeoPostsError::CorruptDocumentLength {
offset: base.saturating_add(offset),
declared_len,
},
BsonCeoPostsError::CorruptBson { offset, detail } => BsonCeoPostsError::CorruptBson {
offset: base.saturating_add(offset),
detail,
},
other => other,
}
}
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_ceo_posts_buffer`],
/// accumulating [`BsonCeoPostsDecodeStats`] and rebasing structural BSON error offsets to
/// absolute stream byte offsets.
pub fn decode_ceo_posts_chunks<R, F>(
reader: &mut RawBsonChunkReader<R>,
fields: &CeoPostsFieldNames<'_>,
unit: CeoPostsTimestampUnit,
mut on_row: F,
) -> Result<BsonCeoPostsDecodeStats, BsonCeoPostsStreamError>
where
R: io::Read,
F: for<'a> FnMut(CeoPost<&'a str>),
{
fields.validate()?;
let mut total = BsonCeoPostsDecodeStats::default();
while let Some(chunk) = reader.next_chunk()? {
let base = chunk.start_offset;
let chunk_stats = decode_ceo_posts_buffer(chunk.bytes, fields, unit, &mut on_row)
.map_err(|err| BsonCeoPostsStreamError::Decode(rebase_ceo_posts_error(base, err)))?;
total += chunk_stats;
}
Ok(total)
}
/// Streams a concatenated raw BSON `ceoPosts` [`std::io::Read`] source through
/// [`decode_ceo_posts_buffer`] with bounded memory.
pub fn decode_ceo_posts_stream<R, F>(
reader: R,
options: BsonStreamOptions,
fields: &CeoPostsFieldNames<'_>,
unit: CeoPostsTimestampUnit,
on_row: F,
) -> Result<BsonCeoPostsDecodeStats, BsonCeoPostsStreamError>
where
R: io::Read,
F: for<'a> FnMut(CeoPost<&'a str>),
{
fields.validate()?;
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
decode_ceo_posts_chunks(&mut chunk_reader, fields, unit, on_row)
}
/// Terminal error returned by [`decode_ceo_shorts_chunks`] and [`decode_ceo_shorts_stream`].
#[derive(Debug)]
pub enum BsonCeoShortsStreamError {

View file

@ -1731,6 +1731,268 @@ fn randomized_buffer_and_read_size_sweep_matches_buffer_decoder() {
}
}
#[test]
fn ceo_posts_chunks_match_buffer_across_small_chunks_and_respect_timestamp_unit() {
use super::{decode_ceo_posts_chunks, BsonStreamOptions, RawBsonChunkReader};
use crate::bson_ceo_posts::{
decode_ceo_posts_buffer, CeoPostsFieldNames, CeoPostsTimestampUnit,
};
use crate::posts::CeoPost;
let fields = CeoPostsFieldNames::default();
let mut fixture = Vec::new();
for i in 0..40_i32 {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("ceoId"), format!("CEO{i}"));
doc.append(cstr!("spielId"), format!("sp-{i}"));
let ts_secs = 1_710_000_000_i64 + i64::from(i) * 60;
if i % 4 == 0 {
// BSON DateTime (always epoch milliseconds regardless of unit)
doc.append(
cstr!("timestamp"),
bson::DateTime::from_millis(ts_secs * 1_000),
);
} else if i % 4 == 1 {
doc.append(cstr!("timestamp"), ts_secs);
} else if i % 4 == 2 {
doc.append(cstr!("timestamp"), ts_secs as f64);
} else {
doc.append(cstr!("timestamp"), ts_secs as i32);
}
if i % 6 == 0 {
// Edited with numeric timestamp
doc.append(cstr!("edited"), ts_secs + 120);
} else if i % 6 == 1 {
// Edited with BSON DateTime
doc.append(
cstr!("edited"),
bson::DateTime::from_millis((ts_secs + 180) * 1_000),
);
} else if i % 6 == 2 {
// Zero sentinel -> unedited
doc.append(cstr!("edited"), 0_i32);
} else if i % 6 == 3 {
// Semantic skip: invalid edited value (boolean true)
doc.append(cstr!("edited"), true);
}
if i % 5 == 0 {
doc.append(cstr!("bot"), "1");
} else if i % 5 == 1 {
doc.append(cstr!("bot"), false);
}
doc.append(cstr!("userId"), format!("user-{i}"));
if i % 9 == 0 {
// Semantic skip: wrong text type
doc.append(cstr!("spiel"), 123_i32);
} else {
doc.append(cstr!("spiel"), format!("post body #{i}"));
}
fixture.extend_from_slice(doc.as_bytes());
}
let to_owned = |p: CeoPost<&str>| CeoPost {
key: p.key.to_owned(),
spiel_id: p.spiel_id,
timestamp_ms: p.timestamp_ms,
edited_ms: p.edited_ms,
bot: p.bot,
user_id: p.user_id,
text: p.text,
};
for unit in [CeoPostsTimestampUnit::Seconds, CeoPostsTimestampUnit::Millis] {
let mut expected_rows = Vec::new();
let expected_stats = decode_ceo_posts_buffer(&fixture, &fields, unit, |p| {
expected_rows.push(to_owned(p));
})
.expect("buffer decode");
assert!(expected_stats.rows_out > 0);
assert!(expected_stats.skipped_total() > 0);
// Tiny capacities and small read steps splitting reads within documents, plus single-chunk.
for (cap, step) in [(17, 7), (64, 19), (128, 37), (fixture.len() + 64, fixture.len())] {
let opts = BsonStreamOptions {
chunk_capacity_bytes: cap,
max_doc_bytes: 4096,
};
let mut reader =
RawBsonChunkReader::with_options(FixedStepReader::new(&fixture, step), opts)
.unwrap();
let mut got_rows = Vec::new();
let got_stats = decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| {
got_rows.push(to_owned(p));
})
.expect("chunk decode");
assert_eq!(got_stats, expected_stats, "unit={unit:?} cap={cap}");
assert_eq!(got_rows, expected_rows, "unit={unit:?} cap={cap}");
assert_eq!(reader.docs_framed() as usize, expected_stats.docs_in);
assert!(
reader.buffer_capacity() <= 4096.max(fixture.len() + 64),
"capacity {} exceeded expected bound",
reader.buffer_capacity()
);
}
}
// Explicitly verify 1,000x difference for numeric posting & edit timestamps and unit
// independence for BSON DateTime.
let mut unit_fixture = Vec::new();
let numeric_ts = 1_710_000_123_i64;
let numeric_ed = 1_710_000_456_i64;
let dt_ts_ms = 1_710_000_789_000_i64;
let dt_ed_ms = 1_710_000_999_000_i64;
{
let mut d_num = RawDocumentBuf::new();
d_num.append(cstr!("ceoId"), "NUM");
d_num.append(cstr!("spielId"), "sp-num");
d_num.append(cstr!("timestamp"), numeric_ts);
d_num.append(cstr!("edited"), numeric_ed);
d_num.append(cstr!("spiel"), "numeric");
unit_fixture.extend_from_slice(d_num.as_bytes());
let mut d_dt = RawDocumentBuf::new();
d_dt.append(cstr!("ceoId"), "DT");
d_dt.append(cstr!("spielId"), "sp-dt");
d_dt.append(cstr!("timestamp"), bson::DateTime::from_millis(dt_ts_ms));
d_dt.append(cstr!("edited"), bson::DateTime::from_millis(dt_ed_ms));
d_dt.append(cstr!("spiel"), "datetime");
unit_fixture.extend_from_slice(d_dt.as_bytes());
}
let decode_unit = |unit: CeoPostsTimestampUnit| -> Vec<CeoPost<String>> {
let mut rows = Vec::new();
let mut reader = RawBsonChunkReader::with_options(
FixedStepReader::new(&unit_fixture, 11),
BsonStreamOptions {
chunk_capacity_bytes: 32,
max_doc_bytes: 4096,
},
)
.unwrap();
decode_ceo_posts_chunks(&mut reader, &fields, unit, |p| rows.push(to_owned(p)))
.expect("decode unit fixture");
rows
};
let rows_sec = decode_unit(CeoPostsTimestampUnit::Seconds);
let rows_ms = decode_unit(CeoPostsTimestampUnit::Millis);
assert_eq!(rows_sec.len(), 2);
assert_eq!(rows_ms.len(), 2);
// Numeric doc: Seconds is 1,000x Millis for both timestamp and edited.
assert_eq!(rows_ms[0].timestamp_ms, numeric_ts);
assert_eq!(rows_sec[0].timestamp_ms, numeric_ts * 1_000);
assert_eq!(rows_ms[0].edited_ms, Some(numeric_ed));
assert_eq!(rows_sec[0].edited_ms, Some(numeric_ed * 1_000));
// DateTime doc: identical under both Seconds and Millis.
assert_eq!(rows_ms[1].timestamp_ms, dt_ts_ms);
assert_eq!(rows_sec[1].timestamp_ms, dt_ts_ms);
assert_eq!(rows_ms[1].edited_ms, Some(dt_ed_ms));
assert_eq!(rows_sec[1].edited_ms, Some(dt_ed_ms));
}
#[test]
fn ceo_posts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() {
use super::{
decode_ceo_posts_chunks, decode_ceo_posts_stream, BsonCeoPostsStreamError,
BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
};
use crate::bson_ceo_posts::{BsonCeoPostsError, CeoPostsFieldNames, CeoPostsTimestampUnit};
// Duplicate field role rejected before reading.
let bad_fields = CeoPostsFieldNames {
key: "ceoId",
spiel_id: "ceoId",
..CeoPostsFieldNames::default()
};
assert!(matches!(
decode_ceo_posts_stream(
Cursor::new(Vec::<u8>::new()),
BsonStreamOptions::default(),
&bad_fields,
CeoPostsTimestampUnit::Millis,
|_| {},
),
Err(BsonCeoPostsStreamError::Decode(
BsonCeoPostsError::InvalidFieldNames { .. }
))
));
let fields = CeoPostsFieldNames::default();
let mut good = RawDocumentBuf::new();
good.append(cstr!("ceoId"), "RY");
good.append(cstr!("spielId"), "sp-1");
good.append(cstr!("timestamp"), 1_710_460_800_000_i64);
good.append(cstr!("spiel"), "ok");
let good_bytes = good.into_bytes();
let mut corrupt = RawDocumentBuf::new();
corrupt.append(cstr!("ceoId"), "TD");
corrupt.append(cstr!("z"), 1_i32);
let mut corrupt_bytes = corrupt.into_bytes();
let z_pos = corrupt_bytes
.windows(3)
.position(|w| w == [0x10, b'z', 0x00])
.expect("locate z");
corrupt_bytes[z_pos] = 0x7e;
let mut combined = Vec::new();
combined.extend_from_slice(&good_bytes);
combined.extend_from_slice(&good_bytes);
let expected_offset = combined.len() as u64;
combined.extend_from_slice(&corrupt_bytes);
// Chunk capacity == one doc forces the corrupt doc into a subsequent chunk.
let opts = BsonStreamOptions {
chunk_capacity_bytes: good_bytes.len(),
max_doc_bytes: 4096,
};
let mut reader = RawBsonChunkReader::with_options(Cursor::new(combined), opts).unwrap();
let err = decode_ceo_posts_chunks(
&mut reader,
&fields,
CeoPostsTimestampUnit::Millis,
|_| {},
)
.unwrap_err();
assert!(
matches!(
err,
BsonCeoPostsStreamError::Decode(BsonCeoPostsError::CorruptBson { offset, .. })
if offset == expected_offset
),
"expected rebased CorruptBson at {expected_offset}, got {err:?}"
);
// Truncated trailing document preserves RawBsonChunkReader's absolute offset.
let mut truncated = Vec::new();
truncated.extend_from_slice(&good_bytes);
let trunc_offset = truncated.len() as u64;
truncated.extend_from_slice(&64_i32.to_le_bytes());
truncated.extend_from_slice(&[0x02, b'a', 0x00]);
let err = decode_ceo_posts_stream(
Cursor::new(truncated),
opts,
&fields,
CeoPostsTimestampUnit::Millis,
|_| {},
)
.unwrap_err();
assert!(
matches!(
err,
BsonCeoPostsStreamError::Stream(BsonStreamError::TruncatedDocument { offset, .. })
if offset == trunc_offset
),
"expected TruncatedDocument at {trunc_offset}, got {err:?}"
);
}
#[test]
fn ceo_shorts_stream_matches_buffer_across_small_chunks_and_preserves_bounded_capacity() {
use super::{decode_ceo_shorts_chunks, BsonStreamOptions, RawBsonChunkReader};

View file

@ -87,13 +87,14 @@ pub use bson_qm_prices::{
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,
};
pub use bson_stream::{
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_intraday_chunks,
decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream,
decode_qm_dividend_chunks, decode_qm_dividend_stream, decode_qm_earnings_chunks,
decode_qm_earnings_stream, decode_qm_filings_chunks, decode_qm_filings_stream,
decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_chunks,
decode_qm_price_stream, decode_qm_split_chunks, decode_qm_split_stream,
decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError,
decode_ceo_posts_chunks, decode_ceo_posts_stream, decode_ceo_shorts_chunks,
decode_ceo_shorts_stream, decode_eod_intraday_chunks, decode_eod_intraday_stream,
decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks,
decode_qm_dividend_stream, decode_qm_earnings_chunks, decode_qm_earnings_stream,
decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_intraday_chunks,
decode_qm_intraday_stream, decode_qm_price_chunks, decode_qm_price_stream,
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
decode_te_market_data_stream, BsonCeoPostsStreamError, BsonCeoShortsStreamError,
BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader,
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
};
@ -308,6 +309,12 @@ pub use run_curate_fx::{
ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE,
};
pub mod run_curate_posts;
pub use run_curate_posts::{
format_curate_posts_report, run_curate_posts, run_curate_posts_with_reader, CuratePostsArgs,
CuratePostsRunReport, RunCuratePostsError,
};
pub mod run_curate_shorts;
pub use run_curate_shorts::{
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,

View file

@ -0,0 +1,615 @@
//! 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;
use std::fs::{self, File};
use std::io;
use std::path::{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,
},
}
impl fmt::Display for RunCuratePostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidOutDir { path, detail } => {
write!(f, "invalid --out '{}': {detail}", path.display())
}
Self::InspectOutDir { path, source } => {
write!(f, "failed to inspect output path '{}': {source}", path.display())
}
Self::EventsDatasetExists { path } => write!(
f,
"refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts",
path.display()
),
Self::InvalidFieldNames { source } => write!(f, "{source}"),
Self::EmptyMappingSource => {
write!(f, "invalid --mapping-source: must not be empty or blank")
}
Self::OpenInput {
label,
path,
source,
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
Self::ReadInput {
label,
path,
source,
} => write!(f, "failed to read {label} '{}': {source}", path.display()),
Self::TsvParse { path, line, detail } => {
write!(f, "{}:{line}: {detail}", path.display())
}
Self::ProviderMapping { path, source } => {
write!(f, "invalid provider_mapping '{}': {source}", path.display())
}
Self::BsonStream { path, source } => {
write!(f, "failed reading ceo-posts '{}': {source}", path.display())
}
Self::CorruptBson {
path,
offset,
source,
} => write!(
f,
"corrupt ceo-posts BSON '{}' at byte offset {offset}: {source}",
path.display()
),
Self::CurateWrite { out_dir, source } => {
write!(f, "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(),
});
}
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;

File diff suppressed because it is too large Load diff