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:43:07 -05:00
parent d999ebe595
commit 3515ef487b
2 changed files with 209 additions and 20 deletions

View file

@ -45,10 +45,10 @@
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::fmt::{self, Write as _};
use std::fs::{self, File};
use std::io;
use std::path::{Path, PathBuf};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
@ -171,54 +171,86 @@ pub enum RunCuratePostsError {
},
}
struct SingleLineWriter<'a, 'b> {
f: &'a mut fmt::Formatter<'b>,
}
impl fmt::Write for SingleLineWriter<'_, '_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let mut rest = s;
while let Some(idx) = rest.find(['\n', '\r']) {
let (head, tail) = rest.split_at(idx);
if !head.is_empty() {
self.f.write_str(head)?;
}
let mut chars = tail.chars();
match chars.next() {
Some('\n') => self.f.write_str("\\n")?,
Some('\r') => self.f.write_str("\\r")?,
_ => unreachable!(),
}
rest = chars.as_str();
}
if !rest.is_empty() {
self.f.write_str(rest)?;
}
Ok(())
}
}
impl fmt::Display for RunCuratePostsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut w = SingleLineWriter { f };
match self {
Self::InvalidOutDir { path, detail } => {
write!(f, "invalid --out '{}': {detail}", path.display())
write!(w, "invalid --out '{}': {detail}", path.display())
}
Self::InspectOutDir { path, source } => {
write!(f, "failed to inspect output path '{}': {source}", path.display())
write!(
w,
"failed to inspect output path '{}': {source}",
path.display()
)
}
Self::EventsDatasetExists { path } => write!(
f,
w,
"refusing to overwrite existing events partition '{}': use a dedicated --out directory for ceoPosts",
path.display()
),
Self::InvalidFieldNames { source } => write!(f, "{source}"),
Self::InvalidFieldNames { source } => write!(w, "{source}"),
Self::EmptyMappingSource => {
write!(f, "invalid --mapping-source: must not be empty or blank")
write!(w, "invalid --mapping-source: must not be empty or blank")
}
Self::OpenInput {
label,
path,
source,
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
} => write!(w, "failed to open {label} '{}': {source}", path.display()),
Self::ReadInput {
label,
path,
source,
} => write!(f, "failed to read {label} '{}': {source}", path.display()),
} => write!(w, "failed to read {label} '{}': {source}", path.display()),
Self::TsvParse { path, line, detail } => {
write!(f, "{}:{line}: {detail}", path.display())
write!(w, "{}:{line}: {detail}", path.display())
}
Self::ProviderMapping { path, source } => {
write!(f, "invalid provider_mapping '{}': {source}", path.display())
write!(w, "invalid provider_mapping '{}': {source}", path.display())
}
Self::BsonStream { path, source } => {
write!(f, "failed reading ceo-posts '{}': {source}", path.display())
write!(w, "failed reading ceo-posts '{}': {source}", path.display())
}
Self::CorruptBson {
path,
offset,
source,
} => write!(
f,
w,
"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())
write!(w, "curate/write to '{}' failed: {source}", out_dir.display())
}
}
}
@ -250,6 +282,51 @@ 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.
let mut prefix = PathBuf::new();
let mut saw_missing = false;
for component in out_dir.components() {
match component {
Component::ParentDir => {
if saw_missing {
return Err(RunCuratePostsError::InvalidOutDir {
path: out_dir.to_path_buf(),
detail: "output path must not contain '..' after a missing component"
.to_string(),
});
}
prefix.push(component);
}
Component::CurDir => {
if !saw_missing {
prefix.push(component);
}
}
Component::RootDir | Component::Prefix(_) => {
prefix.push(component);
}
Component::Normal(_) => {
prefix.push(component);
if !saw_missing {
match fs::metadata(&prefix) {
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {
saw_missing = true;
}
Err(source) => {
return Err(RunCuratePostsError::InspectOutDir {
path: prefix,
source,
});
}
}
}
}
}
}
match fs::metadata(out_dir) {
Ok(meta) if !meta.is_dir() => {
return Err(RunCuratePostsError::InvalidOutDir {

View file

@ -277,7 +277,7 @@ 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'),
!msg.contains('\n') && !msg.contains('\r'),
"error message must be single-line, got: {msg:?}"
);
msg
@ -286,6 +286,7 @@ fn assert_single_line_err(err: &RunCuratePostsError) -> String {
struct FailingReader {
prefix: Vec<u8>,
pos: usize,
error_message: String,
}
impl Read for FailingReader {
@ -298,7 +299,7 @@ impl Read for FailingReader {
}
Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"injected read failure",
self.error_message.clone(),
))
}
}
@ -695,6 +696,70 @@ fn clobber_guard_rejects_existing_year_partitions_and_preserves_bytes() {
assert_eq!(fs::read_dir(&year_2025).unwrap().count(), 0);
}
#[test]
fn clobber_guard_rejects_parent_dir_after_missing_component_and_preserves_tree() {
let dir = TempDirGuard::new("clobber-parent-dir");
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",
),
);
// Seed exports/shared/events/year=2024/part.parquet while exports/scratch is absent.
let exports_dir = dir.path().join("exports");
let shared_dir = exports_dir.join("shared");
let year_2024 = shared_dir.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-2024".to_vec();
write_bytes(&sentinel_path, &sentinel_bytes);
let bypass_out = exports_dir.join("scratch").join("..").join("shared");
assert!(!exports_dir.join("scratch").exists());
let args = default_args(
bson_path,
map_path,
bypass_out,
CeoPostsTimestampUnit::Millis,
);
let err = run_curate_posts(&args).unwrap_err();
assert!(matches!(err, RunCuratePostsError::InvalidOutDir { .. }));
let msg = assert_single_line_err(&err);
assert!(msg.contains(".."), "expected '..' detail in {msg}");
// The missing scratch component must not have been created, and the target partition
// and surrounding directory tree must be completely unchanged.
assert!(!exports_dir.join("scratch").exists());
assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes);
let list_names = |p: &Path| -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(p)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
};
assert_eq!(list_names(&exports_dir), vec!["shared"]);
assert_eq!(list_names(&shared_dir), vec!["events"]);
assert_eq!(list_names(&shared_dir.join("events")), vec!["year=2024"]);
assert_eq!(list_names(&year_2024), vec!["part.parquet"]);
}
#[test]
fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() {
let dir = TempDirGuard::new("fail-closed");
@ -813,7 +878,8 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() {
assert_single_line_err(&err);
assert_out_untouched();
// 6. Injected reader I/O error (valid doc followed by BrokenPipe)
// 6. Injected reader I/O error (valid doc followed by multiline BrokenPipe)
let multiline_cause = "decompression failed\ncaused by: corrupt zstd frame\r\nstream aborted";
let err = run_curate_posts_with_reader(
&valid_map,
DEFAULT_MAPPING_SOURCE,
@ -824,6 +890,48 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() {
FailingReader {
prefix: valid_doc.clone(),
pos: 0,
error_message: multiline_cause.to_string(),
},
),
&out_dir,
)
.unwrap_err();
match &err {
RunCuratePostsError::BsonStream {
source: BsonStreamError::Io { offset, source },
..
} => {
assert_eq!(*offset, valid_doc.len() as u64);
// Typed cause is preserved intact.
assert_eq!(source.kind(), io::ErrorKind::BrokenPipe);
assert_eq!(source.to_string(), multiline_cause);
}
other => panic!("expected BsonStream::Io, got {other:?}"),
}
let msg = assert_single_line_err(&err);
assert!(msg.contains("failing.bson"), "expected path in {msg}");
assert!(
msg.contains(&valid_doc.len().to_string()),
"expected byte offset in {msg}"
);
assert!(
msg.contains("decompression failed\\ncaused by: corrupt zstd frame\\r\\nstream aborted"),
"expected escaped multiline cause in {msg}"
);
assert_out_untouched();
// 6b. Path containing a newline is also escaped to a single line
let err = run_curate_posts_with_reader(
&valid_map,
DEFAULT_MAPPING_SOURCE,
&fields,
CeoPostsTimestampUnit::Millis,
(
Path::new("dir/bad\nname.bson"),
FailingReader {
prefix: Vec::new(),
pos: 0,
error_message: "boom\nline2".to_string(),
},
),
&out_dir,
@ -832,12 +940,16 @@ fn fail_closed_errors_are_typed_single_line_and_leave_out_dir_untouched() {
assert!(matches!(
err,
RunCuratePostsError::BsonStream {
source: BsonStreamError::Io { offset, .. },
source: BsonStreamError::Io { offset: 0, .. },
..
} if offset == valid_doc.len() as u64
}
));
let msg = assert_single_line_err(&err);
assert!(msg.contains(&valid_doc.len().to_string()));
assert!(
msg.contains("dir/bad\\nname.bson"),
"expected escaped path in {msg}"
);
assert!(msg.contains("boom\\nline2"), "expected escaped cause in {msg}");
assert_out_untouched();
// 7. Malformed TSV (line 2)