T-115: M1.2ae — tools/curate-etl: sixth runnable command curate-events (concatenated-BSON qmFilings + qmEarnings files + provider_mapping TSV → events/year=YYYY/part.parquet) with zero-copy qmFilings / qmEarnings decoders, end-to-end tests and local benchmark (no new crates, no MongoDB connection)
This commit is contained in:
parent
c343b97e26
commit
a0d2a154f0
2 changed files with 163 additions and 19 deletions
|
|
@ -2,7 +2,7 @@
|
|||
//!
|
||||
//! Streams concatenated raw BSON `qmFilings` and `qmEarnings` dump files alongside
|
||||
//! `provider_mapping.tsv` into atomically published `<out_dir>/events/year=YYYY/part.parquet`
|
||||
//! partitions via [`curate_and_write_events`].
|
||||
//! partitions via [`curate_events`] and [`write_events_dataset`].
|
||||
//!
|
||||
//! # Contract & Point-in-Time Rules
|
||||
//! - Verified defaults match in-repo evidence (`symbol` / `timefiled` on `qmFilings`;
|
||||
|
|
@ -14,18 +14,19 @@
|
|||
//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from
|
||||
//! [`crate::run_curate_bars::load_provider_mapping_tsv`].
|
||||
//! - All decoded [`QmFiling`] and [`QmEarning`] rows are passed directly to
|
||||
//! [`curate_and_write_events`], which links same-day `8-K` / `News release` filings to
|
||||
//! [`curate_events`], which links same-day `8-K` / `News release` filings to
|
||||
//! earnings, falls back unlinked earnings to `16:05 ET`, resolves `provider_mapping` on each
|
||||
//! event's exact Eastern local calendar date (never UTC or `known_at` date), and counts
|
||||
//! unmapped keys in [`CurateEventsStats::dropped_unmapped`].
|
||||
//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_events`] /
|
||||
//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_events`] /
|
||||
//! [`write_events_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0`
|
||||
//! without creating `<out_dir>/events` or modifying any pre-existing partitions.
|
||||
//! - **Fail-closed safety:** invalid `--out` (including `--out` or `<out>/events` being a regular
|
||||
//! file, or any input path resolving to `--out` or inside `<out>/events`), invalid field names,
|
||||
//! empty `--mapping-source`, unreadable inputs, malformed/overlapping `provider_mapping.tsv`,
|
||||
//! and truncated/corrupt BSON framing or element bytes return a typed [`RunCurateEventsError`]
|
||||
//! before touching `args.out_dir`.
|
||||
//! file, any input path resolving to `--out` or inside `<out>/events`, or a destination
|
||||
//! `year=YYYY` partition directory symlink resolving a `part.parquet` output onto an input),
|
||||
//! invalid field names, empty `--mapping-source`, unreadable inputs, malformed/overlapping
|
||||
//! `provider_mapping.tsv`, and truncated/corrupt BSON framing or element bytes return a typed
|
||||
//! [`RunCurateEventsError`] before touching `args.out_dir`.
|
||||
//!
|
||||
//! # Counter Conservation Invariants
|
||||
//! Every successful [`CurateEventsRunReport`] satisfies:
|
||||
|
|
@ -36,7 +37,7 @@
|
|||
//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + 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::File;
|
||||
|
|
@ -53,10 +54,8 @@ use crate::bson_stream::{
|
|||
decode_qm_earnings_chunks, decode_qm_filings_chunks, BsonQmEventsStreamError, BsonStreamError,
|
||||
BsonStreamOptions, RawBsonChunkReader,
|
||||
};
|
||||
use crate::curate_events::{
|
||||
curate_and_write_events, curate_events, CurateEventsStats, CurateEventsWriteError,
|
||||
};
|
||||
use crate::events::{QmEarning, QmFiling};
|
||||
use crate::curate_events::{curate_events, CurateEventsStats, CurateEventsWriteError};
|
||||
use crate::events::{partition_year_utc, QmEarning, QmFiling};
|
||||
use crate::parquet_events::{
|
||||
write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats,
|
||||
};
|
||||
|
|
@ -345,6 +344,62 @@ fn validate_out_dir_and_inputs(args: &CurateEventsArgs) -> Result<(), RunCurateE
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks each destination `year=YYYY` partition directory and its `part.parquet` path against
|
||||
/// all resolved input paths before publishing.
|
||||
///
|
||||
/// This catches symlinked year directories (e.g. `<out>/events/year=2025 -> /external/dir`)
|
||||
/// whose resolved target lies outside `<out>/events` and would otherwise let `write_events_dataset`
|
||||
/// overwrite an input located at `/external/dir/part.parquet`.
|
||||
fn validate_partition_outputs_and_inputs(
|
||||
args: &CurateEventsArgs,
|
||||
rows: &[EventsParquetRow],
|
||||
) -> Result<(), RunCurateEventsError> {
|
||||
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 = [
|
||||
("qm-filings", &args.qm_filings, resolve_normalized_path(&args.qm_filings)),
|
||||
("qm-earnings", &args.qm_earnings, resolve_normalized_path(&args.qm_earnings)),
|
||||
(
|
||||
"provider-mapping",
|
||||
&args.provider_mapping,
|
||||
resolve_normalized_path(&args.provider_mapping),
|
||||
),
|
||||
];
|
||||
|
||||
let events_dir = args.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("part.parquet");
|
||||
let resolved_part = resolve_normalized_path(&year_dir.join("part.parquet"));
|
||||
|
||||
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
|
||||
{
|
||||
return Err(RunCurateEventsError::InvalidOutDir {
|
||||
path: year_dir,
|
||||
detail: format!(
|
||||
"partition output '{}' would overlap {label} input '{}'",
|
||||
resolved_part_via_dir.display(),
|
||||
input_path.display()
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateEventsError {
|
||||
match err {
|
||||
RunCurateBarsError::OpenInput {
|
||||
|
|
@ -530,7 +585,8 @@ fn decode_all_inputs(args: &CurateEventsArgs) -> Result<DecodedEventsInputs, Run
|
|||
})
|
||||
}
|
||||
|
||||
/// Runs the end-to-end `curate-events` file-to-Parquet pipeline via [`curate_and_write_events`].
|
||||
/// Runs the end-to-end `curate-events` file-to-Parquet pipeline via [`curate_events`] and
|
||||
/// [`write_events_dataset`].
|
||||
///
|
||||
/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before
|
||||
/// touching `args.out_dir`, leaving any pre-existing `<out_dir>/events/` partitions
|
||||
|
|
@ -543,19 +599,27 @@ pub fn run_curate_events(
|
|||
|
||||
let decoded = decode_all_inputs(args)?;
|
||||
|
||||
let write_report = curate_and_write_events(
|
||||
&args.out_dir,
|
||||
let curated = curate_events(
|
||||
decoded.filings,
|
||||
decoded.earnings,
|
||||
&args.mapping_source,
|
||||
&decoded.mapping,
|
||||
EventsWriteOptions::default(),
|
||||
)
|
||||
.map_err(|source| RunCurateEventsError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source,
|
||||
source: CurateEventsWriteError::Curate(source),
|
||||
})?;
|
||||
|
||||
validate_partition_outputs_and_inputs(args, &curated.rows)?;
|
||||
|
||||
let write_stats =
|
||||
write_events_dataset(&args.out_dir, &curated.rows, EventsWriteOptions::default()).map_err(
|
||||
|source| RunCurateEventsError::CurateWrite {
|
||||
out_dir: args.out_dir.clone(),
|
||||
source: CurateEventsWriteError::Parquet(source),
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(CurateEventsRunReport {
|
||||
filings_docs_framed: decoded.filings_docs_framed,
|
||||
filings_bytes_read: decoded.filings_bytes_read,
|
||||
|
|
@ -565,8 +629,8 @@ pub fn run_curate_events(
|
|||
earnings_bytes_read: decoded.earnings_bytes_read,
|
||||
earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes,
|
||||
earnings_decode: decoded.earnings_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(),
|
||||
})
|
||||
}
|
||||
|
|
@ -625,6 +689,8 @@ pub(crate) fn run_curate_events_timed(
|
|||
})?;
|
||||
let curate_elapsed_secs = curate_start.elapsed().as_secs_f64();
|
||||
|
||||
validate_partition_outputs_and_inputs(args, &curated.rows)?;
|
||||
|
||||
let checksum = compute_rows_checksum(&curated.rows);
|
||||
|
||||
let write_start = Instant::now();
|
||||
|
|
|
|||
|
|
@ -678,6 +678,84 @@ fn symlink_followed_by_parent_dir_into_events_output_is_rejected_without_modifyi
|
|||
assert_eq!(fs::read(&real_input).unwrap(), filing_bytes);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_year_partition_directory_overlapping_input_is_rejected_without_modifying_input() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let tmp = TempDirGuard::new("symlink_year_dir_clobber");
|
||||
let dir = tmp.path();
|
||||
|
||||
fs::write(
|
||||
dir.join("provider_mapping.tsv"),
|
||||
"qm\tAAPL\t2020-01-01\t\t101\n",
|
||||
)
|
||||
.unwrap();
|
||||
let valid_filing = rawdoc! {
|
||||
"symbol": "AAPL",
|
||||
"timefiled": "2025-02-10 16:30:00 EST",
|
||||
"formType": "10-K",
|
||||
};
|
||||
let filing_bytes = valid_filing.as_bytes().to_vec();
|
||||
let valid_earning = rawdoc! {
|
||||
"qmSearchCode": "AAPL",
|
||||
"reportDate": "2025-02-10",
|
||||
"announceTime": "AMC",
|
||||
};
|
||||
fs::write(dir.join("qmEarnings.bson"), valid_earning.as_bytes()).unwrap();
|
||||
|
||||
// Case 1: `<out>/events/year=2025` is a symlink to an external directory whose `part.parquet`
|
||||
// is passed as `--qm-filings`.
|
||||
let external_dir = dir.join("external_inputs");
|
||||
fs::create_dir_all(&external_dir).unwrap();
|
||||
let external_part = external_dir.join("part.parquet");
|
||||
fs::write(&external_part, &filing_bytes).unwrap();
|
||||
|
||||
let events_dir = dir.join("out/events");
|
||||
fs::create_dir_all(&events_dir).unwrap();
|
||||
symlink(&external_dir, events_dir.join("year=2025")).unwrap();
|
||||
|
||||
let mut args = default_args(dir);
|
||||
args.qm_filings = external_part.clone();
|
||||
|
||||
let err = run_curate_events(&args).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, RunCurateEventsError::InvalidOutDir { .. }),
|
||||
"expected InvalidOutDir for symlinked year=2025 overlapping input, got: {err:?}"
|
||||
);
|
||||
assert!(!err.to_string().contains('\n'));
|
||||
assert_eq!(
|
||||
fs::read(&external_part).unwrap(),
|
||||
filing_bytes,
|
||||
"external input bytes must remain untouched"
|
||||
);
|
||||
|
||||
let timed_err = run_curate_events_timed(&args).unwrap_err();
|
||||
assert!(
|
||||
matches!(timed_err, RunCurateEventsError::InvalidOutDir { .. }),
|
||||
"expected InvalidOutDir from timed runner, got: {timed_err:?}"
|
||||
);
|
||||
assert_eq!(fs::read(&external_part).unwrap(), filing_bytes);
|
||||
|
||||
// Case 2: `<out>/events/year=2025` is a real directory, but `part.parquet` inside it is a
|
||||
// symlink pointing to an external input file.
|
||||
fs::remove_file(events_dir.join("year=2025")).unwrap();
|
||||
let real_year_dir = events_dir.join("year=2025");
|
||||
fs::create_dir_all(&real_year_dir).unwrap();
|
||||
let external_bson = external_dir.join("qmFilings.bson");
|
||||
fs::write(&external_bson, &filing_bytes).unwrap();
|
||||
symlink(&external_bson, real_year_dir.join("part.parquet")).unwrap();
|
||||
|
||||
args.qm_filings = external_bson.clone();
|
||||
let err = run_curate_events(&args).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, RunCurateEventsError::InvalidOutDir { .. }),
|
||||
"expected InvalidOutDir for symlinked part.parquet overlapping input, got: {err:?}"
|
||||
);
|
||||
assert!(!err.to_string().contains('\n'));
|
||||
assert_eq!(fs::read(&external_bson).unwrap(), filing_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_inputs_return_ok_without_creating_events_dir() {
|
||||
let tmp = TempDirGuard::new("empty");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue