T-209: M2.2u — Fix ceoPosts event kind ('ceo_post') and co-publish under <curatedRoot>/events

This commit is contained in:
Studio 2026-12-04 14:15:52 -05:00
parent 436616b343
commit 035d18bfad
15 changed files with 1213 additions and 250 deletions

View file

@ -1,16 +1,14 @@
//! File-to-file `curate-posts` runner (`M2.2i`).
//! File-to-file `curate-posts` runner (`M2.2i` / `M2.2u`).
//!
//! 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`].
//! atomically published `<out_dir>/events/year=YYYY/part-posts.parquet` dataset via
//! [`curate_posts`] and [`write_posts_events_dataset`].
//!
//! # 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.
//! # Co-Publication with `curate-events`
//! [`crate::run_curate_events`] (filings + earnings) writes `<out_dir>/events/year=YYYY/part.parquet`
//! and this runner writes `<out_dir>/events/year=YYYY/part-posts.parquet` (`kind = "ceo_post"`).
//! Both share `<out_dir>/events/.write.lock` and remain independently re-runnable in the same
//! `curatedRoot` without clobbering each other's partition files.
//!
//! # Contract & Point-in-Time Rules
//! - Field names are supplied via [`CuratePostsArgs`] (validated via
@ -30,10 +28,10 @@
//! [`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`.
//! - **Fail-closed safety:** invalid `out_dir`, input-output path overlap, 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:
@ -43,7 +41,7 @@
//! - `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::collections::{BTreeSet, HashSet};
use std::error::Error;
use std::fmt::{self, Write as _};
use std::fs::{self, File};
@ -59,8 +57,12 @@ 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::curate_posts::{curate_posts, CuratePostsStats, CuratePostsWriteError};
use crate::events::partition_year_utc;
use crate::parquet_events::{
write_posts_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
POSTS_PART_FILE_NAME,
};
use crate::posts::CeoPost;
use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable};
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
@ -130,9 +132,6 @@ pub enum RunCuratePostsError {
path: PathBuf,
source: io::Error,
},
EventsDatasetExists {
path: PathBuf,
},
InvalidFieldNames {
source: BsonCeoPostsError,
},
@ -212,11 +211,6 @@ impl fmt::Display for RunCuratePostsError {
path.display()
)
}
Self::EventsDatasetExists { path } => write!(
w,
"refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts",
path.display()
),
Self::InvalidFieldNames { source } => write!(w, "{source}"),
Self::EmptyMappingSource => {
write!(w, "invalid --mapping-source: must not be empty or blank")
@ -266,15 +260,66 @@ impl Error for RunCuratePostsError {
Self::BsonStream { source, .. } => Some(source),
Self::CorruptBson { source, .. } => Some(source),
Self::CurateWrite { source, .. } => Some(source),
Self::InvalidOutDir { .. }
| Self::EventsDatasetExists { .. }
| Self::EmptyMappingSource
| Self::TsvParse { .. } => None,
Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None,
}
}
}
fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePostsError> {
/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..`
/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked
/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically
/// normalizing `..` within any non-existent suffix.
fn resolve_normalized_path(path: &Path) -> PathBuf {
if let Ok(canon) = path.canonicalize() {
return canon;
}
let abs = if path.is_absolute() {
path.to_path_buf()
} else if let Ok(cwd) = std::env::current_dir() {
cwd.join(path)
} else {
path.to_path_buf()
};
if let Ok(canon) = abs.canonicalize() {
return canon;
}
let mut resolved = PathBuf::new();
for comp in abs.components() {
match comp {
Component::Prefix(prefix) => resolved.push(prefix.as_os_str()),
Component::RootDir => resolved.push(Component::RootDir.as_os_str()),
Component::CurDir => {}
Component::Normal(seg) => {
resolved.push(seg);
if let Ok(canon) = resolved.canonicalize() {
resolved = canon;
}
}
Component::ParentDir => {
resolved.push(Component::ParentDir.as_os_str());
if let Ok(canon) = resolved.canonicalize() {
resolved = canon;
} else {
resolved.pop();
if matches!(resolved.components().next_back(), Some(Component::Normal(_))) {
resolved.pop();
}
}
}
}
}
resolved
}
fn validate_out_dir_and_inputs(
out_dir: &Path,
ceo_posts_path: &Path,
provider_mapping_path: &Path,
) -> Result<(), RunCuratePostsError> {
if out_dir.as_os_str().is_empty() {
return Err(RunCuratePostsError::InvalidOutDir {
path: out_dir.to_path_buf(),
@ -283,8 +328,7 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost
}
// Reject `..` after a missing path component: `fs::metadata` reports `NotFound` for the
// unresolved path, but `create_dir_all` would create the missing component and then traverse
// `..` into an existing directory, bypassing the events clobber guard.
// unresolved path, while `create_dir_all` would create the missing component and traverse `..`.
let mut prefix = PathBuf::new();
let mut saw_missing = false;
for component in out_dir.components() {
@ -327,6 +371,7 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost
}
}
let events_dir = out_dir.join("events");
match fs::metadata(out_dir) {
Ok(meta) if !meta.is_dir() => {
return Err(RunCuratePostsError::InvalidOutDir {
@ -334,8 +379,23 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost
detail: "path exists and is not a directory".to_string(),
});
}
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
Ok(_) => 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 => {}
Err(source) => {
return Err(RunCuratePostsError::InspectOutDir {
path: events_dir,
source,
});
}
},
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(source) => {
return Err(RunCuratePostsError::InspectOutDir {
path: out_dir.to_path_buf(),
@ -344,51 +404,89 @@ fn validate_out_dir_and_events_guard(out_dir: &Path) -> Result<(), RunCuratePost
}
}
let events_dir = out_dir.join("events");
match fs::metadata(&events_dir) {
Ok(meta) if !meta.is_dir() => {
let resolved_out = resolve_normalized_path(out_dir);
let resolved_events = resolve_normalized_path(&events_dir);
for (label, input_path) in [
("ceo-posts", ceo_posts_path),
("provider-mapping", provider_mapping_path),
] {
let resolved_in = resolve_normalized_path(input_path);
if resolved_in == resolved_out
|| resolved_in == resolved_events
|| resolved_in.starts_with(&resolved_events)
{
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,
path: out_dir.to_path_buf(),
detail: format!(
"output directory would overlap {label} input '{}'",
input_path.display()
),
});
}
}
let entries = fs::read_dir(&events_dir).map_err(|source| RunCuratePostsError::InspectOutDir {
path: events_dir.clone(),
source,
})?;
Ok(())
}
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)
/// Checks each destination `year=YYYY` partition directory and its `part-posts.parquet` path
/// against all resolved input paths before publishing.
///
/// Catches symlinked year directories (e.g. `<out>/events/year=2024 -> /external/dir`) whose
/// resolved target lies outside `<out>/events` and would otherwise let
/// `write_posts_events_dataset` overwrite an input located at `/external/dir/part-posts.parquet`.
fn validate_partition_outputs_and_inputs(
out_dir: &Path,
ceo_posts_path: &Path,
provider_mapping_path: &Path,
rows: &[EventsParquetRow],
) -> Result<(), RunCuratePostsError> {
if rows.is_empty() {
return Ok(());
}
let mut years = BTreeSet::new();
for row in rows {
years.insert(partition_year_utc(row.ts_micros));
}
let resolved_inputs = [
(
"ceo-posts",
ceo_posts_path,
resolve_normalized_path(ceo_posts_path),
),
(
"provider-mapping",
provider_mapping_path,
resolve_normalized_path(provider_mapping_path),
),
];
let events_dir = out_dir.join("events");
for year in years {
let year_dir = events_dir.join(format!("year={year:04}"));
let resolved_year_dir = resolve_normalized_path(&year_dir);
let resolved_part_via_dir = resolved_year_dir.join(POSTS_PART_FILE_NAME);
let resolved_part = resolve_normalized_path(&year_dir.join(POSTS_PART_FILE_NAME));
for (label, input_path, resolved_in) in &resolved_inputs {
if *resolved_in == resolved_year_dir
|| *resolved_in == resolved_part_via_dir
|| *resolved_in == resolved_part
{
existing_year_entry = Some(candidate);
return Err(RunCuratePostsError::InvalidOutDir {
path: year_dir,
detail: format!(
"partition output '{}' would overlap {label} input '{}'",
resolved_part_via_dir.display(),
input_path.display()
),
});
}
}
}
if let Some(path) = existing_year_entry {
return Err(RunCuratePostsError::EventsDatasetExists { path });
}
Ok(())
}
@ -545,7 +643,7 @@ where
F: FnOnce() -> Result<R, RunCuratePostsError>,
{
let start = Instant::now();
validate_out_dir_and_events_guard(out_dir)?;
validate_out_dir_and_inputs(out_dir, ceo_posts_path, provider_mapping_path)?;
let decoded = decode_inputs_from_opener(
provider_mapping_path,
@ -556,28 +654,37 @@ where
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,
let curated = curate_posts(decoded.posts, mapping_source, &decoded.mapping).map_err(|err| {
RunCuratePostsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source: CuratePostsWriteError::Curate(err),
}
})?;
// Re-check output directory and per-year partition overlap immediately before writing.
validate_out_dir_and_inputs(out_dir, ceo_posts_path, provider_mapping_path)?;
validate_partition_outputs_and_inputs(
out_dir,
ceo_posts_path,
provider_mapping_path,
&curated.rows,
)?;
let write_stats =
write_posts_events_dataset(out_dir, &curated.rows, EventsWriteOptions::default()).map_err(
|err| RunCuratePostsError::CurateWrite {
out_dir: out_dir.to_path_buf(),
source: CuratePostsWriteError::Parquet(err),
},
)?;
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,
curate_stats: curated.stats,
write_stats,
elapsed_secs: start.elapsed().as_secs_f64(),
})
}