From d999ebe5958be2be0a82df2a471bd6ddbe80b145 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 10:34:50 -0500 Subject: [PATCH] =?UTF-8?q?T-164:=20M2.2i=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20file-to-file=20`ceoPosts`=20runner=20(`decode=5Fceo=5Fposts?= =?UTF-8?q?=5Fchunks`=20in=20`bson=5Fstream.rs`=20+=20`run=5Fcurate=5Fpost?= =?UTF-8?q?s.rs`:=20raw=20BSON=20dump=20+=20`provider=5Fmapping.tsv`=20?= =?UTF-8?q?=E2=86=92=20`curate=5Fand=5Fwrite=5Fposts`=20=E2=86=92=20`event?= =?UTF-8?q?s`=20Zstd=20Parquet)=20with=20tests=20(no=20new=20crates,=20no?= =?UTF-8?q?=20CLI/bench=20changes,=20no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 11 +- tools/curate-etl/src/bson_stream.rs | 111 ++ tools/curate-etl/src/bson_stream_tests.rs | 262 +++++ tools/curate-etl/src/lib.rs | 21 +- tools/curate-etl/src/run_curate_posts.rs | 615 ++++++++++ .../curate-etl/src/run_curate_posts_tests.rs | 1011 +++++++++++++++++ 6 files changed, 2023 insertions(+), 8 deletions(-) create mode 100644 tools/curate-etl/src/run_curate_posts.rs create mode 100644 tools/curate-etl/src/run_curate_posts_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 26f6a65f..599110d5 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -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 `/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 `/events` path, `run_curate_posts` requires a dedicated `--out` directory and fails closed with `RunCuratePostsError::EventsDatasetExists` before any write whenever `/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 `/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`) diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index be7c201a..270dd83d 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -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 for BsonCeoPostsStreamError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From 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( + reader: &mut RawBsonChunkReader, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + mut on_row: F, +) -> Result +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( + reader: R, + options: BsonStreamOptions, + fields: &CeoPostsFieldNames<'_>, + unit: CeoPostsTimestampUnit, + on_row: F, +) -> Result +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 { diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 1ca61802..72ccad08 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -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> { + 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::::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}; diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index bbcac68c..64296c92 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -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, diff --git a/tools/curate-etl/src/run_curate_posts.rs b/tools/curate-etl/src/run_curate_posts.rs new file mode 100644 index 00000000..2a1cd13e --- /dev/null +++ b/tools/curate-etl/src/run_curate_posts.rs @@ -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 `/events/year=YYYY/part.parquet` dataset via +//! [`curate_and_write_posts`]. +//! +//! # Dedicated Output Directory & Clobber Guard +//! `write_events_dataset` replaces whole `/events/year=YYYY/part.parquet` files, and +//! [`crate::run_curate_events`] (filings + earnings) publishes to the same `/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 `/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 `/events`. +//! - **Fail-closed safety:** invalid `out_dir`, pre-existing `/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 = 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>>, + docs_framed: u64, + bytes_read: u64, + peak_chunk_bytes: usize, + decode: BsonCeoPostsDecodeStats, +} + +fn decode_inputs_from_opener( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_path: &Path, + open_posts: F, +) -> Result +where + R: io::Read, + F: FnOnce() -> Result, +{ + 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> = HashSet::new(); + let mut posts: Vec>> = 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 = 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( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_path: &Path, + open_posts: F, + out_dir: &Path, +) -> Result +where + R: io::Read, + F: FnOnce() -> Result, +{ + 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 { + 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( + provider_mapping_path: &Path, + mapping_source: &str, + fields: &CeoPostsFieldNames<'_>, + timestamp_unit: CeoPostsTimestampUnit, + ceo_posts_input: (&Path, R), + out_dir: &Path, +) -> Result { + 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; diff --git a/tools/curate-etl/src/run_curate_posts_tests.rs b/tools/curate-etl/src/run_curate_posts_tests.rs new file mode 100644 index 00000000..3115963e --- /dev/null +++ b/tools/curate-etl/src/run_curate_posts_tests.rs @@ -0,0 +1,1011 @@ +use std::borrow::Cow; +use std::fs::{self, File}; +use std::io::{self, Cursor, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::bson_ceo_posts::{ + DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD, DEFAULT_SPIEL_ID_FIELD, + DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, +}; +use crate::curate_posts::{curate_posts, CuratePostsError, CuratePostsWriteError}; +use crate::parquet_events::EventsParquetRow; +use crate::parquet_posts::{ + EVENT_KIND_POST, KNOWN_AT_SOURCE_POST_EDITED, KNOWN_AT_SOURCE_POST_TIMESTAMP, + POST_SUBTYPE_NEWSWIRE, POST_SUBTYPE_RETAIL, +}; +use crate::posts::PostsError; +use crate::provider_mapping::ProviderMappingRow; +use crate::split::ymd_to_epoch_days; + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-run-posts-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn utc_ms(year: i32, month: u32, day_num: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(year, month, day_num); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000 +} + +fn write_bytes(path: &Path, bytes: &[u8]) { + let mut f = File::create(path).expect("create file"); + f.write_all(bytes).expect("write file"); +} + +fn default_args( + ceo_posts: PathBuf, + provider_mapping: PathBuf, + out_dir: PathBuf, + timestamp_unit: CeoPostsTimestampUnit, +) -> CuratePostsArgs { + CuratePostsArgs { + ceo_posts, + provider_mapping, + out_dir, + timestamp_unit, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_MAPPING_SOURCE.to_string(), + } +} + +#[allow(clippy::too_many_arguments)] +fn make_post_doc( + fields: &CeoPostsFieldNames<'_>, + key: &str, + spiel_id: &str, + timestamp: i64, + edited: Option, + bot: Option<&str>, + user_id: Option<&str>, + text: &str, +) -> Vec { + let cstring = |s: &str| bson::raw::CString::try_from(s.to_owned()).expect("valid BSON key"); + let mut doc = RawDocumentBuf::new(); + doc.append(cstring(fields.key), key); + doc.append(cstring(fields.spiel_id), spiel_id); + doc.append(cstring(fields.timestamp), timestamp); + if let Some(ed) = edited { + doc.append(cstring(fields.edited), ed); + } + if let Some(b) = bot { + doc.append(cstring(fields.bot), b); + } + if let Some(u) = user_id { + doc.append(cstring(fields.user_id), u); + } + doc.append(cstring(fields.text), text); + doc.into_bytes() +} + +fn assert_report_invariants(report: &CuratePostsRunReport) { + assert_eq!(report.docs_framed as usize, report.decode.docs_in); + assert_eq!( + report.decode.docs_in, + report.decode.rows_out + report.decode.skipped_total() + ); + let b = &report.curate_stats.builder; + assert_eq!(report.decode.rows_out, b.input); + assert_eq!( + b.input, + b.newswire + b.retail + b.duplicates_dropped + b.rejected_invalid + ); + let c = &report.curate_stats; + assert_eq!(c.rows_in, b.newswire + b.retail); + assert_eq!( + c.rows_in, + c.rows_out + c.dropped_unmapped + c.dropped_unsupported_date + c.listing_duplicate_collapsed + ); + assert_eq!(c.rows_out, c.newswire_out + c.retail_out); + assert_eq!(report.write_stats.rows_written, c.rows_out); +} + +fn read_events_parquet_and_verify_zstd(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + assert_eq!(rg_meta.num_columns(), 7, "expected 7 columns in events schema"); + for col_idx in 0..rg_meta.num_columns() { + let compression = rg_meta.column(col_idx).compression(); + assert!( + matches!(compression, Compression::ZSTD(_)), + "expected ZSTD compression for row_group={rg_idx} col={col_idx}, got {compression:?}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_i32_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i32 records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 column at index {col_idx}"), + } + vals + }; + + let read_i64_col = |col_idx: usize| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .expect("read i64 records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 column at index {col_idx}"), + } + vals + }; + + let read_str_col = |col_idx: usize| -> Vec { + let mut raw = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx).expect("col reader") { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut raw) + .expect("read byte_array records"); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + } + raw.iter() + .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) + .collect() + }; + + let listing_ids = read_i32_col(0); + let ts = read_i64_col(1); + let known_at = read_i64_col(2); + let known_at_source = read_str_col(3); + let kind = read_str_col(4); + let subtype = read_str_col(5); + let payload_json = read_str_col(6); + + for i in 0..rg_rows { + out.push(EventsParquetRow { + listing_id: listing_ids[i], + ts_micros: ts[i], + known_at_micros: known_at[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + + out +} + +fn read_all_event_partitions(out_dir: &Path) -> Vec { + let events_dir = out_dir.join("events"); + let mut year_dirs: Vec = fs::read_dir(&events_dir) + .expect("read events dir") + .map(|e| e.expect("dir entry").path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("year=")) + }) + .collect(); + year_dirs.sort(); + + let mut all = Vec::new(); + for yd in year_dirs { + all.extend(read_events_parquet_and_verify_zstd(&yd.join("part.parquet"))); + } + all.sort_by(|a, b| { + 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())) + }); + all +} + +fn assert_single_line_err(err: &RunCuratePostsError) -> String { + let msg = err.to_string(); + assert!(!msg.is_empty(), "error message must not be empty"); + assert!( + !msg.contains('\n'), + "error message must be single-line, got: {msg:?}" + ); + msg +} + +struct FailingReader { + prefix: Vec, + pos: usize, +} + +impl Read for FailingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.pos < self.prefix.len() { + let n = (self.prefix.len() - self.pos).min(buf.len()); + buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "injected read failure", + )) + } +} + +#[test] +fn happy_path_matches_curate_posts_verifies_zstd_edit_time_and_invariants() { + let dir = TempDirGuard::new("happy"); + let bson_path = dir.path().join("ceoPosts.bson"); + let map_path = dir.path().join("provider_mapping.tsv"); + let out_a = dir.path().join("out_a"); + let out_b = dir.path().join("out_b"); + + let mapping_tsv = concat!( + "ceo\tCEO_RY\t2020-01-01\t\t101\n", + "ceo\tCEO_SHOP\t2024-01-01\t\t202\n", + ); + write_bytes(&map_path, mapping_tsv.as_bytes()); + + let fields = CeoPostsFieldNames::default(); + let t_wire = utc_ms(2024, 6, 15, 14, 0, 0); + let t_retail = utc_ms(2024, 6, 15, 14, 5, 0); + let t_edited_post = utc_ms(2024, 6, 15, 15, 0, 0); + let t_edited_at = utc_ms(2024, 6, 15, 18, 30, 0); + let t_2025 = utc_ms(2025, 1, 10, 16, 0, 0); + + // Semantic skip doc: invalid edited (boolean true) + let mut skipped_doc = RawDocumentBuf::new(); + skipped_doc.append(cstr!("ceoId"), "CEO_RY"); + skipped_doc.append(cstr!("spielId"), "sp-skip"); + skipped_doc.append(cstr!("timestamp"), t_wire); + skipped_doc.append(cstr!("edited"), true); + skipped_doc.append(cstr!("spiel"), "should skip"); + + let docs = vec![ + // 1. Newswire (bot == "1") + make_post_doc( + &fields, + "CEO_RY", + "sp-wire-1", + t_wire, + None, + Some("1"), + Some("thenewswire"), + "Royal Bank quarterly release", + ), + // 2. Retail (bot == "0") + make_post_doc( + &fields, + "CEO_RY", + "sp-retail-1", + t_retail, + None, + Some("0"), + Some("trader42"), + "Looking strong today", + ), + // 3. Edited retail post: posted at t_edited_post, edited at t_edited_at + make_post_doc( + &fields, + "CEO_SHOP", + "sp-edited-1", + t_edited_post, + Some(t_edited_at), + None, + Some("analyst99"), + "Updated guidance notes", + ), + // 4. Duplicate spielId (earlier version of sp-edited-1 -> dropped by dedup) + make_post_doc( + &fields, + "CEO_SHOP", + "sp-edited-1", + t_edited_post, + None, + None, + Some("analyst99"), + "Initial draft", + ), + // 5. Unmapped key -> dropped_unmapped + make_post_doc( + &fields, + "UNKNOWN_CH", + "sp-unmapped-1", + t_retail, + None, + None, + Some("anon"), + "Unmapped channel post", + ), + // 6. Second partition year (2025) + make_post_doc( + &fields, + "CEO_SHOP", + "sp-2025-1", + t_2025, + None, + Some("1"), + Some("globenewswire"), + "2025 update", + ), + // 7. Semantic skip + skipped_doc.into_bytes(), + ]; + + let mut forward_bytes = Vec::new(); + for d in &docs { + forward_bytes.extend_from_slice(d); + } + write_bytes(&bson_path, &forward_bytes); + + let args_a = default_args( + bson_path.clone(), + map_path.clone(), + out_a.clone(), + CeoPostsTimestampUnit::Millis, + ); + let report_a = run_curate_posts(&args_a).expect("run forward"); + assert_report_invariants(&report_a); + assert_eq!(report_a.docs_framed, 7); + assert_eq!(report_a.decode.docs_in, 7); + assert_eq!(report_a.decode.rows_out, 6); + assert_eq!(report_a.decode.skipped_invalid_edited, 1); + assert_eq!(report_a.curate_stats.builder.input, 6); + assert_eq!(report_a.curate_stats.builder.duplicates_dropped, 1); + assert_eq!(report_a.curate_stats.dropped_unmapped, 1); + assert_eq!(report_a.curate_stats.rows_out, 4); + assert_eq!(report_a.curate_stats.newswire_out, 2); + assert_eq!(report_a.curate_stats.retail_out, 2); + assert_eq!(report_a.write_stats.files_written, 2); + assert_eq!(report_a.write_stats.rows_written, 4); + + // Baseline comparison against pure curate_posts on equivalent typed inputs. + let baseline_mapping = ProviderMappingTable::from_rows(vec![ + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_RY".to_string(), + valid_from: day(2020, 1, 1), + valid_to: None, + listing_id: 101, + }, + ProviderMappingRow { + source: "ceo".to_string(), + source_id: "CEO_SHOP".to_string(), + valid_from: day(2024, 1, 1), + valid_to: None, + listing_id: 202, + }, + ]) + .expect("valid mapping"); + let baseline_posts = vec![ + CeoPost { + key: "CEO_RY".to_string(), + spiel_id: "sp-wire-1".to_string(), + timestamp_ms: t_wire, + edited_ms: None, + bot: Some("1".to_string()), + user_id: Some("thenewswire".to_string()), + text: "Royal Bank quarterly release".to_string(), + }, + CeoPost { + key: "CEO_RY".to_string(), + spiel_id: "sp-retail-1".to_string(), + timestamp_ms: t_retail, + edited_ms: None, + bot: Some("0".to_string()), + user_id: Some("trader42".to_string()), + text: "Looking strong today".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-edited-1".to_string(), + timestamp_ms: t_edited_post, + edited_ms: Some(t_edited_at), + bot: None, + user_id: Some("analyst99".to_string()), + text: "Updated guidance notes".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-edited-1".to_string(), + timestamp_ms: t_edited_post, + edited_ms: None, + bot: None, + user_id: Some("analyst99".to_string()), + text: "Initial draft".to_string(), + }, + CeoPost { + key: "UNKNOWN_CH".to_string(), + spiel_id: "sp-unmapped-1".to_string(), + timestamp_ms: t_retail, + edited_ms: None, + bot: None, + user_id: Some("anon".to_string()), + text: "Unmapped channel post".to_string(), + }, + CeoPost { + key: "CEO_SHOP".to_string(), + spiel_id: "sp-2025-1".to_string(), + timestamp_ms: t_2025, + edited_ms: None, + bot: Some("1".to_string()), + user_id: Some("globenewswire".to_string()), + text: "2025 update".to_string(), + }, + ]; + let baseline = curate_posts(baseline_posts, "ceo", &baseline_mapping).expect("baseline"); + let read_back = read_all_event_partitions(&out_a); + assert_eq!(read_back, baseline.rows); + assert_eq!(report_a.curate_stats, baseline.stats); + + // Independent checks on kind, subtype, and edited post's ts vs known_at. + assert!(read_back.iter().all(|r| r.kind.as_ref() == EVENT_KIND_POST)); + let wire_row = read_back + .iter() + .find(|r| r.payload_json.contains("sp-wire-1")) + .expect("newswire row"); + assert_eq!(wire_row.subtype, POST_SUBTYPE_NEWSWIRE); + assert_eq!(wire_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_TIMESTAMP); + assert_eq!(wire_row.ts_micros, t_wire * 1_000); + assert_eq!(wire_row.known_at_micros, t_wire * 1_000); + + let edited_row = read_back + .iter() + .find(|r| r.payload_json.contains("sp-edited-1")) + .expect("edited row"); + assert_eq!(edited_row.subtype, POST_SUBTYPE_RETAIL); + assert_eq!(edited_row.ts_micros, t_edited_post * 1_000); + assert_eq!(edited_row.known_at_micros, t_edited_at * 1_000); + assert_eq!(edited_row.known_at_source.as_ref(), KNOWN_AT_SOURCE_POST_EDITED); + + // Reversed input order must yield byte-identical Parquet files and deterministic report. + let bson_rev = dir.path().join("ceoPosts_rev.bson"); + let mut rev_bytes = Vec::new(); + for d in docs.iter().rev() { + rev_bytes.extend_from_slice(d); + } + write_bytes(&bson_rev, &rev_bytes); + + let args_b = CuratePostsArgs { + ceo_posts: bson_rev, + out_dir: out_b.clone(), + ..args_a + }; + let report_b = run_curate_posts(&args_b).expect("run reversed"); + assert_report_invariants(&report_b); + assert_eq!(report_a.curate_stats, report_b.curate_stats); + assert_eq!(report_a.write_stats, report_b.write_stats); + + for year in ["year=2024", "year=2025"] { + let a = fs::read(out_a.join("events").join(year).join("part.parquet")).expect("read a"); + let b = fs::read(out_b.join("events").join(year).join("part.parquet")).expect("read b"); + assert_eq!(a, b, "reversed input must produce byte-identical {year}/part.parquet"); + } + + let strip_timing = |s: &str| { + s.lines() + .filter(|l| !l.trim_start().starts_with("timing:")) + .collect::>() + .join("\n") + }; + assert_eq!( + strip_timing(&format_curate_posts_report(&report_a)), + strip_timing(&format_curate_posts_report(&report_b)) + ); +} + +#[test] +fn seconds_vs_millis_and_custom_fields_with_reader_work_end_to_end() { + let dir = TempDirGuard::new("units"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo_alt\tCH_1\t2020-01-01\t\t555\n"); + + let custom_fields = CeoPostsFieldNames { + key: "channel", + spiel_id: "id", + timestamp: "ts", + edited: "ed", + bot: "isBot", + user_id: "author", + text: "body", + }; + + let ts_sec = 1_718_460_000_i64; // 2024-06-15 14:00:00 UTC + let ed_sec = 1_718_463_600_i64; // 2024-06-15 15:00:00 UTC + let doc_sec = make_post_doc( + &custom_fields, + "CH_1", + "p-1", + ts_sec, + Some(ed_sec), + None, + Some("u1"), + "hello", + ); + let doc_ms = make_post_doc( + &custom_fields, + "CH_1", + "p-1", + ts_sec * 1_000, + Some(ed_sec * 1_000), + None, + Some("u1"), + "hello", + ); + + let out_sec = dir.path().join("out_sec"); + let out_ms = dir.path().join("out_ms"); + + let rep_sec = run_curate_posts_with_reader( + &map_path, + "ceo_alt", + &custom_fields, + CeoPostsTimestampUnit::Seconds, + (Path::new("in-mem-sec.bson"), Cursor::new(doc_sec)), + &out_sec, + ) + .expect("run seconds"); + let rep_ms = run_curate_posts_with_reader( + &map_path, + "ceo_alt", + &custom_fields, + CeoPostsTimestampUnit::Millis, + (Path::new("in-mem-ms.bson"), Cursor::new(doc_ms)), + &out_ms, + ) + .expect("run millis"); + + assert_report_invariants(&rep_sec); + assert_report_invariants(&rep_ms); + let rows_sec = read_all_event_partitions(&out_sec); + let rows_ms = read_all_event_partitions(&out_ms); + assert_eq!(rows_sec, rows_ms); + assert_eq!(rows_sec.len(), 1); + assert_eq!(rows_sec[0].ts_micros, ts_sec * 1_000_000); + assert_eq!(rows_sec[0].known_at_micros, ed_sec * 1_000_000); +} + +#[test] +fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() { + let dir = TempDirGuard::new("clobber"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let bson_path = dir.path().join("posts.bson"); + write_bytes( + &bson_path, + &make_post_doc( + &fields, + "CEO_RY", + "sp-1", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "hi", + ), + ); + + // 1. Pre-existing events/year=2024/part.parquet with sentinel bytes + let out_a = dir.path().join("out_existing_parquet"); + let year_2024 = out_a.join("events/year=2024"); + fs::create_dir_all(&year_2024).unwrap(); + let sentinel_path = year_2024.join("part.parquet"); + let sentinel_bytes = b"SENTINEL-FILINGS-EARNINGS-EVENTS-PARQUET".to_vec(); + write_bytes(&sentinel_path, &sentinel_bytes); + + let args_a = default_args( + bson_path.clone(), + map_path.clone(), + out_a.clone(), + CeoPostsTimestampUnit::Millis, + ); + let err = run_curate_posts(&args_a).unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EventsDatasetExists { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("year=2024"), "expected year=2024 in {msg}"); + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); + let entries: Vec<_> = fs::read_dir(out_a.join("events")) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 1); + + // 2. Pre-existing year=* directory without a Parquet file must also fail closed + let out_b = dir.path().join("out_empty_year_dir"); + let year_2025 = out_b.join("events/year=2025"); + fs::create_dir_all(&year_2025).unwrap(); + let args_b = default_args(bson_path, map_path, out_b.clone(), CeoPostsTimestampUnit::Millis); + let err = run_curate_posts(&args_b).unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EventsDatasetExists { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("year=2025"), "expected year=2025 in {msg}"); + assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0); +} + +#[test] +fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() { + let dir = TempDirGuard::new("fail-closed"); + let out_dir = dir.path().join("out"); + fs::create_dir_all(&out_dir).unwrap(); + let marker = out_dir.join("keep.txt"); + let marker_bytes = b"DO-NOT-TOUCH".to_vec(); + write_bytes(&marker, &marker_bytes); + + let assert_out_untouched = || { + assert!(!out_dir.join("events").exists(), "events dir must not be created"); + assert_eq!(fs::read(&marker).unwrap(), marker_bytes); + let entries: Vec<_> = fs::read_dir(&out_dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries.len(), 1); + }; + + let valid_map = dir.path().join("valid_map.tsv"); + write_bytes(&valid_map, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + let fields = CeoPostsFieldNames::default(); + let valid_doc = make_post_doc( + &fields, + "CEO_RY", + "sp-valid", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "valid post", + ); + let valid_bson = dir.path().join("valid.bson"); + write_bytes(&valid_bson, &valid_doc); + + let base_args = default_args( + valid_bson.clone(), + valid_map.clone(), + out_dir.clone(), + CeoPostsTimestampUnit::Millis, + ); + + // 1. Invalid output paths: regular file as out_dir, empty out_dir, regular file as out/events + let file_as_out = dir.path().join("file_out"); + write_bytes(&file_as_out, b"not-a-dir"); + let err = run_curate_posts(&CuratePostsArgs { + out_dir: file_as_out.clone(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + assert_eq!(fs::read(&file_as_out).unwrap(), b"not-a-dir"); + + let err = run_curate_posts(&CuratePostsArgs { + out_dir: PathBuf::new(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + + let out_with_file_events = dir.path().join("out_file_events"); + fs::create_dir_all(&out_with_file_events).unwrap(); + write_bytes(&out_with_file_events.join("events"), b"file-not-dir"); + let err = run_curate_posts(&CuratePostsArgs { + out_dir: out_with_file_events.clone(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. })); + assert_single_line_err(&err); + assert_eq!( + fs::read(out_with_file_events.join("events")).unwrap(), + b"file-not-dir" + ); + + // 2. Blank field name + let err = run_curate_posts(&CuratePostsArgs { + key_field: " ".to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 3. Duplicate field names + let err = run_curate_posts(&CuratePostsArgs { + spiel_id_field: DEFAULT_KEY_FIELD.to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::InvalidFieldNames { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 4. Blank mapping_source + let err = run_curate_posts(&CuratePostsArgs { + mapping_source: " \t ".to_string(), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::EmptyMappingSource)); + assert_single_line_err(&err); + assert_out_untouched(); + + // 5. Missing input file + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: dir.path().join("missing.bson"), + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::OpenInput { .. })); + assert_single_line_err(&err); + assert_out_untouched(); + + // 6. Injected reader I/O error (valid doc followed by BrokenPipe) + let err = run_curate_posts_with_reader( + &valid_map, + DEFAULT_MAPPING_SOURCE, + &fields, + CeoPostsTimestampUnit::Millis, + ( + Path::new("failing.bson"), + FailingReader { + prefix: valid_doc.clone(), + pos: 0, + }, + ), + &out_dir, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::BsonStream { + source: BsonStreamError::Io { offset, .. }, + .. + } if offset == valid_doc.len() as u64 + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&valid_doc.len().to_string())); + assert_out_untouched(); + + // 7. Malformed TSV (line 2) + let bad_tsv = dir.path().join("bad.tsv"); + write_bytes( + &bad_tsv, + b"ceo\tCEO_RY\t2020-01-01\t\t101\nceo\tCEO_SHOP\tnot-a-date\t\t202\n", + ); + let err = run_curate_posts(&CuratePostsArgs { + provider_mapping: bad_tsv, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::TsvParse { line: 2, .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains(":2:"), "expected :2: in {msg}"); + assert_out_untouched(); + + // 8. Overlapping provider_mapping.tsv + let overlap_tsv = dir.path().join("overlap.tsv"); + write_bytes( + &overlap_tsv, + b"ceo\tCEO_RY\t2020-01-01\t2024-06-01\t101\nceo\tCEO_RY\t2024-06-01\t\t102\n", + ); + let err = run_curate_posts(&CuratePostsArgs { + provider_mapping: overlap_tsv, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!(err, RunCuratePostsError::ProviderMapping { .. })); + let msg = assert_single_line_err(&err); + assert!(msg.contains("CEO_RY"), "expected conflicting key in {msg}"); + assert_out_untouched(); + + // 9. Truncated BSON after valid doc + let trunc_bson = dir.path().join("trunc.bson"); + let mut trunc_bytes = valid_doc.clone(); + let trunc_offset = trunc_bytes.len() as u64; + trunc_bytes.extend_from_slice(&[30, 0, 0, 0, 0x02, b'a']); + write_bytes(&trunc_bson, &trunc_bytes); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: trunc_bson, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::BsonStream { + source: BsonStreamError::TruncatedDocument { offset, .. }, + .. + } if offset == trunc_offset + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&trunc_offset.to_string())); + assert_out_untouched(); + + // 10. Corrupt BSON element after valid doc + let corrupt_bson = dir.path().join("corrupt.bson"); + let mut corrupt_doc = RawDocumentBuf::new(); + corrupt_doc.append(cstr!("ceoId"), "CEO_RY"); + corrupt_doc.append(cstr!("z"), 1_i32); + let mut bad_doc_bytes = corrupt_doc.into_bytes(); + let z_pos = bad_doc_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .unwrap(); + bad_doc_bytes[z_pos] = 0x7e; + + let mut combined_corrupt = valid_doc.clone(); + let corrupt_offset = combined_corrupt.len() as u64; + combined_corrupt.extend_from_slice(&bad_doc_bytes); + write_bytes(&corrupt_bson, &combined_corrupt); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: corrupt_bson, + ..base_args.clone() + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::CorruptBson { offset, .. } if offset == corrupt_offset + )); + let msg = assert_single_line_err(&err); + assert!(msg.contains(&corrupt_offset.to_string())); + assert_out_untouched(); + + // 11. Curation timestamp overflow after valid doc -> late failure publishes nothing + let overflow_bson = dir.path().join("overflow.bson"); + let mut overflow_bytes = valid_doc; + overflow_bytes.extend_from_slice(&make_post_doc( + &fields, + "CEO_RY", + "sp-overflow", + i64::MAX, + None, + None, + None, + "overflow ts", + )); + write_bytes(&overflow_bson, &overflow_bytes); + let err = run_curate_posts(&CuratePostsArgs { + ceo_posts: overflow_bson, + ..base_args + }) + .unwrap_err(); + assert!(matches!( + err, + RunCuratePostsError::CurateWrite { + source: CuratePostsWriteError::Curate(CuratePostsError::Posts( + PostsError::TimestampOverflow { .. } + )), + .. + } + )); + assert_single_line_err(&err); + assert_out_untouched(); +} + +#[test] +fn empty_and_all_unmapped_inputs_return_zero_rows_without_creating_events_dir() { + let dir = TempDirGuard::new("zero-rows"); + let map_path = dir.path().join("mapping.tsv"); + write_bytes(&map_path, b"ceo\tCEO_RY\t2020-01-01\t\t101\n"); + + // 1. Empty BSON input + let empty_bson = dir.path().join("empty.bson"); + write_bytes(&empty_bson, &[]); + let out_empty = dir.path().join("out_empty"); + let rep_empty = run_curate_posts(&default_args( + empty_bson, + map_path.clone(), + out_empty.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("empty succeeds"); + assert_report_invariants(&rep_empty); + assert_eq!(rep_empty.docs_framed, 0); + assert_eq!(rep_empty.write_stats.rows_written, 0); + assert_eq!(rep_empty.write_stats.files_written, 0); + assert!(!out_empty.join("events").exists()); + + // 2. All-unmapped BSON input + let fields = CeoPostsFieldNames::default(); + let unmapped_bson = dir.path().join("unmapped.bson"); + write_bytes( + &unmapped_bson, + &make_post_doc( + &fields, + "NO_MATCH", + "sp-unmapped", + utc_ms(2024, 6, 15, 14, 0, 0), + None, + None, + None, + "unmapped", + ), + ); + let out_unmapped = dir.path().join("out_unmapped"); + let rep_unmapped = run_curate_posts(&default_args( + unmapped_bson, + map_path, + out_unmapped.clone(), + CeoPostsTimestampUnit::Millis, + )) + .expect("all-unmapped succeeds"); + assert_report_invariants(&rep_unmapped); + assert_eq!(rep_unmapped.docs_framed, 1); + assert_eq!(rep_unmapped.curate_stats.dropped_unmapped, 1); + assert_eq!(rep_unmapped.write_stats.rows_written, 0); + assert_eq!(rep_unmapped.write_stats.files_written, 0); + assert!(!out_unmapped.join("events").exists()); +}